[Solved]-Django unit testing: How to test concurrent database operations?


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

Actually, Django isn’t an issue here.

Your library for optimistic concurrency control must be testable on it’s own as a stand-alone unit.

Outside Django; using just unittest.

You’ll need to test with multi-threaded (and multi-processing) test drivers. Outside Django.

Once you’re sure that works, you can then test inside Django, just to be sure the API’s work.

Once you’re sure all of that works, you should write a simple urllib2 test driver that executes numerous concurrent transactions against a separate Django server. We wrote a little harness that fires up a Django server, runs the tests using urllib2, and then kills the Django server.

More fundamentally, you’ll need some kind of pretty formal proof that your idea works. This is far, far more important than any testing.



Actually, testing whether a concurrent technique works is nearly impossible. It’s so very easy to miss one small race-condition. The only real way is to prove your code, however, that’s a lot of work 😉


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.


use gevent:

import gevent

def foo():
    print('Running in foo')
    print('Explicit context switch to foo again')

def bar():
    print('Explicit context to bar')
    print('Implicit context switch back to bar')


Running in foo
Explicit context to bar
Explicit context switch to foo again
Implicit context switch back to bar


Leave a comment