Are data created by setUpTestData shared by all tests ?

272 views
Skip to first unread message

Gagaro

unread,
Jun 1, 2015, 9:20:03 AM6/1/15
to django...@googlegroups.com
Hi,

I have an hard time understanding how I am supposed to use setUpTestData. The documentation isn't very clear about it (https://docs.djangoproject.com/en/1.8/topics/testing/tools/#django.test.TestCase.setUpTestData).

"The class-level atomic block described above allows the creation of initial data at the class level, once for the whole TestCase.". and "Note that if the tests are run on a database with no transaction support (for instance, MySQL with the MyISAM engine), setUpTestData() will be called before each test, negating the speed benefits." let me think that the changes made by the test should be rollbacked after each test.

So I would expect the following to works:

class OrderBugTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.order = OrderFactory()
        cls.order.go_available()
        cls.order.go_suspended()

    def test_1(self):
        """ Ok. """
        self.order.go_completed()
        self.assertEqual(self.order.state, 'completed')

    def test_2(self):
        """ Fails, order is modified from test_1. """
        self.assertEqual(self.order.state, 'suspended')

Does this means only static data should be created this way ? Can't I modify data created this way in the test ? Am I doing something wrong ?

Thanks.

Tim Graham

unread,
Jun 1, 2015, 1:06:31 PM6/1/15
to django...@googlegroups.com
It looks like you may be using in-memory models instead of saving them to the database? In case your go_available() method does save the OrderFactory instance, you'll still need to refresh the object from the database using Model.refresh_from_db() in test_2().

Gagaro

unread,
Jun 1, 2015, 2:04:12 PM6/1/15
to django...@googlegroups.com
Indeed, it was that obvious.

class OrderBugTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.order = OrderFactory()
        cls.order.go_available()
        cls.order.go_suspended()

    def setUp(self):
        self.order.refresh_from_db()

    def test_1(self):
        """ Ok. """
        self.order.go_completed()
        self.assertEqual(self.order.state, 'completed')

    def test_2(self):
        """ Fails, order is modified from test_1. """
        self.assertEqual(self.order.state, 'suspended')

Thanks!

Gagaro

unread,
Jun 1, 2015, 2:11:01 PM6/1/15
to django...@googlegroups.com
For information, I went from 30 seconds (with setUp) to 13 seconds with setUpTestData. Thanks to the persons who did this feature!
Reply all
Reply to author
Forward
0 new messages