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

10-12 18:46