unittest 执行测试用例的顺序

unittest中test cases执行的顺序,是根据test suite中加载到的test cases的顺序执行的。
因此,若要改变test cases执行顺序,可以直接将用例的顺序写在test suite中:
可以参考http://blog.csdn.net/u010895119/article/details/77484181末尾处。
上面这个方法的缺点在于:写起来很麻烦…………

另外一种方法是获取test cases names后,改变test cases names 的排序,默认的排序方法在load.py中:

class TestLoader(object):
    """
    This class is responsible for loading tests according to various criteria
    and returning them wrapped in a TestSuite
    """
    testMethodPrefix = 'test'
    sortTestMethodsUsing = cmp
    suiteClass = suite.TestSuite
    _top_level_dir = None
    …………………………
    def getTestCaseNames(self, testCaseClass):
    """Return a sorted sequence of method names found within testCaseClass
    """
    def isTestMethod(attrname, testCaseClass=testCaseClass,
        prefix=self.testMethodPrefix):
        return attrname.startswith(prefix) and \
                hasattr(getattr(testCaseClass, attrname), '__call__')
    testFnNames = filter(isTestMethod, dir(testCaseClass))
    if self.sortTestMethodsUsing:
        testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing))
    return testFnNames

testFnNames.sort(key=_CmpToKey(self.sortTestMethodsUsing)),
等价于:testFnNames.sort(cmp=cmp)
做个小验证:

test_list = [7, 3]
test_list.sort(cmp=cmp)
test_list
[3, 7]

即这种方法会按升序排列。
因此可以通过改变排序的方法(TestLoader().sortTestMethodsUsing)来改变用例在test suite中的排序。搜到以下方法:

from for_all import CasesALL
from unittest import TestLoader


def ln(f):
    print getattr(CasesALL, f).im_func.func_code.co_firstlineno
    return getattr(CasesALL, f).im_func.func_code.co_firstlineno


def ln_cmp(a, b):
    print cmp(ln(a), ln(b))
    return cmp(ln(a), ln(b))

loader = TestLoader()
loader.testMethodPrefix = 'ab'
loader.sortTestMethodsUsing = ln_cmp

即通过方法名对应的代码在python文件中的行数,来确定排序。即写在前面的方法先执行,写在后面的方法后执行。这个方法完美。

参考:
https://stackoverflow.com/questions/4005695/changing-order-of-unit-tests-in-python

猜你喜欢

转载自blog.csdn.net/u010895119/article/details/79165400