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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With