[TIP] Unittesting command line scripts with unittest2?

holger krekel holger at merlinux.eu
Thu Jul 29 02:05:08 PDT 2010

On Thu, Jul 29, 2010 at 00:35 -0400, Jorge Vargas wrote:
> On Thu, Jul 29, 2010 at 12:09 AM, Jorge Vargas <jorge.vargas at gmail.com> wrote:
> > On Wed, Jul 28, 2010 at 6:31 PM, holger krekel <holger at merlinux.eu> wrote:
> >> On Wed, Jul 28, 2010 at 18:10 -0400, Jorge Vargas wrote:
> >>
> > Right now I'm having troubles with the stdout replacement, as it's
> > swallowing up the coverage report :)
> >
> > Seems like tearDown is called after the coverage report, because I get
> > the dots and the ok/failure message.
> >
> I believe the following code should do it right.
> http://paste.ofcode.org/bVdw7bcu74VhaAtaAk33KM
> it
> a- stores a copy of stdout/stderr, so you can assert against it after
> calling made and it echos back to the terminal
> b- it restores the original values just in case something else needs them.
> And I haven't added Holger's suggesting of doing main(args=None) which
> I think it's a good idea.

Seeing your capturing code - here is how the test file would
look like with py.test[0]:

    from <yourpackage> import main

    def test_status(capfd):
        out, err = capfd.readouterr()
        assert '.... ok' in out 

This you can run with::

    py.test test_file.py        # to run the test 
    py.test --pdb test_file.py  # to drop into pdb on failures
    py.test --figleaf test_file.py # coverage, requires pytest-figleaf plugin

The 'capfd' resource will take care for correctly capturing/uncapturing;
it is a helper object created for the test function invocation, discovered
by its name.  There also is e.g. 'tmpdir' you can specify which will create 
a unique temporary directory path for your test function invocation.  


[0] website and more info at http://pytest.org 


More information about the testing-in-python mailing list