Pytest-Fixture妙用

2022/7/5 23:25:10

本文主要是介绍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 仅被执行一次

 

 

 



这篇关于Pytest-Fixture妙用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程