vendredi 18 août 2017

Can I use fixtures to create a test from production database?

I have found a strange bug in my Django application. I have a view accessible on /people/<pk>. In tests it works just fine, but in production I have stumbled over a bug at several (just a few!) pk's: Reverse for 'single-person' with arguments '('',)' not found. 1 pattern(s) tried: ['people/(\\d+)/?$']. Since I couldn't catch it with my tests, I'd like to create another test, with the current state of the database, to debug. Also, to prevent future situations like this, I'd always like to be able to run my tests with a copy of the production database, to minimize the chances something goes wrong with the actual data.

I thought it would be as straightforward as

manage.py dumdata --output db-test.json

and then

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)
            ...

However this attempt fails:

======================================================================
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'

(I have a field named added_by in my Person model.) And then it goes on to say django.contrib.auth.models.DoesNotExist: Problem installing fixture '/Users/username/Documents/python_projects/project/db-test.json': User matching query does not exist.

Since I know that this exactly database works just fine, it doesn't look right to me. So before I dive into debugging this problem, I would like to understand if what I am doing is maybe fundamentally wrong and I shouldn't be able to create test fixtures just like that. Or am I missing some simple mistake?

Aucun commentaire:

Enregistrer un commentaire