Python unittest -- 在我的 setUpClass 方法中使用父 class 方法?

Python unittest -- using parent class methods in my setUpClass method?

我正在编写单元测试并具有以下结构:

class TestSuite(unittest.TestCase, HelperClass):
  @classmethod
  def setUpClass(cls):
    # I want to use methods from HelperClass here, but get errors
    # I have tried cls.method_name() and self.method_name()

  def setUp(self):
    self.method_name() # methods from HelperClass work here
...

如我的评论所述,我想在我的 setUpClass 方法中使用 HelperClass 的一些验证方法,但如果我尝试使用 cls.method_name() 调用,我会得到 TypeError: method_name() missing 1 required positional argument: 'self',但是如果我使用 self.method_name(),我会得到 NameError: name 'self' is not defined

这可能是非常基础的内容,但我只是不确定应该使用正确的搜索词来找到答案。不幸的是,关于 setUpClass 的单元测试文档也没有涉及。

问题是在 setUpClass 中,您根本没有可以调用 HelperClass 定义的实例方法的 TestSuite 实例。测试运行器按照

的方式做了一些事情
TestSuite.setUpClass()

t = TestSuite(...)

t.setUp()
t.test_foo()
t.tearDown()

t.setUp()
t.test_bar()
t.tearDown()

setUpClass 被调用 一次 ,没有 TestSuite 的实例,在您创建将用于调用在class。 setUptearDown 方法分别在每次测试之前和之后调用。

可能想要的是覆盖TestSuite.__init__,每个实例调用一次,而不是在调用每个测试方法之前。

def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.method_name()

我不知道这是否是 正确的 解决方案,但我找到了一种最终非常明显的方法。

class TestSuite(unittest.TestCase, HelperClass):
  @classmethod
  def setUpClass(cls):
    hc = HelperClass()
    hc.method_name()

  def setUp(self):
    self.method_name() # methods from HelperClass work here
...

回想起来,我应该马上就看到了,哈哈。我想有一天我会分享给也在四处搜索的人。