【问题标题】:How to test other thread that access database如何测试访问数据库的其他线程
【发布时间】:2015-07-27 12:04:06
【问题描述】:

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

例如:

在 TestCase 类中:

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> ... ]
[]

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

我看了:Django: using same test database in a separate thread 并尝试为“NAME”和“TEST_NAME”使用相同的数据库,但它对我不起作用

即使我的线程正在访问 db,我可以做些什么来测试它们?

【问题讨论】:

    标签: python django multithreading unit-testing


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-08
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 2012-06-09
      • 2020-05-02
      相关资源
      最近更新 更多