【问题标题】:How do i create a test Suite in python unittest如何在 python unittest 中创建测试套件
【发布时间】:2011-11-02 14:57:41
【问题描述】:

我试过了:

def buildTestSuite():
    suite = unittest.TestSuite()
    for testcase in glob.glob('src/testsuite/test_*.py'):
        module = os.path.splitext(testcase)[0]
        print module
        print type(module)
        suite.addTest(__import__(module).buildTestSuite())
    return suite

但我得到了错误:

Traceback (most recent call last):
  File "runtests.py", line 63, in ?
    results = main()
  File "runtests.py", line 57, in main
    results = unittest.TextTestRunner().run(buildTestSuite())
  File "runtests.py", line 53, in buildTestSuite
    suite.addTest(__import__(module).buildTestSuite())
AttributeError: 'module' object has no attribute 'buildTestSuite'

【问题讨论】:

    标签: python python-unittest


    【解决方案1】:
    def buildTestSuite():
        suite = unittest.TestSuite()
        for testcase in glob.glob('src/testsuite/test_*.py'):
            modname = os.path.splitext(testcase)[0]
            module=__import__(modname,{},{},['1'])
            suite.addTest(unittest.TestLoader().loadTestsFromModule(module))
        return suite
    

    【讨论】:

    • 错误:回溯(最近一次调用最后一次):文件“runtests.py”,第 64 行,在?结果 = main() 文件“runtests.py”,第 58 行,主要结果 = unittest.TextTestRunner().run(buildTestSuite()) 文件“runtests.py”,第 52 行,在 buildTestSuite 模块 =__import__(modname, fromlist ='1') TypeError: __import__() 没有关键字参数
    • __import__ 在 Python2.6+ 中接受关键字参数(至少)。你用的是什么版本的 Python?
    • I see。而不是使用sys.modules,我认为module=__import__(modname,{},{},['1']) 也应该可以工作。
    【解决方案2】:

    尝试类似:

    suite = unittest.TestSuite()
    for t in glob.glob('src/testsuite/test_*.py'):
        try:
            # If the module defines a suite() function, call it to get the suite.
            mod = __import__(t, globals(), locals(), ['suite'])
            suitefn = getattr(mod, 'suite')
            suite.addTest(suitefn())
        except (ImportError, AttributeError):
            # else, just load all the test cases from the module.
            suite.addTest(unittest.defaultTestLoader.loadTestsFromName(t))
    

    【讨论】:

    • 我得到错误:回溯(最近一次调用最后一次):文件“runtests.py”,第 76 行,在?结果 = main() 文件“runtests.py”,第 70 行,主要结果 = unittest.TextTestRunner().run(buildTestSuite()) 文件“/usr/lib64/python2.4/unittest.py”,第 696 行,在运行测试(结果)TypeError:'NoneType'对象不可调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2014-06-16
    相关资源
    最近更新 更多