0

I inherited an existing project with a layout that looks similar to this:

.
├── src
│   ├── __init__.py
│   └── greetings.py
├── tests
│   └── test-greetings.py

The other two files are:

# greetings.py

def hello():
    return 'hello'
# test-greetings.py

import pytest
import sys 

sys.path.append('../src')
from greetings import hello


def test_hello():
    assert hello() == 'hello'

This works, i.e. I can run pytest test-greetings.py from the tests directory but I would like to avoid using the sys.path.append('../src') line. Is there another way to achieve this without changing the project layout?

martineau
  • 119,623
  • 25
  • 170
  • 301
diegus
  • 1,168
  • 2
  • 26
  • 57
  • You could add a `conftest.py` file to your testing directory to avoid adding to path in each testing module: https://stackoverflow.com/a/70172229/14536215 – Tzane Feb 22 '22 at 14:11
  • @Tzane thanks, this could be a preferred solution – diegus Feb 22 '22 at 14:15

1 Answers1

0

You are right that test-greetings.py should assume that it is run in an environment where greetings can be found. How to achieve that is up to whatever installs the package or runs pytest. A simple solution is

PYTHONPATH=../src pytest test-greetings.py

or

PYTHONPATH=src pytest test/test-greetings.py
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks for the replay. This works too. But I was wandering whether something like this `from src.greetings import hello` could be used in this layout.. – diegus Feb 22 '22 at 14:02
  • No. The problem is that you either need `src` to be seen as a directory where top-level modules can be found, or (if you wrote `from src.greetings import hello`) that `src` is seen as a top-level package (which again requires an appropriate search path). Either way, the solution is outside the scope of the code itself. – chepner Feb 22 '22 at 14:05
  • Thanks for the explanation. Just for my understanding. Are you saying that in a scenario where the `tests` directory would be placed inside `src` directory than the `from src.greetings import hello` would work? – diegus Feb 22 '22 at 14:12
  • If `src` could be found in a directory listed in the search path, yes, `from src.greetings import hello` would work, because `greetings` is a module in the package `src`. – chepner Feb 22 '22 at 14:12