这是代码
import pytest
@pytest.fixture
def first_entry():
return "a"
@pytest.fixture(autouse=True)
def append_first(first_entry):
return [first_entry]
def test_string_only(first_entry):
assert first_entry == ["a"]
简单地从这里修改
我已经盯着它看了40分钟,不明白为什么在test_string_only中它仍然将first_entry识别为“a”而不是[“a”]?我认为 autouse=True 的装置将在每个测试用例中执行?
错误日志
======================================================= FAILURES ========================================================
___________________________________________________ test_string_only ____________________________________________________
first_entry = 'a'
def test_string_only(first_entry):
> assert first_entry == ["a"]
E AssertionError: assert 'a' == ['a']
test_fixture2.py:24: AssertionError
我会根据我的评论做出回答,因为这可能确实会让更多人感到困惑。
这里的问题是问题中提到的pytest文档中的示例,它被用作模板:
@pytest.fixture
def first_entry():
return "a"
@pytest.fixture
def order(first_entry):
return []
@pytest.fixture(autouse=True)
def append_first(order, first_entry):
return order.append(first_entry)
def test_string_only(order, first_entry):
assert order == [first_entry]
这不是一个很好的代码基础示例。这里发生的情况是,固定装置
order
返回一个空数组,并且固定装置 append_first
向该数组添加一个条目。由于 append_first
始终被调用,因此它始终将该条目附加到从第一个夹具返回的数组实例中。事实上,它也返回它与这种情况无关——只有直接调用夹具时才需要它。
所以如果使用:
@pytest.fixture(autouse=True)
def append_first(order, first_entry):
order.append(first_entry)
# does not return anything
会产生相同的效果,即更改第一个夹具返回的数组对象的副作用。
这是出乎意料且令人困惑的,在我看来,这与已知的反模式“将数组作为默认参数传递”非常相似。 如前所述,具有
autouse=True
的装置只有在具有副作用时才有意义,并且通常不会返回任何内容。它们可能会返回一个值,但只有直接使用夹具时才会使用该值,否则它将被丢弃。
在您的示例中,您根本不需要autouse
夹具,但可以直接引用夹具,正如其他答案中已经提到的:
@pytest.fixture
def first_entry():
return "a"
@pytest.fixture
def append_first(first_entry):
return [first_entry]
def test_string_only(append_first):
assert append_first == ["a"]
另请注意,当前文档中提到的
pytest
示例
已更改为不返回值,并收到了更好的解释。我相信你已经把你的论点搞混了。尝试将
append_first
以使测试正确通过。像这样:
import pytest
@pytest.fixture
def first_entry():
return "a"
@pytest.fixture(autouse=True)
def append_first(first_entry):
return [first_entry]
def test_string_only(append_first):
assert first_entry == ["a"]
就像评论所说,autouse
通常被用作产生副作用的一种方式。如果您打算将其用作后续方法的输入,则 autouse
是多余的。