Relative/script imports in python test

I have split my custom python testing into multiple files for readability. This is custom_test_runner.py

from platformio.public import UnityTestRunner
from .include.logic_analyzer import LogicAnalyser  # type: ignore
from .include.test_parser import TestParser  # type: ignore


class CustomTestRunner(UnityTestRunner):

    def setup(self):
        return super().setup()

    def stage_testing(self):
        # 1. Gather test results from Serial, HTTP, Socket, or other sources

        # Setup serial analysis
        self.LOGIC_BOOT_OK = LogicAnalyser.start_serial_analysis()
        if not self.LOGIC_BOOT_OK:
            raise RuntimeError("Error starting Logic2")

        # 2. Report test results (add cases)
        for case in TestParser.create_all_test_cases():
            self.test_suite.add_case(case)

And my project tree of the test directory:

└── test
    ├── README
    └── embedded
        ├── __pycache__
        │   └── test_custom_runner.cpython-311.pyc
        ├── include
        │   ├── logic_analyzer.py
        │   └── test_parser.py
        ├── test_custom_runner.py
        ├── test_data.py
        └── test_dummy
            └── main.cpp

When I run this I get

UserSideException: Could not find custom test runner by this path -> /Users/.../ArduinoUnitPIO/test/embedded/test_custom_runner.py

When I comment out the imports I just get a regular Python exception NameError NameError: name 'UnityTestRunner' is not defined which indicates the file ran.

My question is, how do I make these imports work in the PIO venv?

Write instead

import sys
import os

this_dir= os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(this_dir, "include"))

from logic_analyzer import LogicAnalyser  # type: ignore
from test_parser import TestParser  # type: ignore

See https://stackoverflow.com/questions/16114391/adding-directory-to-sys-path-pythonpath

1 Like