【Python教程】pytest中一次请求多个fixtures及多次请求方法详解

所需工具:

Python

聪明的大脑

勤劳的双手

 

注意:本站只提供教程,不提供任何成品+工具+软件链接,仅限用于学习和研究,禁止商业用途,未经允许禁止转载/分享等

 

教程如下

跟着节奏继续来探索fixtures的灵活性。

一、一个测试函数/fixture一次请求多个fixture

在测试函数和fixture函数中,每一次并不局限于请求一个fixture。他们想要多少就可以要多少。

下面是另一个简单的例子:


 	import pytest
 	# Arrange
 	@pytest.fixture
 	def first_entry():
 	     return "a"
 	# Arrange
 	@pytest.fixture
 	def second_entry():
 	     return 2
 	# Arrange
 	@pytest.fixture
 	def order(first_entry, second_entry):
 	     # 这是一个fixture函数,请求了2个其他的fixture函数
 	     return [first_entry, second_entry]
 	# Arrange
 	@pytest.fixture
 	def expected_list():
 	     return ["a", 2, 3.0]
 	def test_string(order, expected_list):
 	     # 这是一个测试函数,请求了2个不同的fixture函数
 	     # Act
 	     order.append(3.0)
 	     # Assert
 	     assert order == expected_list

可以看出,在fixture函数order中,请求了2个其他的fixture函数,分别是:first_entry、second_entry。

在测试函数test_string中,请求了2个不同的fixture函数,分别是:order、expected_list。

二、每个测试函数可以多次请求fixtures(返回值被缓存)

在同一个测试函数中,fixture也可以被请求多次。但是在这个测试函数中,pytest在第一次执行fixture函数之后,不会再次执行它们。

如果第一次执行fixture函数有返回值,那么返回值会被缓存起来。


 	import pytest
 	# Arrange
 	@pytest.fixture
 	def first_entry():
 	     return "a"
 	# Arrange
 	@pytest.fixture
 	def order():
 	     return []
 	# Act
 	@pytest.fixture
 	def append_first(order, first_entry):
 	     # 在这里order第一次被请求,返回一个列表[]
 	     # 接着,order空列表增加了first_entry的返回值,此时的order变成了["a"],被缓存起来
 	     return order.append(first_entry)
 	def test_string_only(append_first, order, first_entry):
 	     # 在测试函数里,order第二次被请求,但是并不会拿到空列表[],而且拿到了被缓存起来的["a"]
 	     # 所以断言order == [first_entry],其实就是 ["a"] == ["a"],测试通过
 	     # Assert
 	     assert order == [first_entry]

从示例中可以看出:

在fixture函数append_first中,order第一次被请求,返回一个列表[],被缓存起来。
接着,order.append(first_entry)在[]中增加了first_entry的返回值,所以,此时的order变成了[“a”]。
最后,在测试函数test_string_only中,order第二次被请求,但是并不会拿到空列表[],而且拿到了被缓存起来的[“a”]。这样的话,最后的断言assert order == [first_entry]就会成功。

反过来,如果同一个fixture在一个测试函数中每次都去请求一次,那上面的测试函数必然失败。

因为,这样一来,虽然在append_first中的返回值仍然是[“a”],但是在test_string_only中,又去重新请求了一次order,拿到的其实是空列表[],所以最后断言会失败。

标签

发表评论