为什么我在使用 pytest 进行测试时收到 ModuleNotFoundError?

Why I receive ModuleNotFoundError while testing using pytest?

我使用 pytest 进行单元测试,但收到此错误:

ModuleNotFoundError: No module named 'package'

当我在本地导入两个模块时:

from package import module1
from package import module2

当前工作目录如下所示:

├── package
│   ├── __init__.py
│   ├── module1.py
│   └── module2.py
├── requirements.txt
├── setup.py
├── test-requirements.txt
└── tests
    ├── test_module1.py
    ├── test_module2.py

尝试 运行 python -m pytest 或使用 pip install . 安装您的项目。它不能直接与 pytest 一起工作的原因是在这种情况下当前工作目录不会附加到 sys.path,即您的项目不可见。