如何从不同的基类调用函数

2024-06-13 22:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

基于我有限的Python知识,我生成了以下代码片段:

#import statements skipped
class DTestWrapper(BaseA if inLinux else unittest.TestCase):

    def setUpDTest(self):
        if inLinux:
            super(BaseA , self).setUpTestCase()
        else:
            super(unittest.TestCase, self).setUp()

    def tearDownDTest(self):
        if inLinux:
            super(BaseA ,self).tearDownTestCase()
        else:
            super(unittest.TestCase,self).tearDown()

一些背景:
BaseA是一个自定义类,用于将测试输出美化为表。它有成员函数setUpTestCasetearDownTestCase和许多其他函数。在

我想做什么
我想为我自己的类setUptearDown基于不同平台调用不同的setUp和{}函数,如上面的代码所示。当它在Linux上运行时,我希望使用BaseAsetUp和{}函数;否则,我希望使用python unittest.TestCase中的函数。我有另一个继承自DTestWrapper的类D,它将重写setUpDTest方法,但为了测试目的,它目前只是空的。在

问题:
当我运行上面的代码片段时,似乎没有调用setUp或{}(测试都失败了,如果调用正确,就不应该调用它们)。 我的问题是:

如何在DTestWrapper中调用不同的setUp函数?这有可能吗?

因为我在学习,任何反馈都是非常感谢。非常感谢。在


Tags: 函数代码selfifdefsetupunittesttestcase
2条回答

super()需要current类以搜索父类为基础:

class DTestWrapper(BaseA if inLinux else unittest.TestCase):
    def setUpDTest(self):
        parent_method = 'setUpTestCase' if inLinux else 'setUp'
        getattr(super(DTestWrapper, self), parent_method)()

    def tearDownDTest(self):
        parent_method = 'tearDownTestCase' if inLinux else 'tearDown'
        getattr(super(DTestWrapper, self), parent_method)()

您可能希望将BaseA方法名与unittest.TestCase方法相匹配,并为自己节省额外的if测试。例如,简单的别名可以;BaseA.tearDown = BaseA.tearDownTestCase。在

super()需要当前类来确定正确的方法解析顺序,这完全取决于基类的组合和顺序。如果给它一个基类从开始,那么super()将跳过该基类上的任何方法,因为它必须假定该基类是父类。在

如果可能的话,我会尝试将您的自定义方法重命名为setUp和{}。在

这样,一旦类被实例化(子类化unittest.TestCase或{}取决于inLinux变量),将自动调用正确的方法,而无需重新定义它们。在

如果您确实需要扩展它们,那么

class DTestWrapper(BaseA if inLinux else unittest.TestCase):

    def setUp(self):
        super(DTestWrapper, self).setUp()
        # your custom logic

    def tearDown(self):
        super(DTestWrapper, self).tearDown()
        # your custom logic

应该可以。在

相关问题 更多 >