1

This question is a follow up to this question that was answered by the user @wim.

I have the same structure

    |
    |-tests
    |    |----test_sum.py
    |
    |--script_to_test.py
    |- pytest.ini

and the files script_to_test.py

def sum(a,b):
    return a+b

pytest.ini

[pytest]
python_files = test_*
python_classes = *Tests
python_functions = test_*

test_sum.py

import script_to_test

def test_sum():
    d=script_to_test.sum(6,5)
    assert d==11

In this situation, pytest does not work since it fails to find the module script_to_test.py

I have read several solutions, some simple but incorrect, some complicated like installing modules, etc.

My solution is simple. Just add an empty file __init__.py

|
|-tests
|    |----__init__.py
|    |----test_sum.py
|
|--script_to_test.py
|- pytest.ini

and with this, pytest works.

Now my question is, is this solution correct, appropriate? and what is the influence of __init__.py here?

wim
  • 338,267
  • 99
  • 616
  • 750
KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • It is not correct/appropriate - it relies on implementation detail of the test discovery mechanism. The interaction with `__init__.py` and pytest's modifications to `sys.path` is explained in detail in my answer on the dupe. My recommendation here is to leave out the `__init__.py` file and use `python -m pytest` instead of `pytest`. – wim Mar 31 '23 at 04:53
  • Thank you for the direction. I am having a bit of a hard time understanding it, but let me ask you a question. In order for pytest to work, what is worst? changing the path of the test code with `sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")` or adding a `__init__.py` file to the test folder. I ask this because installing is out of the question for the team project I am working on with other people – KansaiRobot Mar 31 '23 at 08:06
  • It is better to do the `sys.path.append` (from within the test code, not from within the code under test!), because that will work no matter which [import mode](https://docs.pytest.org/en/7.1.x/explanation/pythonpath.html#import-modes) pytest is running in. Adding `__init__.py` file will not work for the importlib mode, which will become the default in a future version of pytest. However, what is wrong with using `python -m pytest` for your use case? – wim Mar 31 '23 at 14:36
  • Thanks. I will recommend that – KansaiRobot Apr 01 '23 at 07:10

0 Answers0