介面自動化測試 pytest+allure+requests
pytest:
需要安裝pytest和pytest-html(生成html測試報告)
pip install pytest 和 pip install pytest-html
命名規則
Pytest單元測試中的類名和方法名必須是以test開頭,執行中只能找到test開頭的類和方法,比unittest更加嚴謹
unittest:Setup>> setupclass teardown teardownclass
Pytest的setup, setup_class和teardown, teardown_class函式(和unittest執行效果一樣)
運行於測試方法的始末,即:執行一次測試函式會執行一次setup和teardown
運行於測試方法的始末,但是不管有多少測試函式都只執行一次setup_class和 teardown_class
Pytest生成自帶的html測試報告:
直接執行pytest.main()
【自動查詢當前目錄下,以test_開頭的檔案或者以_test結尾的py檔案】(課堂練習_test)
pytest.main("模組.py")
【執行指定模組下,執行所有test開頭的類和測試用例】
pip install pytest-html() :python自帶的外掛
pytest.main(["--html=./report.html","test3.py"])
Pytest呼叫語句:
pytest.main([‘--html=./report.html’,‘模組.py::類::test_a_001'])
執行指定模組指定類指定用例,冒號分割,並生成測試報告
pytest.main(['-x','--html=./report.html','t12est000.py'])
-x出現一條測試用例失敗就退出測試
-v: 豐富資訊模式, 輸出更詳細的用例執行資訊
-s:顯示print內容
-q: 簡化結果資訊,不會顯示每個用例的檔名
Pytest的執行方式:
. 點號,表示用例通過
F 表示失敗 Failure
E 表示用例中存在異常 Error
allure:
Allure是一款輕量級並且非常靈活的開源測試報告框架。 它支援絕大多數測試框架, 例如TestNG、Pytest、JUint等。它簡單易用,易於整合。
首先要安裝allure
pip install allure-pytest
allure-pytest是Pytest的一個外掛,通過它我們可以生成Allure所需要的用於生成測試報告的資料
Allure常用的幾個特性:
@allure.feature # 用於描述被測試產品需求
@allure.story # 用於描述feature的使用者場景,即測試需求
with allure.step(): # 用於描述測試步驟,將會輸出到報告中
allure.attach # 用於向測試報告中輸入一些附加的資訊,通常是一些測試資料,截圖等
allure.feature:
allure.feature # 用於描述被測試產品需求
allure.story:
@allure.story # 用於描述feature的使用者場景,即測試需求
Pytest和allure結合:
Pytest和allure結合生成html格式的測試報告
生成測試報告json
pytest.main([ '--alluredir', 'report/result', 'test001.py']) ## 將測試報告轉為html格式 --html=../report.htmlsplit = 'allure ' + 'generate ' + './report/result ' + '-o ' + './report/html ' + '--clean'os.system(split)#system函式可以將字串轉化成命令在伺服器上執行
Pytest和allure效果展示:
requests:
requests是一個很實用的PythonHTTP客戶端庫,編寫爬蟲和測試伺服器響應資料時經常會用到,Requests是Python語言的第三方的庫,專門用於傳送HTTP請求
GET請求
r = requests.get('http://www.baidu.com')
傳參
payload={'key1':'value1','key2':'value2', 'key3':None}r=requests.get('http://www.baidu.com ',params=payload)
post請求
類似python中的表單提交
payload={'key1':'value1','key2':'value2'}
r=requests.post("http://httpbin.org/post",data=payload)
傳遞檔案(瞭解)
url='http://httpbin.org/post'files={'file':open('report.xls','rb')}
r=requests.post(url,files=files)
Requests響應:
r.status_code 響應狀態碼
r.heards 響應頭
r.cookies 響應cookies
r.text 響應文字
r. encoding 當前編碼
r. content 以位元組形式(二進位制)返回
最常用的是根據響應狀態碼判斷介面是否連通,經常用於做介面中斷言判斷
通過聚合資料請求:
傳送無引數的get請求:
傳送有引數的get請求:
Request擴充:
1:新增等待時間
requests.get(url,timeout=1) #超過等待時間則報錯
2:新增請求頭資訊
requests.get(url,headers=headers) #設定請求頭
3:新增檔案
requests.post(url,files=files) #新增檔案
request+pytest+allure:
讀取檔案中的資料
requests拿到資料請求介面返回狀態碼
通過斷言驗證返回狀態碼和200對比
生成allure的測試報告
模組總覽dataDemo(存放資料)>> readDemo(讀取資料)useRequests(傳送請求)>>testDemo(生成報告):
儲存資料:
讀取資料(readDemo):
將讀取的資料存放在列表中
request請求介面返回狀態碼:
pytest斷言設定並結合allure生成測試報告:
測試報告: