我有一个开发Python包的项目,其中项目的结构类似于以下内容:
myproject/
├── README.md
├── examples/
│ ├── ex1.py
│ └── ex2.py
├── pyproject.toml
├── src/
│ └── mypackage/
│ ├── __init__.py
│ ├── adder.py
│ └── divider.py
└── tests/
├── test_adder.py
├── test_divider.py
└── test_examples.py
该项目用于开发一个名为mypackage
的Python包,该包位于src
目录中。包被上传到PyPI,用户可以在那里pip install
。包的测试使用pytest运行,位于tests
目录中。使用该包的示例位于examples
目录中。示例只是ex1.py
的脚本,如下所示
"""
Example 1
"""
from mypackage import adder
x = 2.5
y = 8
a = adder(x, y)
print('a is', a)
test_examples.py
的目的是测试示例文件,其内容如下:
from examples import ex1
from examples import ex2
def test_ex1():
ex1
def test_ex2():
ex2
当我在myproject
目录中运行pytest时,我会得到如下错误:
$ cd myproject
$ pytest
platform darwin -- Python 3.10.6, pytest-7.1.2, pluggy-1.0.0
rootdir: /Users/gavinw/Desktop/test-examples
collected 2 items / 1 error
================================================================== ERRORS ==================================================================
_________________________________________________ ERROR collecting tests/test_examples.py __________________________________________________
ImportError while importing test module '/Users/gavinw/Desktop/test-examples/tests/test_examples.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/opt/miniconda3/envs/ztest/lib/python3.10/importlib/__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests/test_examples.py:1: in <module>
from examples import ex1
E ModuleNotFoundError: No module named 'examples'
========================================================= short test summary info ==========================================================
ERROR tests/test_examples.py
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
============================================================= 1 error in 0.05s =============================================================
pytest似乎无法运行examples目录中的文件,因为该位置不允许导入这些文件。关于如何测试示例文件,有什么建议吗?我应该使用pytest来测试示例吗?或者有不同的测试工具吗?
有两种方法可以解决这个问题。第一种方法是使用以下命令运行pytest:
python -m pytest
第二种方法是使用pythonpath
设置在pyproject.toml
文件中添加项目目录,如下所示。然后只需使用pytest
命令即可运行测试。
[tool.pytest.ini_options]
pythonpath = ["."]
您应该确保examples目录包含__init__.py
,以便正确导入。
如果这还不够,您可以使用PYTHONPATH
:
PYTHONPATH="/path/to/your/code/project/:/path/to/your/code/project/examples" pytest
PYTHONPATH
可能很棘手,请参阅https://stackoverflow.com/a/4580120/3800552和https://stackoverflow.com/a/39682723/3800552对于一些使用示例。