运行单元测试套件 OO 时出问题

1 投票
2 回答
1024 浏览
提问于 2025-04-15 21:24

我有一个测试套件用来进行冒烟测试。我把所有的脚本都存放在不同的类里,但当我尝试运行这个测试套件时,如果它在一个类里面,我就无法让它正常工作。下面是代码:(一个用来调用测试的类)

from alltests import SmokeTests

class CallTests(SmokeTests):

    def integration(self):

        self.suite()

if __name__ == '__main__':
    run = CallTests()
    run.integration()

还有测试套件:

class SmokeTests():

    def suite(self): #Function stores all the modules to be tested 
        modules_to_test = ('external_sanity', 'internal_sanity')
        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')

这输出了一个错误: 属性错误:'模块'对象没有属性'suite'

我能看到怎么调用一个普通的函数,但我发现调用这个套件有点困难。在其中一个测试中,套件是这样设置的:

class InternalSanityTestSuite(unittest.TestSuite):

# Tests to be tested by test suite
def makeInternalSanityTestSuite():
    suite = unittest.TestSuite()
    suite.addTest(TestInternalSanity("BasicInternalSanity"))
    suite.addTest(TestInternalSanity("VerifyInternalSanityTestFail"))
    return suite

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

如果我把someSuite()放在SmokeTests类里面,Python就找不到属性suite,但如果我把类去掉,它就能工作。我是以脚本的方式运行这个,调用变量到测试中。我不想通过os.system('python tests.py')来运行测试。我希望能像调用其他函数一样,通过我定义的类来调用测试。

有没有人能帮我解决这个问题?

提前感谢任何帮助。

2 个回答

1

这个是行不通的:

class SmokeTests():

    def suite(self): #Function stores all the modules to be tested 
        modules_to_test = ('external_sanity', 'internal_sanity')
        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')

这个会输出一个错误:属性错误:'模块'对象没有属性'suite'。

你的'suite'是SmokeTests().suite()方法的返回值。注意这里提到的变量名suite,因为你并没有定义这样一个变量。

其实用一个简单的函数来代替'suite'会更容易。

def someSuite():
    modules_to_test
    ...
    return alltests

if __name__ == "__main__":
    unittest.main( defaultTest= someSuite() )

像这样的写法会更接近正确。

3

我知道这不是直接的答案,但我建议你使用一些可以自动发现测试用例的库,比如Python 2.7及以上版本的nose或unittest。

这样做的可能性

nosetests module.submodule

或者

nosetests module.submodule:TestCase.test_method

是非常宝贵的哦 :)

撰写回答