首页 > 解决方案 > Github pytest Action 无法从 tests/ 文件夹导入

问题描述

我有一个运行 pytest 的 GitHub 操作设置。这在大约一个月前有效,但现在突然出现以下错误:

==================================== ERRORS ====================================
_____________ ERROR collecting tests/test_encoding/test_encode.py ______________
import file mismatch:
imported module 'test_method' has this __file__ attribute:
  /home/runner/work/my_module/my_module/src/my_module/tests/test_package/test_method.py
which is not the same as the test file we want to collect:
  /home/runner/work/my_module/my_module/tests/test_package/test_method.py
HINT: remove __pycache__ / .pyc files and/or use a unique basename for your test file modules

对于我所有的测试文件,这是一个替换名称以提高可读性的示例。

它与我的目录的放置位置有关,但我不知道为什么它会这样改变?出于某种原因,它正在查看我的tests/文件夹/home/runner/work/my_module/my_module/src/my_module/而不是/home/runner/work/my_module/qiskit-quantum-knn/. 我从来没有src/在我的项目中添加过文件夹。我还检查了我是否不小心犯了__pycache__or .pytest_cache/,但事实并非如此。

我将当前日志几个月前的日志(成功)进行了比较,并且在作业设置和操作设置期间似乎完全相同。

在我的本地机器上运行pytest时,它工作得很好。我的项目结构如下:

my_module
├── docs/
├── my_module
│   ├── package1/
│   ├── package2/
└── tests/
    ├── test_package1/
    │   └── test_method1.py
    └── test_package2/
        └── test_method2.py

为真正想要深入了解日志的人添加了超链接。

标签: pythongithubpytestgithub-actions

解决方案


它必须与 pip 和 pytest 的版本有关,我没有在我的工作流程中固定它们。该解决方案是由我的一位好朋友找到的,并已在此pull request中修复。

这意味着将 a 添加pytest.ini到我的项目的根目录中,其中包含以下内容:

# pytest.ini
[pytest]
testpaths =
    tests
python_files = test_*.py
addopts = -rf --import-mode=importlib

推荐阅读