[Django]-ImportError: Failed to import test module:

10👍

I ran into this issue where I got the ModuleNotFoundError for a folder in my path that I wasn’t directly specifying.

I was running my test file inside PyCharm.

The fix was adding the main entry point to my test file:

if __name__ == '__main__':
    unittest.main()

6👍

i figured it out after more crawling on stackO. It was a simple fix I got the idea from here:
website w/ answer
. it turns out the answer was just to change the relative import to an abolute import

In status/tests.py, the line of code had to change from:

from .models import Status

to:

from status.models import Status

I still find it weird that it threw an error but the accounts/tests.py is fine.

👤Cflux

3👍

Also the test package should not have the same name as the source package. Eg:

- src
 - utils
  - utilities.py
- tests
 - utils
  - test_utilities.py

This setup can cause the error, although it depends on your PYTHONPATH and where you run the tests from. Note how there’s utils package in both src and test directories. Renaming one of the packages seems to solve the problem, eg: utils and test_utils.

Not directly the situation that OP is facing, but I thought it’s worth mentioning.

👤Voy

0👍

Try such as python manage.py test --pattern="*_models.py"

👤Lane

0👍

Double check you pycharm root directory also, if you did put your virtual environment to the same directory as django apps, move env file to higher hierarchy

0👍

So I got this error because I had an __init__.py file in the same directory as the project root (the same directory that manage.py exists in.) This caused some wierd import issues with the tests code and caused a number of other imports of tests to fail.

Leave a comment