I had another tussle with getting pytest to recognise where the modules to be tested are relative to the directory where the testing code is. This time I resolved the issue using relative imports. Last time I tried adding the directory where testing code is to the system path. This is detailed in my post here.
This time I realised that I could solve the issue using relative imports correctly. The blog page here helped me.
Here’s my project structure:
microbit/ microbit/activity_indicator/activity_indicator.py microbit/tests/test_activity_indicatory.py
To be able to access activity_indicator.py from test_activity_indicator.py I needed to:
- start the testing code, called test_activity_indicator.py, with the correct relative import for where the code to be tested is:
from microbit.activity_indicator.activity_indicator import *
- put __init__.py files at the root of the project, in the directory with the code to be tested and in the directory with the testing code. These __init__.py files can be empty, created using ‘touch __init__.py’ in Linux or be saving an empty file in Windows.
microbit/ microbit/__init__.py microbit/activity_indicator/__init__.py/ microbit/activity_indicator/activity_indicator.py microbit/tests/__init__.py microbit/tests/test_activity_indicator.py