【问题标题】:how to init database for testcase in django如何在 django 中为测试用例初始化数据库
【发布时间】:2014-02-11 03:09:11
【问题描述】:

在测试用例中,有很多测试函数,所有的测试函数都使用相同的数据。

class Mytest(TestCase):
    def init_data(self):
        insert data1
        insert data2
        .....
    def test1:
        do something
    def test2:
        do something
    ....

我应该在哪里调用 init_data 函数。如果我在所有测试函数中调用该函数,它会多次插入数据并影响结果。我想我可以在第一个测试函数中调用 init_data 。但是当我编写许多测试函数时,我发现 djang 调用的第一个测试函数不是我编写的第一个测试函数。那么我应该如何调用 init_data() 函数或者是否有其他方法可以做到这一点。提前谢谢

【问题讨论】:

  • 查看setUptearDownmethods。

标签: django django-tests


【解决方案1】:

如果您的测试都使用相同的数据,您可以使用固定装置(一堆用于测试的“假”数据库条目)预先填充 TestCase。查看 Django 测试文档 Providing initial data for modelsTest Case documentation

基本上,您的应用程序中有一个 JSON/XML/YAML 文件,其中包含用于测试的初始数据:

[
  {
    "model": "app.somemodel",
    "pk": 1,
    "fields": {
      "somefield": 'data',
      "otherfield": 'otherdata',
    }
  },
  # more test model instances to follow.
]

如果您使用 JSON a(在上面的示例中)并将文件命名为 initial_data.json,它将在您每次运行测试时自动加载。否则,要为特定的 TestCase 指定要加载的夹具,请将文件命名为:special_data.json 并告诉 TestCase 加载它:

class MyTest(TestCase):
    fixtures = ['special_data',]

    def test1:
        do something
    # etc

希望这会有所帮助!

我还应该提到,虽然固定装置是一种为测试目的提供初始数据的简便方法,但它们也有一些缺点。你可能不想看看ModelFactoreswhy Carl Meyer thinks you should be using them

【讨论】:

    猜你喜欢
    • 2015-12-17
    • 2013-08-05
    • 2019-02-20
    • 1970-01-01
    • 2011-07-27
    • 2012-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    相关资源
    最近更新 更多