Python 覆盖率找不到我自己的模块

标签 python coverage.py

我的代码使用 python3 可以正确执行,但是在导入我创建的包时使用coverage3会返回一个 ImportError 。

我的项目如下所示:

components/common/ConfigTest/ConfigTest.py -> 我想要执行的文件 - 对 Config.py 中声明的 Config 类的测试

components/common/Config.py -> ConfigTest.py 中包含的文件

环境变量 PYTHONPATH 指向 components 目录的位置,因此我可以将其用作导入的基目录。

ConfigTest.py 文件开始如下:

import os
import unittest

from common.Config import Config

当位于 ConfigTest 目录中时,运行以下命令会产生预期的输出:

python3 -m unittest ConfigTest.py

但是,运行 coverage3 run ConfigTest.pycoverage3 run -m unittest ConfigTest.py 会产生以下错误:

Traceback (most recent call last):
File "ConfigTest.py", line 7, in <module>
from common.Config import Config
ImportError: No module named 'common.Config'

过去,我在不同机器/不同版本的Python上执行代码时遇到过类似的问题,这些问题是由于PYTHONPATH环境变量设置错误引起的。在这种情况下,我在执行有问题的导入之前打印了 print(os.environ['PYTHONPATH']) ,并且在使用 python3 和 Coverage3 时打印了此类 var 的正确值。

有任何关于问题可能出在哪里的线索吗? 谢谢。

最佳答案

我通过添加 __init__.py 解决了这个问题在源目录和测试目录中。看来 python3 能够通过使用 PYTHONPATH 找到源,即使目录没有 __init__.py文件,但coverage3要求将目录设置为模块。

这在我当前的配置中有效,但我不确定这是否是一般的 Python 和覆盖行为。

关于Python 覆盖率找不到我自己的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56057370/

相关文章:

python - 使用 urllib 和 Python 3.3 进行简单的 POST

python - 在 TD Ameritrade API 上创建触发止损订单时出现问题

python - “python setup.py notests”报告包的 __init__.py 未被测试覆盖

python - 排除 coverage 中的 'else' 子句

python - 如何在 bash 脚本中使用 Python 3.6 解释器?

python - 单元测试python时的多个异常和代码覆盖

python - 类型错误 : '>=' not supported between instances of 'int' and 'str' even with adding int to the front of score

python - 在networkx中制作二分图

python - django - form.cleaned_data[] 用于模型中的所有字段

python - 从覆盖率报告中删除包