在每种测试方法之前清理Django中的数据库 [英] Cleaning up a database in django before every test method
问题描述
默认情况下,当Django在sqlite后端上运行时,它将创建一个新的内存数据库进行测试。这意味着对于从unittest.TestCase派生的每个类,我都会得到一个新的数据库。可以更改它,以便在运行每个测试方法之前将其清除吗?
By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?
示例:我正在测试一个管理器类,该类在Django持久对象之上提供了更多抽象。代码看起来像这样
Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that
class TestForManager(unittest.TestCase):
def testAddingBlah(self):
manager = Manager()
self.assertEquals(manager.getBlahs(), 0)
manager.addBlah(...)
self.assertEquals(manager.getBlahs(), 1)
def testAddingBlahInDifferentWay(self):
manager = Manager()
self.assertEquals(manager.getBlahs(), 0)
manager.addBlahInDifferentWay(...)
self.assertEquals(manager.getBlahs(), 1)
现在,第二个测试的第一个断言失败,因为在测试调用之间保留了数据库的状态,并且数据库中已经存在 Blah
的实例。
Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of Blah
in the database.
推荐答案
与往常一样,解决方案很简单:使用 django.test.TestCase
而不是 unittest.TestCase
。它适用于Django的所有主要版本!
As always, solution is trivial: use django.test.TestCase
not unittest.TestCase
. And it works in all major versions of Django!
这篇关于在每种测试方法之前清理Django中的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!