[TIP] Unittesting command line scripts with unittest2?

Michael Foord fuzzyman at voidspace.org.uk
Wed Jul 28 14:38:44 PDT 2010

On 28/07/2010 21:59, Jorge Vargas wrote:
> I started writing some tests using this skeleton.
> http://paste.ofcode.org/wr4JtC36nsMEWUVYPdSqj2
> That is doing two things
> 1- silencing the print statements as well as the subprocess calls
> 2- giving me a variable to test the output.
I'm afraid I don't understand what you are wanting to do. Is main() in 
that code unittest2.main() ?

I don't think that replacing sys.stdout will silence the output of 
subprocesses. The subprocess module itself has ways of collecting output 
> So I have two questions, is this a good approach? is there a better
> way? perhaps it should be abstracted into a separate module, maybe a
> unittest2 plugin?
> Also Today I realized there is something wrong with this approach. I'm
> messing around with sys.argv which when called as `unit2 discover`
> gives some troubles. In fact after upgrading to the plugins branch of
> unittest2 I realized my tests are broken as sys.argv[1] will give an
> error. I assume this is a side effect for getopt which was removed in
> http://hg.python.org/unittest2/rev/0190b218cf49 therefore this is a
> minor incompatibility between unittest2-0.5.1 and tip.

sys.argv will contain whatever the *original* test runner script was 
called with. None of the unittest2 code modifies sys.argv and I don't 
think that has changed since I stopped using getopt. If your tests 
depend on the contents of sys.argv you can set or modify the list. (At 
least I'm pretty sure I don't mutate sys.argv - I would consider that 
bad practise, feel free to point it out if I am but a cursory glance 
doesn't show anything.)

There is a difference in the plugins branch: calling unit2 on its own 
(no args) will launch test discovery (equivalent of `unit2 discover`), 
in this case there will be no sys.argv[1]. Could this be what has happened?

All the best,

Michael Foord

> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python


READ CAREFULLY. By accepting and reading this email you agree, on behalf of your employer, to release me from all obligations and waivers arising from any and all NON-NEGOTIATED agreements, licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap, confidentiality, non-disclosure, non-compete and acceptable use policies (”BOGUS AGREEMENTS”) that I have entered into with your employer, its partners, licensors, agents and assigns, in perpetuity, without prejudice to my ongoing rights and privileges. You further represent that you have the authority to release me from any BOGUS AGREEMENTS on behalf of your employer.

More information about the testing-in-python mailing list