Python pytest在测试之间泄漏attrs对象

Python pytest在测试之间泄漏attrs对象,python,pytest,python-attrs,Python,Pytest,Python Attrs,我试图在pytest中运行两个测试,使用attr类的两个不同实例(从函数范围的fixture返回)作为输入参数。第一个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[

我试图在pytest中运行两个测试,使用attr类的两个不同实例(从函数范围的fixture返回)作为输入参数。第一个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)

实际上,这与pytest无关,而与定义
Receiver
类的方式有关。尽管pytest装置生成了两个不同的实例
Receiver()
,但它们都共享相同的
internal\u dict
属性,因为值
default=dict()
在类定义时只计算一次。因此,在没有使用dict的attrs的情况下,在定义不好的init中,可以复制此错误,如果您定义了一个init函数,比如
def\uu init\uuuu(self,internal\u dict={}):self.internal\u dict=internal\u dict
,则可以创建一个等效的“bug”,而不使用attr.s。