I have a module that imports unittest and has some TestCases. I would like to accept some command-line options (for example below, the name of a data file), but when I try to pass the option I get the message option -i not recognized
. Is it possible to have unittest
+ provide options to the app (note: I'm using optparse
to handle the options)? Thanks.
$ python test_app_data.py -i data_1.txt option -i not recognized
=====================
follow-up: this is an implementation of the suggested solution:
import cfg_master #has the optparse option-handling code ... if __name__ == '__main__': #add you app's options here... options_tpl = ('-i', '--in_dir', '-o', '--out_dir') del_lst = [] for i,option in enumerate(sys.argv): if option in options_tpl: del_lst.append(i) del_lst.append(i+1) del_lst.reverse() for i in del_lst: del sys.argv[i] unittest.main()
Which is better – pytest or unittest? Although both the frameworks are great for performing testing in python, pytest is easier to work with. The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class.
The command to run the tests is python -m unittest filename.py . In our case, the command to run the tests is python -m unittest test_utils.py .
It is possible to pass custom command line arguments to the test module.
Building on Alex's answer, it's actually pretty easy to do using argparse
:
if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--input', default='My Input') parser.add_argument('filename', default='some_file.txt') parser.add_argument('unittest_args', nargs='*') args = parser.parse_args() # TODO: Go do something with args.input and args.filename # Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone) sys.argv[1:] = args.unittest_args unittest.main()
I haven't tested all of the flags you can pass into unittest to see if they work or not, but passing test names in does work, e.g.:
python test.py --input=foo data.txt MyTest
Runs MyTest with foo
and data.txt
.
In your if __name__ == '__main__':
section, which you're not showing us, you'll need to optparse
and then del sys.argv[1:]
before you pass control to unittest
code, so that the latter code doesn't try to interpret your command line options again when you've already dealt with them. (It's a bit harder to have some options of your own and also pass some down to unittest
, though it can be done if you do have such complex needs).
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