Pytest-Fixture妙用
作者:互联网
1 每次测试可以多次请求fixture(缓存返回值)
原文:Fixtures can also be requested more than once during the same test, and pytest won’t execute them again for that test.
This means we can request fixtures in multiple fixtures that are dependent on them (and even again in the test itself)
without those fixtures being executed more than once.
意思就是在一个test用例中可以对同一个fixture进行多次请求,pytest仅会执行一次,下面看个例子。
1 import pytest 2 3 4 # Arrange 5 @pytest.fixture 6 def first_entry(): 7 return "a" 8 9 10 # Arrange 11 @pytest.fixture 12 def order(): 13 return [] 14 15 16 # Act 17 @pytest.fixture 18 def append_first(order, first_entry): 19 return order.append(first_entry) 20 21 22 def test_string_only(append_first, order, first_entry): 23 # Assert 24 assert order == [first_entry]
如果在一个 test 用例中每请求一次fixture时,都将该 fixture 执行一遍,那么这个测试会失败。因为 append_first 和 test_string_only 都会将 order 视为一个空列表,
但是 pytest 会在第一次访问 order 时缓存 order 的返回值,在整个 test 用例和 append_first 中都引用相同的 order 对象,因此 append_first 里面是对该 order 对象进行的操作。
可以用 --setup-show 参数观察 fixture 的访问过程,可以看到 order 仅被执行一次
标签:妙用,Fixture,fixture,pytest,Pytest,test,order,append,first 来源: https://www.cnblogs.com/sheehan-dali/p/16448809.html