gpt4 book ai didi

python - 通过模拟在单元测试上运行coverage.py

转载 作者:太空宇宙 更新时间:2023-11-03 17:52:42 26 4
gpt4 key购买 nike

我正在尝试对程序的单元测试运行代码覆盖率。我在测试中使用模拟,这意味着我必须使用 python3 及更高版本。我已经使用 pip 安装了coverage.py:

pip install coverage

安装成功,覆盖范围正常。问题是,当我尝试对单元测试进行覆盖时,它使用 python2.6 运行,并且在导入模拟时失败,尽管我的脚本以 #!/usr/bin/python3 开头:

coverage run ./my_tests.py

回溯(最近一次调用最后一次):
文件“./my_tests.py”,第 9 行,模块
从unittest.mock导入补丁
导入错误:没有名为模拟的模块

有没有办法配置覆盖范围以使用 python3 运行?是否有默认适用于 python3 的覆盖版本?

最佳答案

你显然有 2.6 作为你的默认 python。或者至少,您在 2.6 树中安装了coveragepy 模块,该模块将“coverage”放入 python26/Scripts 中,然后使用 2.6 运行coveragepy。但是,如果您显式使用其中之一而不是仅使用默认值来运行该模块,则该模块可以与 2.x 和 3.x 一起使用。

我碰巧通过将coveragepy克隆到我的dev目录中来“安装”它。我还为我的特殊需要编写了一个 cover.bat,即在提交之前在我的 python 存储库克隆中测试新的和修补的空闲库文件。这是我的文件。与您的问题特别相关的是以 %py% 开头的行。我将其设置为我的存储库版本 3.4,但您可以轻松地将其指向已安装的 3.4,甚至将其作为输入。

@echo off
rem Usage: cover fileName [test_ suffix] # proper case required by coveragepy
rem filename without .py, 2nd parameter if test is not test_filename
setlocal
set py=34\pcbuild\python_d
set src=idlelib.%1
if "%2" EQU "" set tst=34/Lib/idlelib/idle_test/test_%1.py
if "%2" NEQ "" set tst=34/Lib/idlelib/idle_test/test_%2.py

%py% coveragepy run --pylib --source=%src% %tst%
%py% coveragepy report --show-missing
%py% coveragepy html
htmlcov\34_Lib_idlelib_%1.html
rem Above opens new report; htmlcov\index.html displays report index

关于python - 通过模拟在单元测试上运行coverage.py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28914694/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com