我正在尝试测试我为防止竞争条件而放置的代码是否有效。
在我的测试案例中,我已经启动了两个线程,并让它们都调用了有问题的代码。线程正常返回,但似乎postgres数据库连接保持打开状态。
我已将整个测试用例简化为一个非常简单的示例,其中出现了问题:
psycopg2.errors.ObjectInUse: database "test_db" is being accessed by other users
DETAIL: There are 2 other sessions using the database.
测试运行且测试数据库被破坏后,出现以下错误:
for conn in db.connections.all():
conn.close()
我尝试通过添加以下内容来手动关闭测试用例的结尾处的连接:
django.test.TransactionTestCase
但这似乎没有任何效果。
我使用Django 2.2
作为我的基本TestCase类PostgreSQL 10.6
和{{1}}。
答案 0 :(得分:0)
用更多谷歌搜索解决了这个问题。线程执行后,需要手动关闭Django中的线程。
子类线程:
from django.db import connection
from threading import Thread
class TestThread(Thread):
def run(self):
super().run()
connection.close()