0

I'm using PyCharm CE to develop a project with a structure similar to this:

test_python/
|-- app
|   |-- __init__.py
|   |-- mymodule.py
|   |-- mymodule.pyc
|   `-- test_mymodule.py
|-- config.py
`-- tests
    |-- __init__.py
    |-- test_config.py
    `-- test_models.py

When I try to run my test scripts such as test_config.py, I get:

$ python tests/test_config.py 
Traceback (most recent call last):
  File "tests/test_config.py", line 1, in <module>
    from config import app_config
ImportError: No module named config

I have read a lot of other SO posts that talk about needing a init.py file in all directories that are packages (which I have done already). Many also suggest messing around with sys.path. My problem with this latter approach is that I never had to meddle with the paths previously. I'm not sure if it's something that changed with my dev environment setup, but here it is:

Python 2.7 | macOS Sierra | PyCharm CE

I have tried to install a virtual environment with virtualenv but didn't see a difference. Here is the sample project on github if you'd like to run it yourself

kip2
  • 6,473
  • 4
  • 55
  • 72
  • `$ python test_models.py` leads to `ImportError: No module named app.mymodule `, whereas `$ python app/test_mymodule.py` doesn't fail even though both test scripts have almost identical contents except for the import statement – kip2 Nov 29 '17 at 14:15

2 Answers2

0

It seems that there is a problem with folder depth. Replace from ../config import app_config.

Byeongguk Gong
  • 113
  • 1
  • 9
  • Do you mean replace `from config import app_config` with something else? Changing that line to `from ..config import app_config` leads to a `ValueError: Attempted relative import in non-package ` – kip2 Nov 29 '17 at 14:13
  • Here's the similar problem, I think these are the solutions. [How to fix “Attempted relative import in non-package” even with __init__.py](https://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py), [ValueError: Attempted relative import in non-package not for tests package](https://stackoverflow.com/questions/37193670/valueerror-attempted-relative-import-in-non-package-not-for-tests-package) – Byeongguk Gong Nov 29 '17 at 14:20
0

I think it will work if you change the working directory on your run configuration to test_python. All the packages in your import statements are relative to some entry in your Python path, and the working directory is usually in the Python path.

Don Kirkby
  • 53,582
  • 27
  • 205
  • 286