[Django]-Running django tutorial tests fail – No module named polls.tests

216πŸ‘

βœ…

I had exactly the same issue with my Django project:

$ python manage test polls.tests

worked fine whereas the following failed with an import error:

$ python manage test polls
$ python manage test
(...)
ImportError: Failed to import test module: mydjango.polls.tests
Traceback (most recent call last):
(...)
ImportError: No module named polls.tests

Check carefully the error message: Django’s test runner tries to import the tests from mydjango.polls.tests where mydjango is the name of the root directory (the container for your project).

I fixed this issue by deleting the __init__.py file in mydjango directory (at the same level than manage.py file). This directory is not supposed to be a python module and it seems to mess up with Django’s test runner if it is the case.

So just deleting the _init_.py file should fix our problem:

$ rm mydjango/__init__.py
πŸ‘€pchiquet

20πŸ‘

For anyone else having the same problem, another reason for this to happen is if you have the same name for the root folder and the project folder.

For example:

mydjango
β”œβ”€β”€ __init__.py
β”œβ”€β”€ manage.py
β”œβ”€β”€ mydjango
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   β”œβ”€β”€ wsgi.py
β”œβ”€β”€ polls
β”‚   β”œβ”€β”€ admin.py
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ models.py
|   β”œβ”€β”€ tests.py
β”‚   β”œβ”€β”€ templates

running
./manage.py test

throws errors No module named polls.tests

to fix it simply rename the root folder to something else like :

mydjango_project
β”œβ”€β”€ __init__.py
β”œβ”€β”€ manage.py
β”œβ”€β”€ mydjango
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ settings.py
β”‚   β”œβ”€β”€ urls.py
β”‚   β”œβ”€β”€ wsgi.py
β”œβ”€β”€ polls
β”‚   β”œβ”€β”€ admin.py
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ models.py
|   β”œβ”€β”€ tests.py
β”‚   β”œβ”€β”€ templates
πŸ‘€buluba89

2πŸ‘

Anyhow running

$ python manage.py test polls.tests

It works, it’s enough for me right now:

Creating test database for alias 'default'...
F
======================================================================
FAIL: test_was_published_recently_with_future_poll (polls.tests.QuestionMethodTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/sergio/.virtualenvs/django4/mydjango/polls/tests.py", line 17, in test_was_published_recently_with_future_poll
    self.assertEqual(future_question.was_published_recently(), False)
AssertionError: True != False
πŸ‘€bre

0πŸ‘

first answer didn’t work for me. im using win8, may be this is a reason.
in terminal try to change dir to ./polls and the run

python ../manage.py test polls
πŸ‘€mazdack

Leave a comment