[英]ImportError cannot import name when using baseclass with multiple subclasses
I need to have a base class that runs setup/teardown, then subclasses that inherit, in order to allow for all tests to run regardless if certain ones fail. 我需要有一个运行setup / teardown的基类,然后是继承的子类,以便允许所有测试运行,无论某些测试是否失败。 When attempting to have multiple subclasses that import a base class, I see an import error for the second subclass. 当试图有多个导入基类的子类时,我看到第二个子类的导入错误。 I have the following files: runtestcases.py
testcase1.py
testcase2.py
我有以下文件: runtestcases.py
testcase1.py
testcase2.py
Here is runtestcases.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)
Here is testcase1.py: 这是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!')
Here is testcase2.py: 这是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
If I run just testcase1 it works - likewise, running just testcase2 works. 如果我只运行testcase1它也可以运行 - 同样,只运行testcase2。 If I try both this error occurs. 如果我尝试这两个错误发生。 Thoughts? 思考?
This is a problem with circular imports. 这是循环导入的问题。 Move your base class out of the module you run. 将基类移出您运行的模块。
To answer your second question ( https://stackoverflow.com/a/12885312/1745627 ): avoid overriding the runTest
method; 要回答你的第二个问题( https://stackoverflow.com/a/12885312/1745627 ):避免覆盖runTest
方法; it is to be called by the unittest framework, and essentially does the job of runing your testcase. 它由unittest框架调用,基本上可以运行你的测试用例。 Implement your own test methods using a naming convention like test_xxx
(unittest looks for methods starting with test
to execute). 使用命令约定(如test_xxx
实现自己的测试方法(unittest查找以test
开始执行的方法)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.