[Edu-sig] dual use __main__: work or test

David Handy david at handysoftware.com
Sat Feb 11 20:59:10 EST 2017


I often do something similar, but usually with a command-line option or sub-command to indicate whether to run tests instead of doing the normal thing, and my default is usually to do the normal thing, not run tests.
 
However, many times I'll write a module not intended for use as a stand-alone script, but put some tests in it, and put an "if __name__ ==  '__main__'" thing in there that will unconditionally run tests. Then I can run that module's using the "-m" option, which I love:
 
python -m module_name
 
The test could use doctests, or even just call a function that has code with assert statements in it. I often use this technique when "bench-testing" a module under development.
 
David H
 
 
On Saturday, February 11, 2017 7:22pm, "kirby urner" <kirby.urner at gmail.com> said:








Does anyone use this pattern?:  
(a) accept command line parameters if __name__ == "__main__" or(b) run unittests if no parameters passed

Something like:

if __name__ == "__main__":
    if len(sys.argv)==7:
        command_line()  
    else:
        unittest.main()

I'm using this pattern with my classes, as a way of touching on both passing arguments from the command line (with nod to argparse for POSIX compliance), and self-contained testing. 

Maybe this would be better with doctest instead. I could do another version....

Example:
[ https://github.com/4dsolutions/Python5/blob/master/tetravolume.py ]( https://github.com/4dsolutions/Python5/blob/master/tetravolume.py )

Kirby

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20170211/41408a17/attachment.html>


More information about the Edu-sig mailing list