3

Directory Structure

project-root/
├── src/
│ ├── file1.py
│ ├── file2.py
└── tests/
│ ├── test_file1.py
│ ├── test_file2.py
├── requirements.txt
├── pyproject.toml

So basically, under the project root, I have the source codes as src/*.py, test scripts as tests/*.py and the requirements.txt that gives the python packages such as tensorflow==2.18.0

Goal

At the project root directory, run

uv tool run pytest

and all the tests from tests/*.py will be run to log the output to the console.

Difficulties

I am facing two difficulties here, related to the import path, and dependencies.

Import Path

Basically, as follows.

# test_file1.py

from file1 import Class1 # Fails, but this would be my first preference to import
from src.file1 import Class1 # Still fails

How can I import classes and functions defined in src/*.py to the files in the tests? I tried

uv pip install --editable ./

The command run successfully, but did not help, and the classes in the source files are still not visible in the test directory.

Dependency Resolution

I am installing the pip dependencies with

time uv pip install --requirement requirements.txt

which is working for the source code. But it seems the pytest tool cannot see those dependencies, so it is complaining like

ModuleNotFoundError: No module named 'tensorflow'

Note

As I said, uv is my preferred tool for packaging, so it is best if the answer sticks to this framework instead of introducing Poetry or something.

1
  • Have you tried adding sys.path to src? Commented Mar 13 at 11:39

2 Answers 2

6

Complete answer can be found here;

But you can simply create _init_.py file under tests directory!

Secondary fix is to add this to your pyproject.toml:

[tool.pytest.ini_options]
pythonpath = ["."]
Sign up to request clarification or add additional context in comments.

1 Comment

Note that this refers to a different question. uv tool run pytest is not the same as uv run pytest.
2

You should probably not use uv tool run pytest, but uv run pytest. When you run pytest as a tool, it is installed in a separate isolated virtual environment. Since pytest relies on the dependencies, it should run in a virtual environment with the package and dependencies installed. See the second note on this page: https://docs.astral.sh/uv/guides/tools/.

1 Comment

This fixed my failing tests. Targeting my local directory (in this case a uv workspace) with uvx pytest . fails, where uv run pytest after installing it pytest as a dev dependency (uv add --dev pytest) succeeds. This should be the accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.