一、Pytest優點認知:
1.可以結合所有的自動化測試工具
2.跳過失敗用例以及失敗重跑
3.結合allure生產美觀報告
4.和Jenkins持續集成
5.很多強大的插件
pytest-html:生產html測試報告
pytest-xdist:多線程運行
pytest-ordering:改變用例執行順序
pytest-rerunfailures:失敗用例重爬
allure-pytest:美觀測試報告
一般項目中,會使用requerments.text文檔保存插件名稱,進行批量一次性安裝
pip install -r requerments.txt
二、運行方式:
1.主函數運行方式:main方法運行
2.命令運行方式
pytest -vs
-v:更加詳細信息
-s:調試信息
-n=處理:多線程運行
--reruns=數字:失敗用例重跑
--reruns=數字:失敗用例重跑
--html=./report.html:生成html報告
用例分組運行
1.進行用例分組:
2.用例進行注解:
#@pytest.mark.分組名稱 如下:
@pytest.mark.smoke
[pytest]
##運行命令,例如: -vs -m "smoke"分組執行名稱都是固定的
addopts = -vs
#測試用例文件目錄
testpaths = ./testcases
python_files = test_*.py
python_classes = Test*
python_functions = test_*
##分組
markers =
smoke:maoyan
case:gongneng
三、前置后置,夾具
1.簡單區分:直接調用方法,但是接口過多時,比較麻煩
def setup(self):
print("每個用例執行之前,都執行一遍")
def teardown(self):
print("每個用例執行之后,都執行一遍")
2.實現部分前置:如只想之一個用例進行前置,如登錄時需要連接數據庫。
需要使用裝置器:來實現
參數介紹:
@pytest.fixture(scope="作用域",params="數據驅動",autouse="是否自動執行",ids="自定義參數",name="重命名")
作用域:可以函數、類、模塊、包、session
使用方法:
1.需要前置的功能函數上進行標注裝置器
2.別的方法函數之間調用裝置器
如下:一個文件里面進行部分前置喚醒
import time
import pytest
import requests
#實現裝置器標注前置,進行標注,yieid進行喚醒返回
@pytest.fixture(scope="function")
def conn_getbase():
print("連接數據庫成功")
yield
print("關閉數據庫成功")
class TestSendRequsets:
#過多接口時,比較麻煩冗余
# def setup(self):
# print("每個用例執行之前")
#
# def teardown(self):
# print("每個用例執行之后")
def test_getImgCode(self):
# 接口url
t = time.time()
timess = str(int(round(t * 1000)))
times = str(int(t))
url = "http://124.71.230.185:9002/jeecg-boot/sys/randomImage/" + "" + timess
# 參數
data = {
"_t": times,
}
# # get請求
rep = requests.request('get', url, params=data)
print(rep.text)
# 標注為smoke分組用例
@pytest.mark.smoke
def test_Login(self,conn_getbase):
# post請求
url = "http://124.71.230.185:9002/jeecg-boot/sys/login"
# 參數
data = {
"captcha": "Gkak!@#2021",
"checkKey": 1637811815838,
"password": "123456",
"remember_me": 1,
"username": "admin"
}
rep = requests.request('post', url, json=data)
statues = rep.json()["success"]
message = rep.json()["message"]
if statues:
print("")
else:
# raise Exception(message)
print(message)
if __name__ == '__main__':
pytest.main();
3.封裝靈活調用
一般情況下:@pytest.fixture()會和conftest.py文件一塊使用
conftest.py名稱是固定的,功能如下:
1.用處是多個py文件之間共享前置配置。
2.里面的方法在調用時,不需要導入,可以之間調用
3.可以都多個conftest.py文件,也可以有不同的層級
conftest.py文件詳情請看下一章
實現:
1.目錄下之間創建conftest.py文件
2.把上面的這段代碼之間粘貼到conftest.py文件中
# 前置函數
import pytest
@pytest.fixture(scope="function")
def conn_getbase():
print("連接數據庫成功")
yield
print("關閉數據庫成功")