我有一个具有当前结构的包:
my_package
|- pyproject.toml
|- poetry.lock
|- tox.ini
|- my_package
| |- __init__.py
| |- my_package.py
|- tests
|- test_my_package.py
pyproject.toml
为 pytest 配置如下:
[tool.pytest.ini_options]
addopts = [
"--import-mode=importlib",
]
testpaths = [
"tests",
]
tox.ini
具有以下配置,根据诗歌官方示例中的第一个用例
文档
[tox]
env_list =
format
py312
[testenv:format]
description = install black in a virtual environment and invoke it on the current folder
deps = black==22.3.0
skip_install = true
commands = black .
[testenv:py312]
deps =
pytest
commands =
pytest tests
运行
pytest tests
工作得很好,但是当我运行
tox
时,我得到
ImportError while importing test module '~\Documents\repos\my_package\tests\test_my_package.py
-
ModuleNotFoundError: No module named tests
我尝试使用
testpaths
配置tox和pytest(pytest在没有此配置的情况下工作得很好)。我还尝试将
__init__.py
添加到目录
tests
我在这里缺少什么?
作为旁注,我尝试了 Poetry 文档中的第二个用例 - 它可以运行测试,但它不会在与我的工作 venv 分开的虚拟环境中运行测试,并且它还会卸载我生成文档等所需的任何可选包。
问题在于,tox 在默认情况下会在名为
.tox
(tox 本身的配置所在的位置)的目录中创建一个虚拟环境。因此,当运行
pytest tests
时,它找不到
tests
模块,因为它不在 tox 创建的虚拟环境的路径中。
可以通过以下几种方法解决此问题:
1. 使用
-r
标志重新创建 tox 环境:
这将强制 tox 重新创建虚拟环境,并包含的
tests
目录。
bash
tox -r
2. 在
tox.ini
中指定
changedir
:
可以指示 tox 在运行测试之前更改到的项目根目录。
ini
[testenv:py312]
changedir = {toxinidir}/..
deps =
pytest
commands =
pytest tests
这会将当前工作目录更改为
toxinidir
(
.tox
目录)的父目录,即的项目根目录。
3. 使用
poetry install
安装包:
可以指示 tox 使用 Poetry 安装的包,包括开发依赖项,以便
tests
目录在路径中。
ini
[testenv:py312]
deps =
pytest
commands =
poetry install
pytest tests
这将使用 Poetry 安装的包,包括在
pyproject.toml
中定义的开发依赖项,并确保
tests
目录在 Python 路径中。
这些解决方案中的任何一个都应该可以解决的问题。我个人建议使用第三种方法,因为它更明确地定义了的测试环境,并且与 Poetry 的工作方式更加一致。
标签:python,pytest,python-poetry,tox From: 78814048