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")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With