pytest and relative imports part 2

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:


To be able to access from I needed to:

  • start the testing code, called, with the correct relative import for where the code to be tested is:
from microbit.activity_indicator.activity_indicator import *
  • put 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 files can be empty, created using ‘touch’ in Linux or be saving an empty file in Windows.

Running pytest when the test files are in a different directory to the source files

I had a battle to get my testing directory structure to work outside of an IDE. Please find my solution below. Tested on Windows 7 using python 3.6 and Linux Mint using python 3.4, running the code using the command line:

python -m pytest

The file I wrote to be tested is called in a directory named \src. The file containing tests to be run using pytest is called in a subdirectory \tests, so the full directory path is \src\tests. I needed to add a file called to the \src\tests directory. This file is used in to enable access to in the directory above. The files are empty.

Directory structure:


\src\tests contains the script to be tested.

import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import compress_files  

The line:

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__)

comes from the suggestion at the hitch hikers guide to python at:

This adds the path of the directory above the /src/tests directory to sys.path, which in this case is /src.

import os
import pytest
from .context import compress_files
from compress_files import *

# tests start here

I put this up as an answer to a stackoverflow question here.