如何测试其他访问数据库的线程 [英] How to test other thread that access database

查看:49
本文介绍了如何测试其他访问数据库的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

django在测试期间使用的数据库似乎未与其他线程共享

It seem that the database used by django during tests isn't shared with other thread

例如:

在TestCase类中:

inside a TestCase class :

def my_test(self):
    print(MyModel.objects.all())
    my_function()

在我班上:

def worker():
    print(MyModel.objects.all())

def my_function():
    thread = Thread(target=worker)
    thread.start()

控制台结果:

[<MyModel object>, <MyModel object>, <MyModel object> ... ]
[]

所以我们得到了第一个调用,但是一旦我们进入另一个线程,它就不再使用测试数据库了.

So We get the first call, but as soon as we are inside another thread, it doesn't use the test db anymore.

我查看了以下内容: Django:在一个单独的线程并尝试对"NAME"和"TEST_NAME"使用相同的数据库,但这对我不起作用

I looked at : Django: using same test database in a separate thread and tried to use the same db for "NAME" and "TEST_NAME" but it doesn't work for me

即使线程正在访问db,我该怎么做以测试我的线程?

What could I do to test my threads even if they are accessing db ?

推荐答案

Django的 TestCase 在单个事务中运行每个测试类.任何更改都不会提交,因此其他线程无法读取这些更改的效果.

Django's TestCase runs each test class in a single transaction. Any changes are not committed, so other threads cannot read the effects of those changes.

解决方案是使用 TransactionTestCase .它将以默认的自动提交模式运行查询,并且您的更改将立即可用于其他线程.

The solution is to use a TransactionTestCase. It will run queries in the default autocommit mode, and your changes will immediately be available to other threads.

这篇关于如何测试其他访问数据库的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆