gpt4 book ai didi

python - py.test 运行 Python2 和 Python3

转载 作者:太空狗 更新时间:2023-10-29 21:06:08 27 4
gpt4 key购买 nike

我编写了一个包 ( http://github.com/anntzer/parsedcmd ),它可以在 Python2 和 Python3 上运行。但是,我不得不为 Python2 和 Python3 编写单独的 (py.test) 单元测试(主要是因为我想测试 Python3 的额外功能,特别是仅关键字参数),所以我有一个 test_py2.py和一个 test_py3.pytest分包。现在,如果我跑,说 py.test2 mypkg , test_py2通过,但是 test_py3失败并显示 SyntaxError .同样,对于 py.test3 mypkg , test_py3通过但test_py2失败(虽然我可以让这个工作,这只是一个问题 StringIO 已经移动到 io )。

我可以设计 test分包以便 import mypkg.test只导入正确版本的测试,但显然 py.test 并不关心——它只看到两个文件匹配 test_*并捕获他们两个的所有测试,忽略什么 __init__.py告诉他导入。

所以现在我必须同时做这两件事 py.test2 mypkg/test/test_py2.pypy.test3 mypkg/test/test_py3.py .有没有办法设置整个事情,以便 py.test2 mypkgpy.test3 mypkg会“正常工作”吗?

谢谢。

最佳答案

如果您可以让您的模块在所有解释器上都可导入并适本地跳过测试是一个常见的解决方案。否则,您可以将以下内容作为“conftest.py”放入测试目录:

import sys
py3 = sys.version_info[0] >= 3

class DummyCollector(pytest.collect.File):
def collect(self):
return []

def pytest_pycollect_makemodule(path, parent):
bn = path.basename
if "py3" in bn and not py3 or ("py2" in bn and py3):
return DummyCollector(path, parent=parent)

这会选择一个特定于项目的插件,并将正确地忽略文件名包含错误解释器版本上的“py2”或“py3”子字符串的测试模块。当然,您可以将其改进为直接在 conftest.py 文件中有一个显式列表,而不是检查文件名等。pp。

HTH,霍尔格

关于python - py.test 运行 Python2 和 Python3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10347178/

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