【问题标题】:Can I use fixtures to create a test from production database?我可以使用夹具从生产数据库创建测试吗?
【发布时间】:2017-08-18 19:06:50
【问题描述】:

我在我的 Django 应用程序中发现了一个奇怪的错误。我在/people/<pk> 上有一个可访问的视图。在测试中它工作得很好,但在生产中我偶然发现了几个(只有几个!)pk的错误:Reverse for 'single-person' with arguments '('',)' not found. 1 pattern(s) tried: ['people/(\\d+)/?$']。由于我的测试无法捕捉到它,我想创建另一个测试,使用数据库的当前状态进行调试。此外,为了防止将来出现这种情况,我总是希望能够使用生产数据库的副本运行我的测试,以尽量减少实际数据出现问题的可能性。

我认为它会像

一样简单
manage.py dumdata --output db-test.json

然后

from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test import Client

from people.models import Person


class TestPeopleWithMyData(StaticLiveServerTestCase):
    fixtures = ['db-test.json']

    def setUp(self):
        self.client = Client()
        self.client.force_login(user='test_user')

    def test_person(self):
        for person in Person.objects.all():
            print('Testing %s: ' % person, end='')
            r = self.client.get('/people/%d' % person.pk)
            print(r)
            ...

但是这个尝试失败了:

======================================================================
ERROR: setUpClass (people.tests.test_my_data.TestPeopleWithMyData)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/username/Documents/python_projects/project/venv/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__
    rel_obj = getattr(instance, self.cache_name)
AttributeError: 'Person' object has no attribute '_added_by_cache'

(我的Person 模型中有一个名为added_by 的字段。)然后它继续说django.contrib.auth.models.DoesNotExist: Problem installing fixture '/Users/username/Documents/python_projects/project/db-test.json': User matching query does not exist.

因为我知道这个数据库工作得很好,所以我觉得它不合适。所以在我深入调试这个问题之前,我想了解我所做的是否从根本上是错误的,我不应该能够像那样创建测试装置。还是我错过了一些简单的错误?

【问题讨论】:

    标签: django database testing fixture


    【解决方案1】:

    我认为你需要在运行测试之前做

    python manage.py makemigrations
    python manage.py migrate
    

    在您的夹具文件中,您的模型中没有“_add_by_cache”。

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      • 2017-11-10
      • 1970-01-01
      • 2011-08-08
      • 2016-11-02
      相关资源
      最近更新 更多