2

我正在尝试使用 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

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

4

1 回答 1

3

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

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

考虑改为使用工厂:

@attr.s
class Receiver:
    internal_dict = attr.ib(factory=dict)
于 2018-09-24T23:09:41.017 回答