接口自動化——參數化

? ? ? ? 之前有說過,通過pytest測試框架標記參數化功能可以實現數據驅動測試。數據驅動測試使用的文件主要有以下類型:

  • txt 文件?
  • csv 文件
  • excel 文件
  • json 文件
  • yaml 文件
  • ....

本文主要講的就是以上幾種文件類型的讀取和使用

一.txt 文件讀取使用

? ? ? ? 首先創建一個 txt 文件,文件內容為:

張三,男,2024-09-10
李四,女,2022-09-10
王五,男,2090-09-10

?然后讀取文件內容

def get_txt_data():with open(r"D:\python_project\API_Auto\API3\data\txt_data", encoding="utf-8") as file:content = file.readlines()# print(content)# 去掉數據后面的換行符list_data = []list_data1 = []for i in content:list_data.append(i.strip())# 將數據分割for i in list_data:list_data1.append(i.split(","))return list_data1

這樣就得到了 符合參數化要求的參數,對讀取的內容進行使用:

@pytest.mark.parametrize(("name", "gender", "data"), get_txt_data())
def test_txt_func(name, gender, data):print(f'輸入名字:{name}')print(f'輸入性別 :{gender}')print(f'輸入日期:{data}')

輸出為:

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... [['張三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]
collected 3 itemstestcases/test_ddt.py::test_txt_func[張三-男-2024-09-10] 輸入名字:張三
輸入性別 :男
輸入日期:2024-09-10
PASSED
testcases/test_ddt.py::test_txt_func[李四-女-2022-09-10] 輸入名字:李四
輸入性別 :女
輸入日期:2022-09-10
PASSED
testcases/test_ddt.py::test_txt_func[王五-男-2090-09-10] 輸入名字:王五
輸入性別 :男
輸入日期:2090-09-10
PASSED============================== 3 passed in 0.06s ==============================
Report successfully generated to .\reportProcess finished with exit code 0

二.csv 文件讀取使用

首先創建一個csv文件,內容為:

1,2,3
1,3,3
2,2,4

?然后讀取文件內容

import csvdef get_csv_data():list1 = []f = csv.reader(open(r"D:\python_project\API_Auto\API3\data\x_y_z.csv", encoding="utf-8"))for i in f:# list1.append(i.strip())# [int(element) for element in i],  列表推導式,它的作用是對 i 中的每個元素進行遍歷,并將每個元素從字符串(str)轉換為整數(int)a = [int(element) for element in i]list1.append(a)return list1

然后使用讀取到的數據

@pytest.mark.parametrize(("x", "y", "z"), get_csv_data()
)
def test_csv_func(x, y, z):assert x * y == z

輸出為:

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... [['張三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]
collected 3 itemstestcases/test_ddt.py::test_csv_func[1-2-3] FAILED
testcases/test_ddt.py::test_csv_func[1-3-3] PASSED
testcases/test_ddt.py::test_csv_func[2-2-4] PASSED================================== FAILURES ===================================
____________________________ test_csv_func[1-2-3] _____________________________x = 1, y = 2, z = 3@pytest.mark.parametrize(("x", "y", "z"), get_csv_data())def test_csv_func(x, y, z):
>       assert x * y == z
E       assert (1 * 2) == 3testcases\test_ddt.py:21: AssertionError
----------------------------- Captured log setup ------------------------------
WARNING  pytest_result_log:plugin.py:122 ---------------Start: testcases/test_ddt.py::test_csv_func[1-2-3]---------------
---------------------------- Captured log teardown ----------------------------
WARNING  pytest_result_log:plugin.py:128 ----------------End: testcases/test_ddt.py::test_csv_func[1-2-3]----------------
=========================== short test summary info ===========================
FAILED testcases/test_ddt.py::test_csv_func[1-2-3] - assert (1 * 2) == 3
========================= 1 failed, 2 passed in 0.13s =========================
Report successfully generated to .\reportProcess finished with exit code 0

三.excel 文件讀取使用

首先創建一個excel文件,文件內容為:

然后在讀取Excel數據內容前,要針對不同版本使用不同的第三方庫

  • xls
    • office 2003版本
      • 安裝:xlrd第三庫
      • 必須指定版本
      • pip install xlrd==1.2.0
  • xlsx
    • office 2016版本
      • 安裝:openpyxl第三方庫
      • 默認安裝最新的版本庫即可
      • pip install openpyxl

安裝完后,讀取 數據:

import xlrd# # 讀取excel 文件數據獲取xls文件對象
# xls = xlrd.open_workbook(r'D:\python_project\API_Auto\API3\data\test.xlsx')
#
# # 獲取excel 中的sheet 表,0代表第一張 表的索引、
# sheet = xls.sheet_by_index(0)
#
# # 輸出數據列
# print(sheet.ncols)
#
# # 輸出數據行
# print(sheet.nrows)
#
# # 讀取具體某一行內容,0代表第一行數據索引
# print(sheet.row_values(1))
#def get_excel_data(path):list_excel =  []xls = xlrd.open_workbook(path)# 獲取excel 中的sheet 表,0代表第一張 表的索引、sheet = xls.sheet_by_index(0)for i in range(sheet.nrows):list_excel.append(sheet.row_values(i))# 刪除表頭數據list_excel.pop(0)# print(list_excel)return list_excel

使用讀取到的數據:

@pytest.mark.parametrize(("name", "age", "height", "money"), get_excel_data(r"D:\python_project\API_Auto\API3\data\test.xlsx")
)
def test_excel_func(name, age, height, money):print(f"name是{name},age是{age},height是{height},money是{money}")

輸出結果為 :

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... collected 3 itemstestcases/test_ddt.py::test_excel_func[張三-18.0-185.0-10000000.0] name是張三,age是18.0,height是185.0,money是10000000.0
PASSED
testcases/test_ddt.py::test_excel_func[李四-30.0-178.0-2000.0] name是李四,age是30.0,height是178.0,money是2000.0
PASSED
testcases/test_ddt.py::test_excel_func[王五-40.0-169.0-43323.0] name是王五,age是40.0,height是169.0,money是43323.0
PASSED============================== 3 passed in 0.09s ==============================
Report successfully generated to .\reportProcess finished with exit code 0

四.json 文件的讀取使用

首先創建一個json文件,內容為:

[[1,2,3],[4,2,6],[7,8,9]
]

然后讀取文件內容

def get_json_data(path):with open(path, encoding="utf-8") as file:content = file.read()# print(eval(content))# print(type(eval(content)))# eval() : 去掉最外層的引號return eval(content)

對讀取到的內容進行使用:


@pytest.mark.parametrize(("x", "y", "z"), get_json_data(r'D:\python_project\API_Auto\API3\data\json.json')
)
def test_json_func(x, y, z):assert x + y == z

輸出結果為:

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... collected 3 itemstestcases/test_ddt.py::test_json_func[1-2-3] PASSED
testcases/test_ddt.py::test_json_func[4-2-6] PASSED
testcases/test_ddt.py::test_json_func[7-8-9] FAILED================================== FAILURES ===================================
____________________________ test_json_func[7-8-9] ____________________________x = 7, y = 8, z = 9@pytest.mark.parametrize(("x", "y", "z"), get_json_data(r'D:\python_project\API_Auto\API3\data\json.json'))def test_json_func(x, y, z):
>       assert x + y == z
E       assert (7 + 8) == 9testcases\test_ddt.py:35: AssertionError
----------------------------- Captured log setup ------------------------------
WARNING  pytest_result_log:plugin.py:122 --------------Start: testcases/test_ddt.py::test_json_func[7-8-9]---------------
---------------------------- Captured log teardown ----------------------------
WARNING  pytest_result_log:plugin.py:128 ---------------End: testcases/test_ddt.py::test_json_func[7-8-9]----------------
=========================== short test summary info ===========================
FAILED testcases/test_ddt.py::test_json_func[7-8-9] - assert (7 + 8) == 9
========================= 1 failed, 2 passed in 0.14s =========================
Report successfully generated to .\reportProcess finished with exit code 0

五.yaml 文件讀取使用?

1.yaml數據讀寫

序列化:內存中數據,轉化為文件

反序列化:將文件轉化為內存數據 需要操作yaml文件,安裝第三方庫

? ? ? ? ? ? ? ? ??pip install pyyaml

2.序列化 ?將yaml 數據寫入文件中

"""
YAML 是一個可讀性 高,用來達標數據序列化的格式基本語法格式:1.區分大小寫2.使用縮進表示層級 關系3.縮進不能 使用 tab  建,只能使用空格4.縮進的空格數不重要,只要相同 層級的元素左對齊即可5.可以使用 注釋符號 #yaml  序列化 常用數據類型:1.對象(python中的 字段,鍵值對)2.數組(python 中的列表 )3.純量:單個的、不可再分值4.布爾值5.空值YAML 數據讀寫:序列化:將內存 中數據轉化為文件反序列化 :將文件轉化為內存數據需要安裝第三方庫:pip install pyyaml
"""data = {'數字': [1, 2, 3, 4, -1],'字符串': ["a", "@#", "c"],'空值': None,'布爾值': [True, False],'元組': (1, 2, 3)
}import yaml# 將 python 數據類型,轉換為yaml 格式
yaml_data = yaml.safe_dump(data,  # 要轉化的數據內容allow_unicode=True,  # 允許unicode 字符,中文原樣顯示sort_keys=False  # 不進行排序,原樣輸出
)# 序列化  將yaml 數據寫入文件中
f = open(r"D:\python_project\API_Auto\API3\data\yaml.yaml", "w", encoding="utf-8")
f.write(yaml_data)
f.close()

3.反序列化 讀取yaml 文件中的數據

# 反序列化   讀取yaml 文件中的數據
f = open(r"D:\python_project\API_Auto\API3\data\yaml.yaml", "r", encoding="utf-8")
s = f.read()
data_yaml = yaml.safe_load(s)
print(data_yaml)

4.寫入一個大列表里面嵌套小列表

# 寫入一個大列表里面嵌套小列表list1 = [['張三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]yaml_data = yaml.safe_dump(list1,  # 要轉化的數據內容allow_unicode=True,  # 允許unicode 字符,中文原樣顯示sort_keys=False  # 不進行排序,原樣輸出
)# 序列化  將yaml 數據寫入文件中
f = open(r"D:\python_project\API_Auto\API3\data\yaml1.yaml", "w", encoding="utf-8")
f.write(yaml_data)
f.close()

完整代碼為:

data = {'數字': [1, 2, 3, 4, -1],'字符串': ["a", "@#", "c"],'空值': None,'布爾值': [True, False],'元組': (1, 2, 3)
}import yamldef get_yaml_data():# 將 python 數據類型,轉換為yaml 格式yaml_data = yaml.safe_dump(data,  # 要轉化的數據內容allow_unicode=True,  # 允許unicode 字符,中文原樣顯示sort_keys=False  # 不進行排序,原樣輸出)# 序列化  將yaml 數據寫入文件中f = open(r"D:\python_project\API_Auto\API3\data\yaml.yaml", "w", encoding="utf-8")f.write(yaml_data)f.close()# 反序列化   讀取yaml 文件中的數據f = open(r"D:\python_project\API_Auto\API3\data\yaml.yaml", "r", encoding="utf-8")s = f.read()data_yaml = yaml.safe_load(s)print(data_yaml)# 寫入一個大列表里面嵌套小列表list1 = [['張三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]yaml_data = yaml.safe_dump(list1,  # 要轉化的數據內容allow_unicode=True,  # 允許unicode 字符,中文原樣顯示sort_keys=False  # 不進行排序,原樣輸出)# 序列化  將yaml 數據寫入文件中f = open(r"D:\python_project\API_Auto\API3\data\yaml1.yaml", "w", encoding="utf-8")f.write(yaml_data)f.close()# 反序列化   讀取yaml 文件中的數據f = open(r"D:\python_project\API_Auto\API3\data\yaml1.yaml", "r", encoding="utf-8")s = f.read()data_yaml1 = yaml.safe_load(s)print(data_yaml1)return data_yaml1

使用讀取到的數據:

@pytest.mark.parametrize(("x"), get_yaml_data()
)
def test_yaml_func(x):for i in x:print(i)

輸出為 :

D:\python_project\API_Auto\API3\venv\Scripts\python.exe D:\python_project\API_Auto\API3\main.py 
============================= test session starts =============================
platform win32 -- Python 3.10.6, pytest-8.3.5, pluggy-1.5.0 -- D:\python_project\API_Auto\API3\venv\Scripts\python.exe
cachedir: .pytest_cache
rootdir: D:\python_project\API_Auto\API3
configfile: pytest.ini
plugins: allure-pytest-2.13.5, result-log-1.2.2
collecting ... {'數字': [1, 2, 3, 4, -1], '字符串': ['a', '@#', 'c'], '空值': None, '布爾值': [True, False], '元組': [1, 2, 3]}
[['張三', 18.0, 185.0, 10000000.0], ['李四', 30.0, 178.0, 2000.0], ['王五', 40.0, 169.0, 43323.0]]
collected 3 itemstestcases/test_ddt.py::test_yaml_func[x0] 張三
18.0
185.0
10000000.0
PASSED
testcases/test_ddt.py::test_yaml_func[x1] 李四
30.0
178.0
2000.0
PASSED
testcases/test_ddt.py::test_yaml_func[x2] 王五
40.0
169.0
43323.0
PASSED============================== 3 passed in 0.10s ==============================
Report successfully generated to .\reportProcess finished with exit code 0

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/904119.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/904119.shtml
英文地址,請注明出處:http://en.pswp.cn/news/904119.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

游戲引擎學習第257天:處理一些 Win32 相關的問題

設定今天的工作計劃 今天我們本來是打算繼續開發性能分析器(Profiler),但在此之前,我們認為有一些問題應該先清理一下。雖然這類事情不是我們最關心的核心內容,但我們覺得現在是時候處理一下了,特別是為了…

實驗三 觸發器及基本時序電路

1.觸發器的分類?各自的特點是什么? 1 、 D 觸發器 特點:只有一個數據輸入端 D ,在時鐘脈沖的觸發沿,輸出 Q 的狀態跟隨輸入端 D 的 狀態變化,即 ,功能直觀,利于理解和感受…

硬件加速模式Chrome(Edge)閃屏

Chrome開啟“硬件加速模式”后,打開瀏覽器會閃屏或看視頻會閃屏,如果電腦只有集顯,直接將這個硬件加速關了吧,沒啥必要開著 解決方法 讓瀏覽器使用獨立顯卡 在Windows左下角搜索 圖形設置 ,將瀏覽器添加進去&#…

前端工程化利器:Node.js 文件匹配庫 fast-glob 完全指南——比傳統方案快 350% 的「文件搜索神器」

為什么需要 fast-glob? 在前端工程化場景中,文件匹配是高頻操作:自動化構建、資源打包、靜態資源管理等都依賴高效的路徑匹配。傳統的 node-glob 雖然功能齊全,但性能瓶頸明顯。fast-glob 應運而生——它以 極簡 API 和 超高性能…

React class 的組件庫與函數組件適配集成

如果你有一個 基于 React class 的組件庫,現在需要在 React hooks 函數組件中使用,你可以通過以下幾種方式實現適配和集成: 數據生命周期確保 class 組件使用 React.forwardRef 導出(或手動綁定 ref) ? 1. 直接使用 c…

Sway初體驗

Sway(縮寫自 SirCmpwn’s Wayland compositor[1])是一款專為 Wayland 設計的合成器,旨在與 i3 完全兼容。根據官網所述: Sway 是 Wayland 的合成器,也是 x11 的 i3 窗口管理器的替代品。它可以根據您現有的 i3 配置工作…

dubbo 參數校驗-ValidationFilter

org.apache.dubbo.rpc.Filter 核心功能 攔截RPC調用流程 Filter是Dubbo框架中實現攔截邏輯的核心接口,作用于服務消費者和提供者的作業鏈路,支持在方法調用前后插入自定義邏輯。如參數校驗、異常處理、日志記錄等。擴展性機制 Dubbo通過SPI擴展機制動態…

Lesson 16 A polite request

Lesson 16 A polite request 詞匯 park n. 公園,停車場,莊園 v. 停車,泊車 例句:讓我來停車。    Let me park. 相關:spot n. 車位 區別:garden n. 花園 [小,私家的] 例句:我們…

解決 Builroot 系統編譯 perl 編譯報錯問題

本文提供一種修復 Builroot 系統編譯 perl 編譯報錯途徑 2025-05-04T22:45:08 rm -f pod/perl5261delta.pod 2025-05-04T22:45:08 /usr/bin/ln -s perldelta.pod pod/perl5261delta.pod 2025-05-04T22:45:08 /usr/bin/gcc -c -DPERL_CORE -fwrapv -fpcc-struct-return -pipe -f…

Spring MVC 中解決中文亂碼問題

在 Spring MVC 中解決中文亂碼問題,需要從 請求參數編碼 和 響應內容編碼 兩方面入手。以下是完整的解決方案: 一、解決請求參數中文亂碼 1. POST 請求編碼(表單提交) 配置 CharacterEncodingFilter 在 web.xml 中添加 Spring 提…

MYSQL數據庫突然消失

之前在下載mysql時發現沒有my.ini。考慮到后面的項目可能需要,看著教程自己創建了一次,當時就發生了所有數據庫消失的問題,近幾天這種事件又發生了。我在服務里看到我有mysql和mysql57兩個服務,啟動一個的時候另一個就無法啟動&am…

【Spring】idea + maven 從零創建Spring IoC容器示例

【Spring】idea maven 從零創建Spring IoC容器示例 1. 環境準備2. 創建maven項目3. 添加依賴4. 創建Java類與接口4.1 定義接口UserService4.2 實現接口UserServiceImpl 5. 配置Spring IoC容器6. 編寫主類調用IoC容器擴展:使用注解方式實現IoC1. 修改beans.xml2.使用…

面試回答之STAR結構

面試回答之STAR結構 1. STAR結構的起源 STAR是行為面試法(Behavioral Interview)的核心框架,由以下四個單詞首字母組成: ? Situation(情境) ? Task(任務) ? Action&#xff…

Kubernetes部署運行應用

①使用 Deployment 運行一個無狀態應用 ②運行一個單實例有狀態應用 ③運行一個有狀態的應用程序 ④使用 Persistent Volumes 部署 WordPress 和 MySQL

二叉搜索樹的最近祖先(遞歸遍歷)

235. 二叉搜索樹的最近公共祖先 - 力扣(LeetCode) class Solution { private:TreeNode*traversal(TreeNode*cur,TreeNode*p,TreeNode*q){if(curNULL){return NULL;}if(cur->val>p->val&&cur->val>q->val){TreeNode*lefttrave…

網絡:TCP三次握手、四次揮手

目錄 深刻理解三次握手 深刻理解四次揮手 深刻理解三次握手 三次握手時,如果最后一個ACK包,服務器沒有收到,此時: 客戶端:認為已經建立鏈接 服務器:認為沒有建立鏈接,還在超時等待。 而此…

MySQL 實戰 45 講 筆記 ----來源《極客時間》

01 | 基礎架構:一條SQL查詢語句是如何執行的? 1. MySQL 可以分為 Server層 和 存儲引擎層 兩部分。Server 層包括連接器、查詢緩存、分析器、優化器、執行器等。存儲引擎層支持 InnoDB、MyISAM等. (1) 連接器:管理連接,權限認證…

nextjs+supabase vercel部署失敗

1.不能含有<any> 改成unknown或者增加類(如圖) 2.檢查vecel是否配置環境變量&#xff08;即supabase的url和anon-key&#xff09;

數據庫Mysql_聯合查詢

或許自己的不完美才是最完美的地方&#xff0c;那些讓自己感到不安的瑕疵&#xff0c;最終都會變成自己的特色。 ----------陳長生. 1.介紹 1.1.為什么要進行聯合查詢 在數據設計的時候&#xff0c;由于范式的需求&#xff0c;會被分為多個表&#xff0c;但是當我們要查詢數據…

(37)VTK C++開發示例 ---紋理地球

文章目錄 1. 概述2. CMake鏈接VTK3. main.cpp文件4. 演示效果 更多精彩內容&#x1f449;內容導航 &#x1f448;&#x1f449;VTK開發 &#x1f448; 1. 概述 將圖片紋理貼到球體上&#xff0c;實現3D地球的效果。 該代碼使用了 VTK (Visualization Toolkit) 庫來創建一個紋理…