Caching result of setUp() using Python unittest

Posted by dbr on Stack Overflow See other posts from Stack Overflow or by dbr
Published on 2008-12-31T07:43:31Z Indexed on 2011/01/02 11:53 UTC
Read the original article Hit count: 221

Filed under:
|

I currently have a unittest.TestCase that looks like..

class test_appletrailer(unittest.TestCase):
    def setup(self):
        self.all_trailers = Trailers(res = "720", verbose = True)

    def test_has_trailers(self):
        self.failUnless(len(self.all_trailers) > 1)

    # ..more tests..

This works fine, but the Trailers() call takes about 2 seconds to run.. Given that setUp() is called before each test is run, the tests now take almost 10 seconds to run (with only 3 test functions)

What is the correct way of caching the self.all_trailers variable between tests?

Removing the setUp function, and doing..

class test_appletrailer(unittest.TestCase):
    all_trailers = Trailers(res = "720", verbose = True)

..works, but then it claims "Ran 3 tests in 0.000s" which is incorrect.. The only other way I could think of is to have a cache_trailers global variable (which works correctly, but is rather horrible):

cache_trailers = None
class test_appletrailer(unittest.TestCase):
    def setUp(self):
        global cache_trailers
        if cache_trailers is None:
            cache_trailers = self.all_trailers = all_trailers = Trailers(res = "720", verbose = True)
        else:
            self.all_trailers = cache_trailers

© Stack Overflow or respective owner

Related posts about python

Related posts about unit-testing