gpt4 book ai didi

python - 测试顺序在 python 2 上工作完美,但在 python 3 上不工作

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:40 26 4
gpt4 key购买 nike

我正在使用 unittes 编写我的测试用例。据我了解,unittest 默认情况下按字母顺序处理测试类中的测试类和测试方法(即使 loader.sortTestMethodsUsing 为 None)。所以我找到了一些解决方案 here它在 python 2 上确实运行良好。当我尝试在 python 3 上运行此解决方案时,出现错误 NameError: name 'cmp' is not defined 所以我找到了关于如何解决这个问题的答案问题 here .我在另一个文件中创建函数,然后导入 cmp()。但我在订购测试时仍然遇到问题,我不知道为什么。

cmp_f.py

def cmp(a, b):
return (a > b) - (a < b)

test_f.py

import unittest
from cmp_f import cmp


class Login(unittest.TestCase):

def test_remove_notes_and_reports(self):
print("1")

def test_login_app(self):
print("2")

def test_report_summary_after_edit(self):
print("3")

def test_report_summary(self):
print("4")


if __name__ == "__main__":
loader = unittest.TestLoader()
ln = lambda f: getattr(Login, f).im_func.func_code.co_firstlineno
lncmp = lambda a, b: cmp(ln(a), ln(b))
loader.sortTestMethodsUsing = lncmp
unittest.main(testLoader=loader, verbosity=2)

最佳答案

出现此问题的原因是,在 Py3k 中,在类上查找函数现在会生成原始函数而不是未绑定(bind)方法。在 Py2 中:

class Foo(object):
def bar(self):
pass

type(Foo.bar)
<type 'instancemethod'>

在 Python3 中

class Foo:
def bar(self):
pass

type(Foo.bar)
<class 'function'>

所以解决方案非常简单:您不需要 .im_func 部分。此外,function.func_code 现在被命名为 function.__code__。所以你想要类似的东西(警告:未经测试的代码):

ln = lambda f: getattr(Login, f).__code__.co_firstlineno

FWIW,您完全可以按照我的方式自行调试:检查 Python shell 中的内容(我花了大约 2 分钟才找到它 xD)。

关于python - 测试顺序在 python 2 上工作完美,但在 python 3 上不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58323278/

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