pytest can't access django classes

Viewed 1529

I have a Django application, working fine. When I run the tests with pytest, it only works with utility classes (so not Django related).

For example, a test from package A calling an utility class from this package, or another, works fine. However, I'm facing an error as soon as I import a django class.

example 1 : I import my model (in the test), starting the test class with :

from app.common.models import Country

--> ImportError: No module named django.db

[django.db is called in models.py]

example 2 : I import an url resolver (in the test), starting the test class with :

from django.core.urlresolvers import reverse

--> ImportError: No module named django.core.urlresolvers

first try of fix

Following another topic, I set the content of PYTHONPATH :

/home/user/pyenv/lib/python3.5/site-packages

This folder contains installed packages in the virtualenv : django, pytest, psycopg2, and more.

1) If I set DJANGO_SETTINGS_MODULE to the same file as the application, "py.test" gives this error ending with : File "/home/user/pyenv/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 24, in raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)

2) If I set DJANGO_SETTINGS_MODULE to a smaller test setting file, containing only the database infos, I face a different error (self.client failing in a test) :

class Test(unittest.TestCase):
    def testUrls(self):
        response = self.client.get('/countries/all/get')
        self.assertEqual(response.status_code, 200)  

--> AttributeError: 'Test' object has no attribute 'client'

more infos :

1) The python interpreter, for the application, is located in a virtualenv.

2) conftest.py is located in application root folder, so same place as manage.py, and has the following content:

import os
import sys

sys.path.append(os.path.dirname(__file__))

3) pytest.ini is located in same folder as manage.py too, with this content :

[pytest]
python_files = test_*.py test*.py

4) most important : the application works fine, so db settings are valid

If you have any idea of what's wrong, and how to test django classes, any idea will be welcomed. Thank you in advance.

2 Answers
Related