0

I'd like to run specific tests in pytest with dynamically added CLI arguments, i.e:

class TestHyperML:
    def some_test(self):
        # Setup some CLI argument such as --some_arg 3 -- some_other_arg 12
        my_class = SomeClass()

class SomeClass:
    def parse_cli_arguments(self):
        # here I want to fetch my arguments in sys.argv.
        parameters = {}
        name = None
        for x in sys.argv[1:]:
            if name:
                parameters[name] = {'default': ast.literal_eval(x)}
                name = None
    
            elif x.startswith('-'):
                name = x.lstrip('-')
    
        return parameters

I understand there is a way to do that programatically by running pytest test_something.py --somearg, but I would like to do that programatically from inside the test.

Is it possible ? Thanks !

Jeyekomon
  • 2,878
  • 2
  • 27
  • 37
jhagege
  • 1,486
  • 3
  • 22
  • 36
  • I am not sure if your test has anything to do with arguments at all. Can you give a more specific, actual example? – Nils Werner Jul 11 '18 at 09:10
  • @NilsWerner Just modified example to be more concrete. – jhagege Jul 11 '18 at 09:13
  • But your code doesn't explain **why you want to access the arguments** – Nils Werner Jul 11 '18 at 09:14
  • Hope this makes it clearer this time :) – jhagege Jul 11 '18 at 10:12
  • 1
    Possible duplicate of [How do I set sys.argv so I can unit test it?](https://stackoverflow.com/questions/18668947/how-do-i-set-sys-argv-so-i-can-unit-test-it) – Nils Werner Jul 11 '18 at 10:16
  • or even better [pytest: setting command line arguments for main function tests](https://stackoverflow.com/questions/43390053/pytest-setting-command-line-arguments-for-main-function-tests/43390054) – Nils Werner Jul 11 '18 at 10:17
  • Thanks for your help, posted an answer of my solution combining a few of those sources. – jhagege Jul 11 '18 at 11:06
  • Possible duplicate of [pytest: setting command line arguments for main function tests](https://stackoverflow.com/questions/43390053/pytest-setting-command-line-arguments-for-main-function-tests) – phd Jul 11 '18 at 15:33

1 Answers1

0

Thanks to answers posted above, and similar SO questions, here is the solution that I used:

import mock

def test_parsing_cli_arguments(self):
    args = 'main.py --my_param 1e-07 --my_other_param 2'.split()
    with mock.patch('sys.argv', args):
        parser = ConfigParser("config.yaml")
        # Inside parser, sys.argv will contain the arguments set here.
jhagege
  • 1,486
  • 3
  • 22
  • 36
  • 1
    Feel free to accept your own answer if it solved your problem! This lets others know that the question is resolved so that they don't come across it (e.g. in the Linked section) and think help is still needed. – Nathan Feb 21 '19 at 16:18