测试顺序在 python 2 上完美运行,但在 python 3 上不完美

The order of tests works perfect on python 2 but not on python 3

我正在使用 unittes 编写我的测试用例。据我所知,unittest 默认按字母顺序处理测试 类 和测试 类 中的测试方法(即使 loader.sortTestMethodsUsing 是 None)。所以我找到了一些解决方案here and it's really works fine on python 2. When I try to run this solution on python 3 I get the error NameError: name 'cmp' is not defined So I find the answer about how I can solve this problem 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 中,在 class 上查找函数现在会生成原始函数而不是未绑定方法。在 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)。