Caching result of setUp() using Python unittest

How about using a class member that only gets initialized once?

class test_appletrailer(unittest.TestCase):

    all_trailers = None

    def setup(self):
        # Only initialize all_trailers once.
        if self.all_trailers is None:
            self.__class__.all_trailers = Trailers(res = "720", verbose = True)

Lookups that refer to self.all_trailers will go to the next step in the MRO -- self.__class__.all_trailers, which will be initialized.


An alternative to the proposed solution would be to use a more featured test runner like Nose. With Nose, you can have module-level setup functions which will be run once for a test module. Since it is entirely compatible with unittest, you wouldn't have to change any code.

From the Nose manual:

nose supports fixtures at the package, module, class, and test case level, so expensive initialization can be done as infrequently as possible.

Fixtures are described in detail here. Of course, apart from fulfilling your use-case, I can also strongly recommend it as a general testing tool. None of my projects will leave home without it.