Setting command line arguments for main function tests

后端 未结 3 1777
我在风中等你
我在风中等你 2021-01-12 04:51

I have a main() function in python that gets command line arguments. Is there a way for me to write pytest tests for this function and define the arguments in the code?

3条回答
  •  轮回少年
    2021-01-12 05:25

    To add to the previous answers, instead of modifying sys.argv It is safer to use a context manager which can cover up and protect the underlying object. An example would be

    with unittest.mock.patch('sys.argv', ['program_name', '--option1', 'inputFile']):
        main()
    

    This works only with python3. For python2 the Mock library does the trick.

    I found this solution on a different stackoverflow post here.

提交回复
热议问题