IntelliJ Python unittests cannot import modules

2.1k Views Asked by At

I'm trying to configure my IntelliJ Ultimate 2017 IDE to run Python unit tests. It's not working.

  • The project is a Gradle project, and most modules are Java/Scala. There are several Python modules though.
  • The Python plugin is installed and the Python facet added to the appropriate modules.
  • The Python Interpreter is set up fine. The IDE can actually move around in the code with a ctrl-click action.
  • Under 'Project Structure' -> '<mymodule>' -> dependencies both the interpreter and the <Module source> are included.
  • Each Python module has a 'content root'. Immediately under this is a src folder, under which there is a test folder. The contents of the test folder mirror the src folder, except that files are prepended with test_ to avoid Python name collisions.
  • The test configuration has both 'Add source/content roots to PYTHONPATH' options checked. The interpreter is specified.
  • If test is marked as a tests folder within the module settings, I can right click and 'run tests' for the tests in that folder. However, ImportErrors occur, because it can't find modules within the src directory.
  • There are __init__.py files in all the appropriate places.
  • IntelliJ gives you what it is running, and if I run that on the command, it works, something like:

    python -m unittest discover -s /Users/nathanielford/myrepo/mymodule/src/tests -p test_util.py
    

It appears as though the root path that is being used is set to wherever the unittest file I'm running is: it doesn't use src as the path, and so it cannot find things to import. There is no obvious place to specify this behavior. It didn't seem to work like this in the past.

This started happening recently, after an IntelliJ update. It's possible some configuration became screwy and needs to be fixed, but I don't know what that is. It's also possible that some bug was introduced into IntelliJ, but I don't know how to identify that, either. What am I missing?

2

There are 2 best solutions below

0
On

I have similar problems: cannot import manually installed module. I try to add classpath in Mac environment parameters and intellij SDKs, but it doesn't work. My final solution is to add the classpath of the module to Run/Debug Configurations:

Open Run/Debug Configurations and select your unittest class:

Run --> Edit Configurations...

Add your module's classpath to Environment variables: enter image description here

0
On

Had the same issue and resolved it by no marking the test folder as excluded but just moving it out of the source.

So if the structure is:

src
--->package
--->resources
test

mark in IntelliJ src folder as Sources and src/resources as Resources.

You tests will run from within IDEA.

As I am new to python, I am not sure whether this will affect the packaging. Doing a build though doesn't export the test folder.

Hope that helps.