【问题标题】:Why pytest calls a duplicate method [duplicate]为什么pytest调用重复方法[重复]
【发布时间】:2017-12-07 08:00:40
【问题描述】:

为什么会这样? 重复调用,因为我添加了“self.log”

代码

import logging, logging.handlers
class TestCase:

    def setup_method(self,test_method):
            self.log = logging.getLogger('test')
            self.log.addHandler( logging.StreamHandler())

    def test_one(self):
            log = self.log
            log.info('one')
    def test_two(self):
            log = self.log
            log.info('two')

控制台

$pytest -s
=========================================== test session starts ===========================================
platform darwin -- Python 3.6.2, pytest-3.3.1, py-1.5.2, pluggy-0.6.0
rootdir: /Users/taeun/dev/workspace/test/pytest-test/tests, inifile:
collected 2 items

test_one.py one
.two
two
.                                                                                      [100%]

有人帮帮我吗?

【问题讨论】:

  • 请将您的源代码粘贴为文本,而不是图像。
  • 我刚刚更新了!谢谢

标签: python pytest self


【解决方案1】:

那是因为您在setup_methodwhich will be called once for each test run 中的记录器中添加了StreamHandler。如果同时运行两个测试会发生什么:

  1. setup_method 被调用,StreamHandler 的一个实例被添加到记录器中
  2. test_one 运行,记录器有一个处理程序将消息 one 发送到标准输出
  3. 第二次调用setup_method,将StreamHandler另一个实例添加到记录器处理程序
  4. test_two 运行,但现在记录器有两个处理程序,都将消息 two 发送到标准输出

要克服这个问题,您可以清理setup_method 中的处理程序,以确保每次测试运行都有一个StreamHandler

class TestCase:

    def setup_method(self):
        self.log = logging.getLogger('test')
        self.log.handlers = [h for h in self.log.handlers
                             if not isinstance(h, logging.StreamHandler)]
        self.log.addHandler(logging.StreamHandler())

        ...

或者您将记录器配置声明为一次性操作(如果您问我,这是一种更简洁的解决方案):

class TestCase:

    @classmethod
    def setup_class(cls):
        logging.getLogger('test').addHandler(logging.StreamHandler())

    def setup_method(self,test_method):
        self.log = logging.getLogger('test')

    ...

【讨论】:

  • 天哪...非常感谢您的友好回答(_ _)
  • @taeun 很高兴能帮到你!试一下代码,如果你的问题能解决,你可以考虑接受答案...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2011-05-08
  • 2021-02-08
  • 1970-01-01
相关资源
最近更新 更多