python - Django 测试用例 : recreate database in self. 子测试(...)

标签 python django testing

我需要用不同的参数测试一个函数,最合适的方法似乎是使用 with self.subTest(...) 上下文管理器。

但是,该函数向数据库写入了一些内容,并以不一致的状态结束。我可以删除我写的东西,但如果我能完全重新创建整个数据库会更干净。有办法吗?

最佳答案

不确定如何在 self.subTest() 中重新创建数据库,但我目前正在使用另一种技术,您可能会感兴趣。您可以使用固定装置创建数据库的“快照”,该快照基本上将被复制到仅用于测试目的的第二个数据库中。我目前使用这种方法来测试我正在工作的一个大项目的代码。

我将发布一些示例代码,让您了解这在实践中会是什么样子,但您可能需要做一些额外的研究来根据您的需要定制代码(我添加了链接来指导您) .

这个过程相当简单。您将创建一个数据库副本,其中仅包含使用固定装置所需的数据,该副本将存储在 .yaml 文件中,并且只能由您的测试单元访问。

这个过程是这样的:

  1. 列出要复制到测试数据库的项目,以使用固定装置填充它。这只会创建一个包含所需数据的数据库,而不是愚蠢地复制整个数据库。它将存储在 .yaml 文件中。

生成.py

    django.setup()
    stdout = sys.stdout

    conf = [
        {
            'file': 'myfile.yaml',
            'models': [
                dict(model='your.model', pks='your, primary, keys'),
                dict(model='your.model', pks='your, primary, keys')
            ]
        }
    ]

    for fixture in conf:
        print('Processing: %s' % fixture['file'])
        with open(fixture['file'], 'w') as f:
            sys.stdout = FixtureAnonymiser(f)

        for model in fixture['models']:
            call_command('dumpdata', model.pop('model'), format='yaml',indent=4, **model)
            sys.stdout.flush()

        sys.stdout = stdout
  1. 在您的测试单元中,将生成的 .yaml 文件导入为夹具,您的测试将自动使用夹具中的数据来执行测试,同时保持主数据库不变。

test_class.py

from django.test import TestCase

class classTest(TestCase):

    fixtures = ('myfile.yaml',)

    def setUp(self):
        """setup tests cases"""
       # create the object you want to test here, which will use data from the fixtures

    def test_function(self):
        self.assertEqual(True,True)
        # write your test here

您可以在这里阅读更多内容:

如果您因为不清楚而有任何疑问,请尽管提问,我很乐意为您提供帮助。

关于python - Django 测试用例 : recreate database in self. 子测试(...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46099343/

相关文章:

python - Python 的 HackerRank "filled orders"问题

python - icon_clock.gif 和 icon_calender.gif 的 django static admin 404

python - 箭头键、home 和 end 在 django 终端中不起作用

unit-testing - 未注入(inject)模拟对象

python - 针对 Python Web 开发的 TDD 资源

python - Python 中的简单 Tensorflow 代码出现错误

python - 漂亮的打印 Pandas : how to set the columns as displayed rows (and rows as displayed columns)?

python - 在 python 中没有 for 循环的情况下重复函数几次

database - Django:使用平均达到指定数字的随机整数字段值创建模型实例

testing - google-analytics.com 阻止我本地的测试用例