views:

540

answers:

2

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()
+5  A: 

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 pas 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).

Alex Martelli
great, thanks; just to confirm: first allow optparse to handle the (possibly multiple and variable) app options, then delete them from sys.argv, and finally allow unittest to take over?
jd
@jd yep, that's the gist of it!
Alex Martelli
Brilliant, thanks Alex! I couldn't work this out at all :P
Skilldrick
but what do you do if you want to pass arguments to unittest.main()?
Matt Joiner
@Matt, set `sys.argv` to have exactly those args you want `unittest.main` to parse -- no more, no less.
Alex Martelli
A: 

You should not take arguments and options to run unittests, as you make them run under different, less predictable conditions this way. You should figure out why you need to run tests with different data, and make you test suite complete enough to cover the ground of all data sets without being run differently each time.

ironfroggy
i receive weekly data reports (files); i'd like to feed these new reports to the unittests, before generating public reports. If for some reason the structure or type of the data has changed (e.g. a new column field was added, a data range changed and a bug is unveiled) I'd like to catch them with the tests. Hope this makes sense.
jd
sure but thats data validation, not unittesting.
ironfroggy