【问题标题】:how to test django fixture json file如何测试 django 夹具 json 文件
【发布时间】:2019-05-06 14:09:40
【问题描述】:

我有一个脚本会为我的 django 应用程序生成一个 JSON 文件(让我称之为 data.json),通常我可以通过运行命令来测试它

python manage.py testserver data.json

但是,我想在单元测试中运行这个东西,而不是通过 shell 运行它(因为它会启动一个服务器并且永远不会返回到 shell)。我不需要运行任何依赖于此夹具的测试。我只想确保生成的fixture可以加载。

【问题讨论】:

    标签: django django-testing django-tests django-fixtures django-manage.py


    【解决方案1】:

    Django 自己的TestCase 支持通过类级别的fixtures 属性自动设置和拆除fixture。例如

    from django.test import TestCase
    
    class MyTest(TestCase):
    
        # Must live in <your_app>/fixtures/data.json
        fixtures = ['data.json']
    
        def test_something(self):
            # When this runs, data.json will already have been loaded
            ...
    

    但是,由于您只想检查是否可以加载夹具而不是将其用作测试的一部分,因此您可以在测试代码中的某处调用 loaddata 命令。

    例如

    from django.core.management import call_command
    
    call_command('loaddata', '/path/to/data.json')
    

    【讨论】:

    • 嗯,这意味着夹具将实际加载到真实数据库中,我想避免这种情况。
    • @HsiaoYi 所以你想将它加载到不同的数据库中?您为此配置了特定的数据库?
    • 我希望将其加载到测试数据库中,但不会启动测试服务器。我现在在想的一件事是在不运行服务器的情况下使用基本机制(github.com/django/django/blob/…),但我怕我错过了一些东西。
    • 如果您的单元测试扩展了 Django 的TestCase,那么当您运行测试时,这一切都会发生在您身上。 Django 会在测试开始前将夹具数据插入到测试数据库中。
    • 你的意思是我应该在扩展TransactionTestCase 的单元测试中使用call_command('loaddata', ...) 吗?
    【解决方案2】:

    Django 管理命令可以使用call_commands 在您的代码中运行。

    from django.core.management import call_command
    from django.core.management.commands import testserver
    
    call_command('testserver', 'data.json')
    

    【讨论】:

    • 但是,它看起来不会返回到 shell。
    猜你喜欢
    • 2016-01-27
    • 2011-01-17
    • 2013-10-25
    • 2018-02-07
    • 2011-01-12
    • 2011-04-16
    • 2019-10-02
    • 1970-01-01
    • 2015-09-12
    相关资源
    最近更新 更多