Django测试未加载夹具数据

qhhrdooz  于 2023-03-04  发布在  Go
关注(0)|答案(6)|浏览(183)

我已经为我正在做的Django项目写了测试,但是有一个特定的fixture无法加载。这个fixture是使用dumpdata生成的,我根本没有摆弄过它。我可以使用manage.py在那个fixture上加载数据,没有错误。我已经验证了数据实际上是使用shell和查询数据加载的。这让我抓狂,任何帮助都将非常感谢。
以下是我的测试文件(删除了不相关的部分):

class ViewsFromUrls(TestCase):
    fixtures = [
        'centers/fixtures/test_data.json',
        'intranet/fixtures/test_data.json',
        'training/fixtures/test_data.json', #The one that fails to load
        ]

    def setUp(self):
        self.c = Client()
        self.c.login(username='USER', password='PASS')

    ...

    def test_ViewBatch(self):
        b = Batch.objects.all()[0].ticket_number
        response = self.c.get(reverse('training.views.view_batch', kwargs={'id':b}))
        self.assertTrue(response.status_code, 200)
    ...
rta7y2nd

rta7y2nd1#

django.test导入测试用例:

from django.test import TestCase

class test_something(TestCase):
    fixtures = ['one.json', 'two.json']
    ...
  • 非:import unittest
  • 非:import django.utils.unittest
  • 但是:import django.test

这是一个沮丧的一天。停止抱怨-它在文件中:-/

nszi6y05

nszi6y052#

我不知道这是否解决了您的问题,但在这个网站上:
https://code.djangoproject.com/wiki/Fixtures
我发现了一句有趣的话:
你会看到Django搜索 appnames/fixture and settings.FIXTURE_DIRS并加载第一个匹配的fixture.所以如果你使用testdata.json这样的fixture名称,你必须确保没有其他活动的应用程序使用相同名称的fixture.否则,你永远无法确定你实际加载的是什么fixture.因此建议你在fixture前面加上应用程序名称,例如,我的应用程序/夹具/我的应用程序_测试数据. json。
应用这个(在文件名中用appname作为前缀重命名fixture),解决了我的问题(我遇到了这里描述的相同问题)

2eafrhcq

2eafrhcq3#

检查夹具是否真的在正确的位置。来自文档:
Django将在三个位置搜索固定装置:
1.在每个已安装应用程序的fixtures目录中
1.在FIXTURE_DIRS设置中指定的任何目录中
1.在fixture命名的文本路径中

r6vfmomb

r6vfmomb4#

One thing to note, when creating the FIXTURE_DIRS constant in your settings file, be sure to leave out the leading '/' if you have a general fixtures directory off of the root of your project.
Ex:
'/actual/path/to/my/app/fixtures/'
Now, in the settings.py file:
Will NOT work:
FIXTURE_DIRS = '/fixtures/'
Will work:
FIXTURE_DIRS = 'fixtures/'
It's possible this depends on how your other routes are configured, but it was a gotcha that had me scratching my head for a little while. Hope this is useful. Cheers.

wwtsj6pe

wwtsj6pe5#

我犯的一个简单错误是添加了一个自定义的setUpClass(),但忘记了包含super().setUpClass()(当然,这也是Django加载fixture的逻辑所在)

zbwhf8kr

zbwhf8kr6#

对我来说:必需的TestCase而不是SimpleTestCase!导入pdb后仍然看不到postgres中的数据;pdb.set_trace(),但数据在那里,正如我的API调用测试所报告的那样。

相关问题