简体   繁体   English

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

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

I am writing unit tests and have the following structure:我正在编写单元测试并具有以下结构:

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
...

As noted in my comments, I'd like to use some validation methods from HelperClass in my setUpClass method, but if I try to call with cls.method_name(), I get TypeError: method_name() missing 1 required positional argument: 'self' , but if I use self.method_name(), I get NameError: name 'self' is not defined .正如我的评论中所指出的,我想在我的 setUpClass 方法中使用 HelperClass 中的一些验证方法,但是如果我尝试使用 cls.method_name() 调用,我会得到TypeError: method_name() missing 1 required positional argument: 'self' ,但如果我使用 self.method_name(),我会得到NameError: name 'self' is not defined

This is probably something pretty basic, but I'm just not sure the correct search term I'm supposed to use to find the answer.这可能是非常基本的东西,但我不确定我应该用来找到答案的正确搜索词。 The unittest documentation on setUpClass doesn't get into it either, unfortunately.不幸的是,有关 setUpClass 的 unittest 文档也没有涉及。

The problem is that in setUpClass , you simply don't have an instance of TestSuite on which you can call instance methods defined by HelperClass .问题是,在setUpClass ,你根本就没有的一个实例TestSuite上,你可以调用定义的实例方法HelperClass The test runner does something along the lines of测试运行器按照以下方式做一些事情

TestSuite.setUpClass()

t = TestSuite(...)

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

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

setUpClass is called once , without an instance of TestSuite , before you create the single instance that will be used to call each test defined in the class.在您创建将用于调用类中定义的每个测试的单个实例之前, setUpClass被调用一次,没有TestSuite的实例。 The setUp and tearDown methods are called before and after, respectively, each test. setUptearDown方法分别在每次测试之前和之后调用。

What you might want is to override TestSuite.__init__ , which is called once per instance, rather than before each test method is called.可能想要的是覆盖TestSuite.__init__ ,每个实例调用一次,而不是在调用每个测试方法之前。

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

I don't know if it was the right solution, but I found a way to do this that was ultimately pretty obvious.我不知道这是否是正确的解决方案,但我找到了一种最终非常明显的方法。

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
...

In retrospect, I should have seen this right away, haha.回想起来,我应该马上看到这个,哈哈。 Figured I'd share for someone also searching around on this someday.想我会分享给有人也在寻找有一天。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM