In the python unittest module, how can I perform different tasks based on how the test ends? I am running selenium webdriver automated tests, and in the case of of a failure or error, I would like to capture a screenshot.
Asked
Active
Viewed 118 times
0
-
At least relevant: [`Automatic screenshots when test fail by Selenium Webdriver in Python`](http://stackoverflow.com/questions/12024848/automatic-screenshots-when-test-fail-by-selenium-webdriver-in-python), at most duplicate. – alecxe Jun 16 '14 at 14:36
-
Also see: [How do I capture a screenshot if my nosetests fail?](http://stackoverflow.com/questions/14991244/how-do-i-capture-a-screenshot-if-my-nosetests-fail) – alecxe Jun 16 '14 at 14:37
-
Well...not quite (first comment). That would work if I warp my entire test in a `try/except`, but I would rather not do that. I would rather `tearDown()` know that the test failed and then do other things, (in this case) such as take a screenshot. But I'm also interested in just learning more about unittest and I couldn't find the answer to my question anywhere. – kroe761 Jun 16 '14 at 15:54
1 Answers
0
You define "how the test ends". The general principle is you should have one assertion per unit test (in the context of the unittest module this means a test_*
method. So the test ends after you've run your assertion.
def test_my_page(self):
try:
self.assertEqual(some_element.field, '42')
except Exception:
# take screenshot
Of course you could go a bit more general:
class MyTestClass(unittest.TestCase):
def setUp(self):
self.take_screenshot = False
def tearDown(self):
if self.take_screenshot:
# take screenshot with selenium
# and do other stuff
def test_my_page(self):
try:
self.assertEqual(some_element.field, '42')
except Exception:
self.take_screenshot = True
Although that might not be much of an improvement over the first one (it just keeps the cleanup out of the test methods... kinda.
The point is: you still have to catch those exceptions yourself. unittest will not catch exceptions unless you tell it to and in the case of an uncaught exception, the tearDown method is not called.

Oin
- 6,951
- 2
- 31
- 55