Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tests fails with TransactionTestCase and pytest

I have an issue with a my unit tests and the way django manages transactions.

In my code I have a function:

def send():
    autocommit = transaction.set_autocommit(False)
    try:
         # stuff
    finally:
         transaction.rollback()
         transaction.set_autocommit(autocommit)

In my test I have:

class MyTest(TransactionTestCase):
    def test_send(self):
        send()

The issue I am having is that my test_send passes successfully but not 80% of my other tests.

It seems the transaction of the other tests are failing

btw I am using py.test to run my tests

EDIT: To make things more clear when I run my tests with only myapp.test.test_module.py it runs fine and all 3 tests passes but when I run all my tests most of the fails, will try to produce a test app

Also all my tests passes with the default test runner from django

EDIT2: Here is A minimal example to test this issue:

class ManagementTestCase(TransactionTestCase):

    def test_transfer_ubl(self, MockExact):
        pass

class TestTestCase(TestCase):

     def test_1_user(self):
         get_user_model().objects.get(username="admin")
         self.assertEqual(get_user_model().objects.all().count(), 1)

Bear in mind there is a datamigration that adds an "admin" user (the TestTestCase succeeds alone but not when the ManagmentTestCase is run before)

It seems autocommit has nothing to do with it.

like image 382
maazza Avatar asked Jan 06 '23 19:01

maazza


1 Answers

The TestCase class wraps the tests inside two atomic blocks. Therefore it is not possible to use transaction.set_autocommit() or transaction.rollback() if you are inheriting from TestCase.

As the docs say, you should use TransactionTestCase if you are testing specific database transaction behaviour.

like image 62
Alasdair Avatar answered Jan 08 '23 08:01

Alasdair