I like most things about Pycharm. But one thing I dread is configuring Django tests. There are too many possible ways to set things up and error messages are not very helpful. To make matters worse, I can have the Pycharm Django server configured and working. I can easily get the tests working from the command line. But I still struggle getting the tests configured in Pycharm. You might wonder why to bother. I have found that having the Pycharm debugger available while writing tests is pretty valuable.
How The Test Server Differs in Pycharm
I find it odd that the Pycharm dev server can work but the test runner does not. The reason for this is the Pycharm test runner replaces manage.py with pycharm.django_test_manage.py. This code does a lot of imports. Evidently manage.py is more forgiving.
No Such Manage File and Could Not Import Settings
In pycharm.django_test_manage.py, the command to import the manage.py file is in a try/except statement. If it fails, it prints the message “No such manage file” and moves on. This is how you can have both “no such manage file” and “could not import settings.”
ImportError: No module named XXX
Is your module in a package called “utils”? If so, it could be conflicting with the Pycharm utils package. If you have a package called utils and you can run the test from the command line, then this is likely your problem. There is a patch on the JetBrains issues tracker. They say the problem will be resolved in version 4.5.3, but it is not. I installed the patch and things seem to be working.
Check Your __init__.py Files
I had some apps that were missing them. At the same time I had a __init__.py in the same folder as manage.py. Evidently that is a bad thing. Here is a discussion in Stackoverflow.
Double Check Your Pycharm Django Settings for This Project
Due to some re-factoring, I also had some errors here. Combined with the errors above, it created a mess. Luckily the Pycharm debugger was working, so I could inspect pycharm.django_test_manage.py.
I write my Django as re-usable apps. In each app, I have a directory called “example” that is a full Django project for demo-ing and testing the app. Unfortunately, in some projects, I have a bunch of paths that end with “example.project.settings”. The settings file that gets loaded depends on the order of [sys.path]. In Pycharm tests, the sys.path often has a different order. So code that runs from the command line, fails in Pycharm.
I have solved the problem by putting an app specific prefix on the name of the example directory. I am sure there are better ways, but this works.
A Working Example
When you get all the settings and configurations right, setting up the test runner is pretty easy: