我需要一个运行setup / teardown的基类,然后运行继承的子类,以便允许所有测试运行,无论某些测试是否失败。当试图有多个导入基类的子类时,我看到第二个子类的导入错误。我有以下文件:
runtestcases.py
testcase1.py
testcase2.py
这是runtestcases.py:
import unittest
import testcase1, testcase2
class ArithTestSuper (unittest.TestCase):
def setUp (self):
print("Setting up ArithTest cases")
def tearDown (self):
print("Cleaning up ArithTest cases")
def my_suite():
suite = unittest.TestSuite()
suite.addTest (testcase1.ArithTest())
suite.addTest (testcase2.ArithTestFail())
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
test_suite = my_suite()
runner.run (test_suite)
这是testcase1.py:
from runtestcases import ArithTestSuper
class ArithTest (ArithTestSuper):
def runTest (self):
""" Test addition and succeed. """
print("Running ArithTest")
self.failUnless (1+1==2, 'one plus one fails!')
self.failIf (1+1 != 2, 'one plus one fails again!')
self.failUnlessEqual (1+1, 2, 'more trouble with one plus one!')
这是testcase2.py:
from runtestcases import ArithTestSuper
class ArithTestFail (ArithTestSuper):
def runTest (self):
""" Test addition and fail. """
print("Running ArithTestFail")
self.failUnless (1+1==2, 'one plus one fails!')
self.failIf (1+1 != 2, 'one plus one fails again!')
self.failUnlessEqual (1+1, 2, 'more trouble with one plus one!')
self.failIfEqual (1+1, 2, 'expected failure here')
self.failIfEqual (1+1, 2, 'second failure')
Compilation fails on testcase2.py with:
ImportError: cannot import name ArithTestSuper
如果我只运行testcase1它也可以运行 - 同样,只运行testcase2。如果我尝试这两个错误发生。想法?
答案 0 :(得分:2)
这是循环导入的问题。将基类移出您运行的模块。
答案 1 :(得分:0)
回答第二个问题(https://stackoverflow.com/a/12885312/1745627):避免覆盖runTest
方法;它由unittest框架调用,基本上可以运行你的测试用例。使用命名约定test_xxx
实现您自己的测试方法(unittest查找以test
开头的方法来执行)。