1

I have a project structured like this:


├───project
|   ├───__init__.py
|   ├───main.py
│   ├───collect_data
│   │   └───functions.py
│   └───other_folder
│       └───generate.py
├───tests
|   ├───__init__.py
│   └───test_functions.py
├───pyproject.toml
└───poetry.lock

I did poetry install (which generated the poetry.lock). I am using vscode in a windows machine with python 3.7.11, pytest 7.0.1. and conda environnements.
So now the problem is: if I do a test for functions.py, I import like so : from project.collect_data.functions import my_function and this works.
But if I try testing an endpoint that is in 'main.py' (from project.main import another_function) the problem is that in turn main.py is importing some functions but without calling 'project' (like from collect_data.functions import my_function) so when the test run I have an error with collect_data module not found.
I've read tons of docs but obviously I'm doing something wrong. The code is usually ran from "project" so i'm not willing to change the way main is importing other functions (and some sub folders are calling others functions from somewhere else as well, the project is actually a lot bigger than the example).
I think the problem hs something to do with the PATH but I'm not really sure how to fix it.
I've tried to put an empty conftest.py at the root of the project (I saw it somewhere in SO, can't find the link now)but it doesn't work either.

Reine Baudache
  • 413
  • 4
  • 16
  • Your imports should always be absolute. They should always start from a top-level package (or module). In your case the top-level importable package is `project`, so in `project/main.py` you should have `from project.collect_data.functions import my_function`. – sinoroc Aug 16 '22 at 21:49
  • You did not say how you start the program, but if you do something like `python project/main.py` then that is also not recommended and it will be much easier to do something like `python -m project.main` instead. – sinoroc Aug 16 '22 at 22:12

1 Answers1

2

One thing that should work is adding project to your $PYTHONPATH environment variable, ie running export PYTHONPATH=project. Then you can run pytest with poetry run pytest (as suggested by poetry). Or setting the property in your pyproject.toml as

[tool.pytest.ini_options]
pythonpath = "project"
Gregor
  • 588
  • 1
  • 5
  • 19
  • +1 for setting in pyproject per [this answer](https://stackoverflow.com/questions/50155464/using-pytest-with-a-src-layer) – danialk Dec 17 '22 at 21:00