tam*_*yte 3 django django-testing
我正在尝试测试我为防止竞争条件而设置的代码是否有效。
在我的测试用例中,我启动了两个线程并让它们都调用有问题的代码。线程正常返回,但似乎 postgres 数据库连接保持打开状态。
我已将整个测试用例简化为一个非常简单的示例,其中出现了问题:
def test_threading(self):
obj = mommy.make(self.model_class)
def test_concurrency():
self.model_class.objects.get(id=obj.id)
t1 = Thread(target=test_concurrency)
t2 = Thread(target=test_concurrency)
t1.start()
t2.start()
t1.join()
t2.join()
Run Code Online (Sandbox Code Playgroud)
在测试运行并且测试数据库被销毁后,我收到以下错误:
psycopg2.errors.ObjectInUse: database "test_db" is being accessed by other users
DETAIL: There are 2 other sessions using the database.
Run Code Online (Sandbox Code Playgroud)
我尝试通过添加以下内容在测试用例结束时手动关闭连接:
for conn in db.connections.all():
conn.close()
Run Code Online (Sandbox Code Playgroud)
但这似乎没有任何影响。
我使用django.test.TransactionTestCase作为我的基本 TestCase 类,Django 2.2并且PostgreSQL 10.6.
tam*_*yte 10
用更多的谷歌搜索弄清楚了这一点。Django 中的线程需要在线程执行后手动关闭数据库连接。
子类线程:
from django.db import connection
from threading import Thread
class TestThread(Thread):
def run(self):
super().run()
connection.close()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
886 次 |
| 最近记录: |