Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up a resource shared by several unit tests?

In Python, how can I have one setup (which may contain expensive function calls) for a whole set of unit tests?

Example:

import unittest

class Test1(unittest.TestCase):
    def setUp(self):
        print "expensive call"
    def test1(self):
        self.assertEqual(1, 1)
    def test2(self):
        self.assertEqual(1, 1)

if __name__ == "__main__":
    unittest.main()

Will run the expensive call twice:

$ python unittest.py
expensive call
.expensive call
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

How can I change it so the expensive call is made only once and its resources accessible to all tests?

UPDATE: I'm using Python 2.6.

like image 976
Frank Avatar asked Aug 30 '12 17:08

Frank


People also ask

Can unit tests depend on each other?

Unit tests should not affect each other. Unit tests should be deterministic. Unit tests should not depend on any external state.

What are best practices for unit testing methods that use cache heavily?

If you want true Unit Tests, then you have to mock the cache: write a mock object that implements the same interface as the cache, but instead of being a cache, it keeps track of the calls it receives, and always returns what the real cache should be returning according to the test case.


1 Answers

You can use setUpClass

import unittest

class Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print 'setUpClass'
        cls.data = 123

    def test_one(self):
        print 'test_one'
        print self.data

    def test_two(self):
        print 'test_two'


if __name__ == "__main__":
    unittest.main()

See http://docs.python.org/library/unittest.html#unittest.TestCase.setUpClass

UPDATE:

For python 2.6, I suppose you could use class-level attributes:

class Test(unittest.TestCase):
     value = result_of_some_expensive_function()
     def test(self):
         print self.value

That function will run once when your test is defined.

like image 78
ChrisB Avatar answered Sep 19 '22 06:09

ChrisB