我需要在后端测试并发编辑错误的处理。 我试图使用线程使客户端并行工作,但我在测试运行时遇到异常: “详细信息:还有2个其他会话正在使用数据库。”
不是OP的例子,但我有同样的问题。预期的结果是其中一个调用由于事务回滚而被拒绝。
@pytest.mark.django_db
def test_transaction_failure(postdata, client):
results_lock = threading.Lock()
results = []
def async_request():
response = client.post('/edit-url', postdata)
with results_lock:
results.append(response)
t1 = threading.Thread(target=async_request)
t2 = threading.Thread(target=async_request)
t1.start()
t2.start()
t1.join(timeout=10)
t2.join(timeout=10)
# assertions
错误出现在拆解中:
..\..\env\lib\site-packages\django\test\utils.py:312: in teardown_databases
connection.creation.destroy_test_db(old_name, verbosity, keepdb)
..\..\env\lib\site-packages\django\db\backends\base\creation.py:263: in destroy_test_db
self._destroy_test_db(test_database_name, verbosity)
..\..\env\lib\site-packages\django\db\backends\base\creation.py:280: in _destroy_test_db
% self.connection.ops.quote_name(test_database_name))
..\..\env\lib\site-packages\django\db\backends\utils.py:64: in execute
return self.cursor.execute(sql, params)
..\..\env\lib\site-packages\django\db\utils.py:94: in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
..\..\env\lib\site-packages\django\utils\six.py:685: in reraise
raise value.with_traceback(tb)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <django.db.backends.utils.CursorWrapper object at 0x000002606A7A0F98>
sql = 'DROP DATABASE "test_postgres"', params = None
def execute(self, sql, params=None):
self.db.validate_no_broken_transaction()
with self.db.wrap_database_errors:
if params is None:
> return self.cursor.execute(sql)
E django.db.utils.OperationalError: database "test_postgres" is being accessed by other users
E DETAIL: There are 2 other sessions using the database.
..\..\env\lib\site-packages\django\db\backends\utils.py:62: OperationalError