【发布时间】:2021-11-09 01:38:42
【问题描述】:
我在使用 pytest 和 tox 测试我的包时遇到问题。尝试运行两者时,我收到ModuleNotFoundError。 Pytest 确实找到了 test_hello.py,但在尝试导入我的包进行测试时立即失败。
我正在使用 PyCharm IDE,它会自动为我的项目设置 pipenv 环境。我在 PyCharm 中使用终端 shell(Powershell 实例)来运行 pytest / tox / pip 命令。
我尝试过运行 pytest,有无 pip 先安装我的包:pip install -e . 两者都产生相同的 ModuleNotFoundError 结果。
追溯
ImportError while importing test module 'C:\Users\USERNAME\Workspace\hello2\tests\test_hello.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\appdata\local\programs\python\python39\lib\importlib\__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests\test_hello.py:2: in <module>
from hello import Hello
E ModuleNotFoundError: No module named 'hello'
包结构
root/
+--- src/
| +--- hello/
| +--- __init__.py
| +--- hello.py
|
+--- tests/
| +--- test_hello.py
|
+--- setup.py
+--- tox.ini
init.py
from .hello import Hello # noqa
tox.ini
[tox]
envlist = py39
skipsdist = True
[testenv]
deps =
flake8
pytest
pytest-cov
safety
commands =
pip install -e .
safety check --full-report
flake8 --max-line-length=120 --statistics setup.py src/ tests/
pytest -p no:warnings --cov=src --cov-fail-under=80 --cov-report=term --cov-report=xml --
junit-xml report.xml
test_hello.py
import os
from hello import Hello
running_in_ci = os.environ.get('CI_JOB_ID') is not None
test_name = 'Bob'
def test_hello():
"""Check if search returns expected results."""
cli = Hello(name=test_name)
assert cli.say_hello() is None
assert cli.say_hello(by_name=True) is None
【问题讨论】:
标签: python pycharm package pytest tox