pytest and relative imports part 2
Publish date: Jan 16, 2019
Last updated: Jan 23, 2023
Last updated: Jan 23, 2023
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. I use the eclipse IDE for coding. 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_indicator.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 by 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