Django可以在每个单元测试之间刷新其数据库吗? [英] Can Django flush its database(s) between every unit test?

查看:59
本文介绍了Django可以在每个单元测试之间刷新其数据库吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django(1.2 beta)将在每个运行的测试之间重置数据库,这意味着每个测试都在一个空的DB上运行.但是,数据库没有清除.刷新数据库的作用之一是 auto_increment 计数器被重置.

Django (1.2 beta) will reset the database(s) between every test that runs, meaning each test runs on an empty DB. However, the database(s) are not flushed. One of the effects of flushing the database is the auto_increment counters are reset.

考虑一个通过主键将数据从数据库中拉出的测试:

Consider a test which pulls data out of the database by primary key:

class ChangeLogTest(django.test.TestCase):
    def test_one(self):
        do_something_which_creates_two_log_entries()
        log = LogEntry.objects.get(id=1)
        assert_log_entry_correct(log)
        log = LogEntry.objects.get(id=2)
        assert_log_entry_correct(log)

这将通过,因为仅创建了两个日志条目.但是,如果将另一个测试添加到 ChangeLogTest 中并且恰好在之前 test_one 运行,则日志条目的主键不再是1,并且2,它们可能是2和3.现在 test_one 失败了.

This will pass because only two log entries were ever created. However, if another test is added to ChangeLogTest and it happens to run before test_one, the primary keys of the log entries are no longer 1 and 2, they might be 2 and 3. Now test_one fails.

这实际上是一个两部分的问题:

This is actually a two part question:

  1. 是否可以强制 ./manage.py test 在每个测试用例之间刷新数据库?
  2. 由于Django默认情况下不会在每个测试之间刷新数据库,因此也许有充分的理由.有人知道吗?
  1. Is it possible to force ./manage.py test to flush the database between each test case?
  2. Since Django doesn't flush the DB between each test by default, maybe there is a good reason. Does anyone know?

推荐答案

是否可以强制./manage.py测试在每个测试用例之间刷新数据库?

is it possible to force ./manage.py test to flush the database between each test case?

看看django.core.management.commands.flush.py命令的实现.

Have a look on the implementation of the command of django.core.management.commands.flush.py.

您可以从测试调用内部调用flush命令(也许在TestCase.setUp中):

You can call the flush command from inside your test call (maybe in TestCase.setUp):

management.call_command('flush')

也许有充分的理由.有人知道吗?

maybe there is a good reason. Does anyone know?

是的:加速.从json刷新并重新加载许多数据需要一段时间...

Yes there is: Speed up. Flushing and reloading many data from json takes a while...

也许您应该看看 TransactionTestCase

这篇关于Django可以在每个单元测试之间刷新其数据库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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