python - 为什么pytest调用重复方法

标签 python pytest self

<分区>

为什么会这样? 重复调用,因为我添加了“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%]

有人帮帮我吗?

最佳答案

那是因为您在 setup_method 中向记录器添加了一个 StreamHandlerwhich will be called once for each test run .如果同时运行这两个测试会发生什么:

  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')

    ...

关于python - 为什么pytest调用重复方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47690250/

相关文章:

python-2.7 - pytest-timeit或pytest-benchmark在精度s上哪个更好?

python - 'py.test' 不是内部或外部命令,也不是可运行的程序或批处理文件

python - 使用 pytest 和 unittest runner 从两个终端运行测试套件,但仅显示 unittest runner 结果并执行一次

ios - 在 block 中使用局部变量名称 "self"是否正确?

mongodb - 使用 MongoDB 进行自引用更新

Python:从列表中删除逗号,以便我可以使用 pandas 将数据导入到 Excel 中的单独单元格中

python - 用redis或者mongodb存储用户信息

python - 更好的设计以避免违反 Liskov 替换原则

python - 通过实例方法操作实例本身

python - 使用 langchain PyPDFLoader 在 python 笔记本中加载在线 pdf 的问题