Joseph Woolf
Joseph Woolf

Reputation: 550

Does Python's unittest have a global setUp for an entire TestSuite?

I'm a bit new to Python's unittest library and I'm currently looking at setting up my Flask server before running any of my integration tests. I know that the unittest.TestCase class allows you to use setUp() before every test cases in the class. I also know that the same class has another method called setUpClass() that runs only once for the entire class.

What I'm actually interested is trying to figure out how to do something similar like setUpClass(), but done on an entire unittest.TestSuite. However, I'm having no luck at it.

Sure, I could set up the server for every TestCase, but I would like to avoid doing this.

There is an answer on a separate question that suggests that by overriding unittest.TestResult's startTestRun(), you could have a set up function that covers the entire test suite. However, I've tried to passed in the custom TestResult object into unittest. TextTestRunner with no success.

So, how exactly can I do a set up for an entire test suite?

Upvotes: 3

Views: 1675

Answers (1)

Stephen
Stephen

Reputation: 2833

This is not well documented, but I recently needed to do this as well.

The docs mention that TestResult.startTestRun is "Called once before any tests are executed."

As you can see, in the implementation, the method doesn't do anything.

I tried subclassing TestResult and all kinds of things. I couldn't make any of that work, so I ended up monkey patching the class.

In the __init__.py of my test package, I did the following:

import unittest


OLD_TEST_RUN = unittest.result.TestResult.startTestRun

def startTestRun(self):
    # whatever custom code you want to run exactly once before 
    # any of your tests runs goes here:
    ...

    # just in case future versions do something in this method
    # we'll call the existing method
    OLD_TEST_RUN(self)

unittest.result.TestResult.startTestRun = startTestRun

There is also a stopTestRun method if you need to run cleanup code after all tests have run.

Note that this does not make a separate version of TestResult. The existing one is used by the unittest module as usual. The only thing we've done is surgically graft on our custom implementation of startTestRun

Upvotes: 3

Related Questions