Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class fixtures in Python's unittest

I'm trying to understand class fixtures in Python's unittest module. In order to speed up testing, I'd like to create an 'expensive' connection object just once in each class. At first blush I thought of doing it like this:

import unittest
import rethinkdb as r

class TestRethink(unittest.TestCase):
    conn = r.connect('localhost', 28016)

    def test_table_list(self):
        r.table_list().run(self.conn)

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

It seems from the documentation, however, that one is supposed to do it like this:

import unittest
import rethinkdb as r

class TestRethink(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.conn = r.connect('localhost', 28016)

    def test_table_list(self):
        r.table_list().run(self.conn)

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

What is the difference between the two approaches? In both cases the RethinkDB connection object is a class variable, isn't it?

like image 598
Kurt Peek Avatar asked Mar 10 '23 02:03

Kurt Peek


1 Answers

What is the difference between the two approaches? In both cases the RethinkDB connection object is a class variable, isn't it?

the main differences are scope and order of execution, a class variable will get defined and executed when the class itself will be loaded, whereas the setupClass() method will be called by unittest at the time of running your tests, when that class will be instanciated (it's acting a bit like a constructor).

In your minimal example this should be of little difference, but if you subclass your TestRethink class, then it will. Because in the first case you'll share a single DB connection for all your subclasses, whereas with the setup/teardown you'll have one connection per subclass.

like image 108
zmo Avatar answered Mar 21 '23 09:03

zmo