Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test other thread that access database

It seem that the database used by django during tests isn't shared with other thread

For example:

inside a TestCase class :

def my_test(self):
    print(MyModel.objects.all())
    my_function()

inside my class :

def worker():
    print(MyModel.objects.all())

def my_function():
    thread = Thread(target=worker)
    thread.start()

Console result :

[<MyModel object>, <MyModel object>, <MyModel object> ... ]
[]

So We get the first call, but as soon as we are inside another thread, it doesn't use the test db anymore.

I looked at : Django: using same test database in a separate thread and tried to use the same db for "NAME" and "TEST_NAME" but it doesn't work for me

What could I do to test my threads even if they are accessing db ?

like image 212
BlueMagma Avatar asked Nov 16 '25 11:11

BlueMagma


1 Answers

Django's TestCase runs each test class in a single transaction. Any changes are not committed, so other threads cannot read the effects of those changes.

The solution is to use a TransactionTestCase. It will run queries in the default autocommit mode, and your changes will immediately be available to other threads.

like image 50
knbk Avatar answered Nov 18 '25 12:11

knbk