python - pytest 在测试之间泄漏 attrs 对象

标签 python pytest python-attrs

我正在尝试使用 attr 类的两个不同实例(从函数范围的固定装置返回)作为输入参数在 pytest 中运行两个测试。第一个 msg 对象也出现在第二个测试中。我的例子:

import attr
import pytest
import uuid

@attr.s
class Receiver:
    internal_dict = attr.ib(default=dict())

    def send_message(self, msg):
        self.internal_dict[msg] = msg

@pytest.fixture
def msg():
    yield uuid.uuid1()

@pytest.fixture
def receiver():
    yield Receiver()

def test_send_msg_1(msg, receiver):
    receiver.send_message(msg)
    assert len(receiver.internal_dict) == 1

def test_send_msg_2(msg, receiver):
    receiver.send_message(msg)
    print("internal_dict:{}".format(receiver.internal_dict))
    assert len(receiver.internal_dict) == 1  # FAILS

两个测试之间的可变状态如何泄漏?

最佳答案

此代码共享相同 dict() 实例作为可变默认值:

@attr.s
class Receiver:
    internal_dict = attr.ib(default=dict())

考虑使用工厂:

@attr.s
class Receiver:
    internal_dict = attr.ib(factory=dict)

关于python - pytest 在测试之间泄漏 attrs 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52488478/

相关文章:

python - 为什么 pycharm 无法识别我的 pytest 测试并显示测试输出?

Python attrs - 父类(super class)中的位置属性而子类中可选

python - 销毁/清理对象实例时如何返回值

python - 从 Python 访问 Facebook

python - 带有 numpy ctypes 的大数组

python - LXML - 解析 tr 标签内的 td 内容

python - 如何在 py.test 终结器中打印内容

python - 如何将值传递给 Pytest fixture

python - Mypy 为带有 attrs 包的装饰类的子类返回错误 "Unexpected keyword argument"