0

I have a project with a structure like this:

readme.md
requirements.txt
project/
    main.py
    helpers.py
    recording.py

I want to write some tests, for example test_helpers.py that will test the functionaility in helpers.py

I tried doing it like this:

readme.md
requirements.txt
project/
    __init__.py
    main.py
    helpers.py
    recording.py
tests/
    test_helpers.py

and in test_helpers.py:

from ..project import helpers

But this throws an error:

ImportError: attempted relative import with no known parent package

How would I go about importing things correctly?

I'm aware that I can add the directory using sys.path.insert but that seems quite hacky considering I would have to do it for every test*.py file?

psidex
  • 435
  • 1
  • 6
  • 15
  • For example: Move `tests` folder to the `project` folder and add another `__iniit__.py` inside `tests` – progmatico Jun 05 '20 at 18:49
  • Run tests from outside folder, maybe use test discovery. – progmatico Jun 05 '20 at 18:50
  • @progmatico moving it doesn't help, it still errors with `ImportError: attempted relative import with no known parent package` – psidex Jun 05 '20 at 18:56
  • After the changes mentioned, try launching `python -m unittest discover project.tests` issued from the `project` *parent folder*. – progmatico Jun 05 '20 at 21:30
  • @progmatico I should have mentioned I'm using pytest, now I'm getting another error: ```python project\tests\test_helpers.py:1: in from .. import helpers project\helpers.py:5: in import config ModuleNotFoundError: No module named 'config'``` (I should mention theres another python file in the project folder called config.py that is imported by helpers.py) – psidex Jun 05 '20 at 23:52
  • Look [here](https://stackoverflow.com/questions/1896918/running-unittest-with-typical-test-directory-structure/24266885#24266885) for unittests and [here](https://docs.pytest.org/en/reorganize-docs/new-docs/user/directory_structure.html) for pytests. Hope that helps. – progmatico Jun 06 '20 at 14:31

0 Answers0