0

I am working on a Python project where I have the following project structure:

project_directory/
├── src/
│   └── my_functions.py   # Contains functions to test
├── tests/
│   └── test_my_functions.py   # pytest test file
└── other_files_and_folders/   # Additional files or folders in the project

In the project_directory, I have a src directory containing the source code with functions that I want to test using pytest. The tests directory holds the pytest test file test_my_functions.py, which contains the test functions.

Initially, to import and access the functions from the src directory in the test_my_functions.py file, I used the following code to modify the Python path:

import sys
import os

# Get the path of the current directory (where test_my_functions.py is located)
current_directory = os.path.dirname(os.path.abspath(__file__))

# Add the parent directory of 'src' to the Python path
parent_directory = os.path.dirname(current_directory)
sys.path.append(parent_directory)

While this approach works, I am seeking a cleaner and more efficient way to access the pytest test features without explicitly modifying the Python path in the test script. I want to ensure that my test script can import the modules from the src directory seamlessly while following best practices and avoiding any potential pitfalls.

Is there a more elegant solution to achieve this without explicitly modifying the Python path in the test script? I am looking for insights and suggestions on how to accomplish this while maintaining a clean and maintainable project structure. Thank you for your help!

Bosser445
  • 303
  • 1
  • 9

2 Answers2

0

If you don't mind using plugins, try pytest-pythonpath.

Install:

pip install pytest-pythonpath

Then create a file called pyproject.toml:

# pyproject.toml
[tool.pytest.ini_options]
python_paths = ["src", "other_files_and_folders"]

Then in your test_my_functions.py:

import my_functions

# tests to follow...
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
0

If you don't want to use pytest plugins, then another alternative is to set PYTHONPATH environment variable before running the test. I prefer to use make and Makefile. Here is my Makefile:

# Makefile
.PHONY: test
test:
    PYTHONPATH=${PWD}/src:${PWD}/other_files_and_folders pytest

Run the test:

make test

You can also create a shell script (or a Windows .cmd file) to set the PYTHONPATH, then run pytest.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • Hi thanks for your input, I placed the Makefile `project_directory` and copied the code that you have like this `PYTHONPATH=${PWD}/src:${PWD}/other_files_and_folders pytest` but it still does not work and I get the message: `# make test make: Nothing to be done for 'test'.` – Bosser445 Jul 25 '23 at 17:50
  • In `Makefile`, make sure that you indent the line after `test:` using a tab, not spaces. – Hai Vu Jul 25 '23 at 19:28