setUpClass是否可以在最不合理的框架中扩展?

定义扩展unnitest.TestCase的Base1,Base1具有setUpClass方法。

import unittest
class Base1(unittest.TestCase):

@classmethod
def setUpClass(cls):
    print('setupClass - this is Base1')

@classmethod
def tearDownClass(cls):
    print('tearDownClass - this is Base1')


定义扩展Base1类的Base2

from Base1 import Base1
import unittest

class Base2(Base1):

@classmethod
def setUpClass(cls):
    print('setupClass - this is Base2')

@classmethod
def tearDownClass(cls):
    print('tearDownClass - this is Base2')

def test_default_size(self):
    self.assertEqual('a','a')

def test_resize(self):
    self.assertEqual('a','b')


我希望在Base2中的所有测试用例之前执行Base1中的setUpClass和Base2中的setUpClass,这可能吗?

最佳答案

您必须显式调用setUpClasstearDownClass

class Base2(Base1):
    @classmethod
    def setUpClass(cls):
        print('setupClass - this is Base2')
        super(Base2, cls).setUpClass()

    @classmethod
    def tearDownClass(cls):
        print('tearDownClass - this is Base2')
        super(Base2, cls).tearDownClass()


但是,如果不添加这些类方法,则可以跳过对它们的定义:

class Base3(Base1):,
    def test1(self):
        print('test1')


在这种情况下,setUpClass中的tearDownClassBase1将被隐式调用。

关于python - setUpClass是否可以在最不合理的框架中扩展?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37107185/

10-12 18:54