子类化python unittest.Testcase,调用相同的main

时间:2012-01-22 20:35:10

标签: python syntactic-sugar

我想创建一个名为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

3 个答案:

答案 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__"代码无法访问。

多尔的建议或类似的东西似乎最合理。 但是,如果您无法访问相关模块,则可以考虑将执行模块的runpy.run_module()视为主要模块。

答案 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