在django单元测试中加载夹具

问题描述 投票:36回答:9

我正在尝试开始为django编写单元测试,我对夹具有一些疑问:

我制作了我的整个项目数据库(不是某些应用程序)的夹具,我想为每个测试加载它,因为看起来只加载某个应用程序的夹具是不够的。

我想将夹具存储在/proj_folder/fixtures/proj_fixture.json中。

我在我的settings.py中设置了FIXTURE_DIRS = ('/fixtures/',)。然后在我的测试用例中我正在尝试

fixtures = ['proj_fixture.json']

但是我的装置没有加载。怎么解决这个问题?如何添加搜索灯具的地方?一般情况下,为每个应用程序中的每个测试加载整个test_db的夹具是否可以(如果它非常小)?谢谢!

django unit-testing fixtures
9个回答
30
投票

你真的在你的硬盘上有一个文件夹/fixtures/吗?

您可能打算使用:

FIXTURE_DIRS = ('/path/to/proj_folder/fixtures/',)

84
投票

我在TestCase中指定了相对于项目根目录的路径,如下所示:

from django.test import TestCase

class MyTestCase(TestCase):
    fixtures = ['/myapp/fixtures/dump.json',]
    ...

它没有使用FIXTURE_DIRS工作


29
投票

好的做法是在settings.py中使用PROJECT_ROOT变量:

import os.path
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
FIXTURE_DIRS = (os.path.join(PROJECT_ROOT, 'fixtures'),)

13
投票

不是创建fixures文件夹并在其中放置灯具(在每个应用程序中),处理这个的更好和更简洁的方法是将所有灯具放在项目级别的一个文件夹中并加载它们。

from django.core.management import call_command

class TestMachin(TestCase):

    def setUp(self):
        # Load fixtures
        call_command('loaddata', 'fixtures/myfixture', verbosity=0)

调用call_command相当于运行:

 manage.py loaddata /path/to/fixtures 

3
投票

我做了这个,我没有给路径引用,夹具文件名对我来说已经足够了。

class SomeTest(TestCase):

    fixtures = ('myfixture.json',)

2
投票

您有两个选项,具体取决于您是否有夹具,或者您有一组Python代码来填充数据。

对于灯具,使用cls.fixtures,如an answer中对此问题所示,

class MyTestCase(django.test.TestCase):
    fixtures = ['/myapp/fixtures/dump.json',]

对于Python,请使用cls.setUpTestData

class MyTestCase(django.test.TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.create_fixture()  # create_fixture is a custom function

setUpTestDataTestCase.setUpClass称为setUpTestData

您可以同时使用两者,在这种情况下首先加载灯具,因为在加载灯具后调用hello_django


2
投票

假设你的项目名称是api,它有一个名为api的应用程序。以下是在python manage.py dumpdata --format=json > api/fixtures/testdata.json中创建灯具的步骤:

  1. 可选步骤:从数据库创建fixture文件:api/tests
  2. 创建测试目录:__init__.py
  3. api/tests中创建空文件Test Fixtures
  4. 创建测试文件:test_fixtures.py

python manage.py test api.tests

  1. 运行测试(将在数据库中加载你的灯具):setUpClass

0
投票

如果你已经覆盖了super().setUpClass()方法,请确保将from django.test import TestCase方法作为方法的第一行。加载fixture的代码在TestCase类中。


0
投票

你需要导入from unittest import TestCase而不是qazxswpoi。这解决了我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.