那么有的时候,我们可能会写一个fixture,而这个fixture所有的测试函数都会用到它。那这个时候,就可以用
autouse
自动让所有的测试函数都请求它,不需要在每个测试函数里显示的请求一遍。
具体用法就是,将autouse=True
传递给fixture的装饰器即可。
import 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]
def test_string_and_int(order, first_entry):
order.append(2)
assert order == [first_entry, 2]
先来看第一个测试函数test_string_only(order, first_entry)
的执行情况:
- 虽然在测试函数里请求了2个fixture函数,但是
order
拿到的并不是[]
,first_entry
拿到的也并不是"a"
。 - 因为存在了一个
autouse=True
的fixture函数,所以append_first
先会被调用执行。 - 在执行
append_first
过程中,又分别请求了order、 first_entry
这2和fixture函数。 - 接着,
append_first
对分别拿到的[]
和"a"
进行append处理,最终返回了["a"]
。
所以,断言assert order == [first_entry]
是成功的。
同理,第二个测试函数test_string_and_int(order, first_entry)
的执行过程亦是如此。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。