如何在django测试中强制事务中的竞争条件?
发布时间:2020-12-20 13:41:23 所属栏目:Python 来源:网络整理
导读:有没有办法使用多个线程运行 django测试并强制竞争条件?我想确保执行处理事务错误的代码路径.更具体一点,我希望能够生成2个尝试在数据库上执行相同操作的线程,其中一个成功,另一个失败.我正在使用django中的测试框架. Python伪代码: def some_method(): tr
有没有办法使用多个线程运行
django测试并强制竞争条件?我想确保执行处理事务错误的代码路径.更具体一点,我希望能够生成2个尝试在数据库上执行相同操作的线程,其中一个成功,另一个失败.我正在使用django中的测试框架.
Python伪代码: 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 解决方法
从我正在阅读的内容中,您想要覆盖处理异常的路径.我问你这个问题:你是否真的需要在多线程竞争条件的情况下触发它,或者你只是想确保在它发生的情况下它做了正确的事情?
这就是我要做的事情: import unittest import mock # added just mimic django's 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 这样做可以避免您进行挡板测试.你知道随机失败的那些. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |