Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting command line arguments for main function tests

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?

e.g.

def main():
    # argparse code
    args, other = arg_parser.parse_known_args()
    return args.first_arg


def test_main():
    res = main() # call with first_arg = "abc"
    assert(res == "abc")
like image 849
Dotan Avatar asked Apr 13 '17 10:04

Dotan


1 Answers

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.

like image 145
leafmeal Avatar answered Oct 04 '22 11:10

leafmeal