pytest 运行测试出现 No module named 错误


环境

  • python 2.7 虚拟环境下已经安装pytest 4.6.11
  • 文件结构: ./src/__init__.py ./src/main.py ./tests/__init__.py ./tests/one/__init__.py ./tests/one/test_one.py
  • ./tests/one/test_one.py 第一行加入 from src import main
  • 项目根目录运行 pytest 出现错误 No module named src

解决

  • python -m pytest

关于 python -m pytestpytest 的区别

  • 前者会将当前目录加入sys.path
  • https://docs.pytest.org/en/6.2.x/pythonpath.html#pytest-vs-python-m-pytest