How to force race state in transaction in django tests?

Is there a way to run django tests using multiple threads and a forced race condition? I want to make sure that the code path that handles transaction errors is executing. To be a little more specific, I want to be able to create 2 threads that will try to perform the same action in the database, one of which succeeds and the other unsuccessful. I am using a test framework that is in django.

Python Pseudo Code:

def some_method():
  try
    with transaction.atomic():
      objectA = get_object_from_db()
      objectA.delete()
  except Error:
    # error handling code to be run


class TestClass(TransactionalTestCase):
  def test_some_method():
    # run two threads and make sure that the race condition was present and some_method recovered successfully
+4
source share
1 answer

, , , . : , , , , , ?

:

import unittest
import mock


# added just mimic django orm for the purpose of the demo
class QuerySet(object):
  def delete(self):
    pass

def get_object_from_db():
  return QuerySet()

def some_method():
  try:
    objectA = get_object_from_db()
    objectA.delete()
    return True # this should be whatever you want to do in case it worked
  except Exception: # I would look up and check what ever error the django orm is raising.
    return False # this should be whatever you want to do in case it didn't work

class TestClass(unittest.TestCase):
  def test_some_method_in_case_it_worked(self):
    self.assertEqual(some_method(), True)

  def test_some_method_in_case_it_did_not_work(self):
    with mock.patch('__main__.get_object_from_db') as mocked_get_object_from_db:
      mocked_get_object_from_db.side_effect = RuntimeError('a message')
      self.assertEqual(some_method(), False)

if __name__ == '__main__':
    unittest.main()

mock . https://pypi.python.org/pypi/mock

. , .

+1

Source: https://habr.com/ru/post/1533034/


All Articles