網站首頁 編程語言 正文
跟著節奏繼續來探索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,拿到的其實是空列表[],所以最后斷言會失敗。
原文鏈接:https://www.cnblogs.com/pingguo-softwaretesting/p/14474056.html
相關推薦
- 2022-07-09 document.write() 的作用*
- 2022-11-10 Android開發Jetpack組件ViewModel與LiveData使用講解_Android
- 2022-03-26 使用C語言如何輸出逆序數_C 語言
- 2022-12-11 詳解Android?GLide圖片加載常用幾種方法_Android
- 2023-01-20 React?Redux管理庫示例詳解_React
- 2022-09-16 詳解C++?中?shared_ptr?weak_ptr_C 語言
- 2022-08-25 基于Python編寫一個點名器的示例代碼_python
- 2023-11-11 微信 小程序 在電腦PC端無法加載的解決辦法。電腦微信小程序打不開是怎么回事?電腦微信小程序不能打開
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支