测试套件unittest

时间:2010-01-21 16:22:21

标签: python unit-testing testing test-suite

我有一个测试套件,我试图让它与我创建的测试一起工作。测试工作如果我单独运行它们但我想在测试套件中运行它们。下面的代码显示了创建的测试套件:

import unittest

def suite():
    modules_to_test = ('TestAbsoluteMove', 'TestContinuousMove') # and so on
    alltests = unittest.TestSuite()
    for module in map(__import__, modules_to_test):
        alltests.addTest(unittest.findTestCases(module))
    return alltests

if __name__ == '__main__':
    unittest.main(defaultTest='suite')

我已将此代码放入我的测试代码中以连接套件:

class AbsoluteMoveTestSuite(unittest.TestSuite):

def makeAbsoluteMoveTestSuite():
    suite = unittest.TestSuite()
    suite.addTest(TestAbsoluteMove("BasicAbsolutePan"))
    suite.addTest(TestAbsoluteMove("VerifyAbsolutePan"))
    suite.addTest(TestAbsoluteMove("VerifyAbsoluteTilt"))
    suite.addTest(TestAbsoluteMove("VerifyAbsolutePanSpeed"))
    suite.addTest(TestAbsoluteMove("VerifyAbsoluteTiltSpeed"))
    return suite

def suite():
    return unittest.makeSuite(TestAbsoluteMove)

产生的错误声称没有名为'TestAbsoluteMove'和TestContinuousMove'的模块。有谁知道如何使这段代码有效?

由于

4 个答案:

答案 0 :(得分:2)

Nose使这种事情变得简单。它会自动检测您的测试并将其作为套件运行。 (您也可以通过传递标志来运行特定测试。)

答案 1 :(得分:2)

TestAbsoluteMove是一个类,它需要来自某个地方。无论在何处定义AbsoluteMoveTestSuite类,都需要导入TestAbsoluteMove。

答案 2 :(得分:2)

这就是我创建testsuite的方法(loadTestFromTestCase自动检测你的测试)

def suite():
    """ returns all the testcases in this module """
    return TestLoader().loadTestsFromTestCase(AbsoluteMoveTestSuite)

并立即运行它们我有一个包含所有子套件的套件(注意所有导入,你需要在它们在新模块中可用之前导入它们)

import sys
import unittest

import test.framework.asyncprocess as a
import test.framework.easyconfig as e
import test.framework.modulegenerator as mg
import test.framework.modules as m
import test.framework.filetools as f
import test.framework.repository as r
import test.framework.robot as robot
import test.framework.easyblock as b
import test.framework.variables as v
import test.framework.github as g
import test.framework.toolchainvariables as tcv
import test.framework.toolchain as tc
import test.framework.options as o
import test.framework.config as c


# call suite() for each module and then run them all
SUITE = unittest.TestSuite([x.suite() for x in [r, e, mg, m, f, a, robot, b, v, g, tcv, tc, o, c]])

# uses XMLTestRunner if possible, so we can output an XML file that can be supplied to Jenkins
xml_msg = ""
try:
    import xmlrunner  # requires unittest-xml-reporting package
    xml_dir = 'test-reports'
    res = xmlrunner.XMLTestRunner(output=xml_dir, verbosity=1).run(SUITE)
    xml_msg = ", XML output of tests available in %s directory" % xml_dir
except ImportError, err:
    sys.stderr.write("WARNING: xmlrunner module not available, falling back to using unittest...\n\n")
    res = unittest.TextTestRunner().run(SUITE)

答案 3 :(得分:0)

像这样使用

unittest有点痛苦。我非常推荐您按照Alison的建议查看nose或使用我个人喜欢的Python测试工具py.test。只需按照特定的命名约定创建函数,然后让它翻录!整个xUnit事物并不适合Python领域。