我想创建一个名为BasicTest的python的unittest.Testcase的子类。我希望BasicTest的每个子类在main中运行相同的例程。我怎么能做到这一点?
示例:
in basic_test.py:
class BasicTest(unittest.TestCase):
...
if __name__ == '__main__':
# Do optparse stuff
unittest.main()
in some_basic_test.py:
class SomeBasicTest(BasicTest):
...
if __name__ == '__main__':
#call the main in basic_test.py
答案 0 :(得分:2)
# basic_test.py
class BasicTest(unittest.TestCase):
@staticmethod
def main():
# Do optparse stuff
unittest.main()
if __name__ == '__main__':
BasicTest.main()
# some_basic_test.py
class SomeBasicTest(BasicTest):
...
if __name__ == '__main__':
BasicTest.main()
答案 1 :(得分:1)
您无法(重新)将模块导入为新的主,因此if __name__=="__main__"
代码无法访问。
答案 2 :(得分:1)
我希望BasicTest的每个子类在main
中运行相同的例程
我想你想要的是在从任何测试用例运行测试之前运行一些设置/初始化代码。在这种情况下,您可能对setUpClass
类方法感兴趣。
testA.py
import unittest
class BasicTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
print 'Preparing to run tests'
class TestA(BasicTest):
def test1(self):
print 'testA: test1'
def test2(self):
print 'testA: test2'
if __name__ == '__main__':
unittest.main()
testB.py
import unittest
from testA import BasicTest
class TestB(BasicTest):
def test1(self):
print 'testB: test1'
def test2(self):
print 'testB: test2'
if __name__ == '__main__':
unittest.main()
testA.py的输出:
Preparing to run tests
testA: test1
testA: test2
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
testB.py的输出:
Preparing to run tests
testB: test1
testB: test2
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK