0

我需要有一个运行 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 也可以。如果我尝试这两种错误都会发生。想法?

4

2 回答 2

2

这是循环导入的问题。将您的基类移出您运行的模块。

于 2012-10-14T16:05:45.903 回答
0

要回答您的第二个问题(https://stackoverflow.com/a/12885312/1745627):避免覆盖该runTest方法;它将由 unittest 框架调用,并且基本上完成了运行测试用例的工作。使用命名约定实现您自己的测试方法,例如test_xxx(unittest 查找以执行开头的方法test)。

于 2012-10-15T01:33:45.870 回答