I have some class-based unit tests running in python's unittest2 framework. We're using Selenium WebDriver, which has a convenient save_screenshot()
method. I'd like to grab a screenshot in tearDown() for every test failure, to reduce the time spent debugging why a test failed.
However, I can't find any way to run code on test failures only. tearDown()
is called regardless of whether the test succeeds, and I don't want to clutter our filesystem with hundreds of browser screenshots for tests that succeeded.
How would you approach this?
Override
fail()
to generate the screenshot and then callTestCase.fail(self)
?sys.exc_info()
should give you exit information on whether a test failed or not. So something like this:Found a solution - I can override
failureException
:This seems incredibly hacky but it seems to work so far.
Use a decorator around each test.
The safest way to remember to decorate new tests, or to avoid going back and decorating a bunch of existing tests, is to use a metaclass to wrap all of the test functions. The How to wrap every method of a class? answer provides the basics of what you need.
You probably should filter the functions that are wrapped down to just the tests, e.g.:
Here is similar approach to @craigds answer, but with directory support and better compatibility with Python 3:
This was actually found in this blog.
I've extended it further more with
argparse
:so the dir can be specified dynamically either by system variable or passed argument:
This is especially useful, if you've additional wrapper to run all your scripts, like a base class.