Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django unit testing: How to test concurrent database operations?

I'm creating a Django library which uses optimistic concurrency control to prevent concurrent writes from causing inconsistent data. I'd like to be able to write unit tests for this functionality but I'm not sure how to accomplish this.

I know that Django's unit tests are single threaded, so the only way I can envision a test working is by having two separate database connections (to the same database) open simultaneously and toggling which connection the Django ORM uses when executing queries, though I'm not sure if connection toggling is even possible in Django.

What are some techniques for testing concurrent database operations with Django?

like image 227
brildum Avatar asked Mar 07 '11 20:03

brildum


People also ask

What is RequestFactory in Django?

The request factory The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view.

Does Django use Unittest?

Writing testsDjango's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.

Where does Django store test database?

from the docs: When using SQLite, the tests will use an in-memory database by default (i.e., the database will be created in memory, bypassing the filesystem entirely!). The TEST dictionary in DATABASES offers a number of settings to configure your test database.


1 Answers

One way to handle this is to spawn multiple copies of Django runserver in separate processes pointed at the same DB. Then your unit test spawns threads/processes and they all bang on the runservers exercising your concurrency. During teardown you join with all your processes.

like image 126
Spike Gronim Avatar answered Oct 11 '22 13:10

Spike Gronim