pytest接口自動化測試框架搭建得全過程

目錄

一. 背景

Pytest目前已經(jīng)成為Python系自動化測試必學必備得一個框架,網(wǎng)上也有很多得內(nèi)容講述相關(guān)得知識。最近自己也抽時間梳理了一份pytest接口自動化測試框架,因此準備寫內(nèi)容記錄一下,做到盡量簡單通俗易懂,當然前提是基本得python基礎(chǔ)已經(jīng)掌握了。如果能夠?qū)π聦W習這個框架得同學起到一些幫助,那就更好了~

二. 基礎(chǔ)環(huán)境

語言:python 3.8

編譯器:pycharm

基礎(chǔ):具備python編程基礎(chǔ)

框架:pytest+requests+allure

三. 項目結(jié)構(gòu)

項目結(jié)構(gòu)圖如下:

每一層具體得含義如下圖:

測試報告如下圖:

四、框架解析

4.1 接口數(shù)據(jù)文件處理

框架中使用草料二維碼得get和post接口用于demo測試,比如:

get接口:https://cli.im/qrcode/getDefaultComponentMsg

返回值:{“code”:1,“msg”:"",“data”:{xxxxx}}

數(shù)據(jù)文件這里選擇使用Json格式,文件內(nèi)容格式如下,test_http_get_data.json:

{  "dataItem": [    {      "id": "testget-1",      "name": "草料二維碼get接口1",      "headers":{        "Accept-Encoding":"gzip, deflate, br"      },      "url":"/qrcode/getDefaultComponentMsg",      "method":"get",      "expectdata": {        "code": "1"      }    },    {      "id": "testget-2",      "name": "草料二維碼get接口2",      "headers":{},      "url":"/qrcode/getDefaultComponentMsg",      "method":"get",      "expectdata": {        "code": "1"      }    }  ]}

表示dataitem下有兩條case,每條case里面聲明了id, name, header, url, method, expectdata。如果是post請求得話,case中會多一個parameters表示入?yún)ⅲ缦拢?/p>

{    "id":"testpost-1",    "name":"草料二維碼post接口1",    "url":"/Apis/QrCode/saveStatic",    "headers":{        "Content-Type":"application/x-www-form-urlencoded",        "Accept-Encoding":"gzip, deflate, br"    },    "parameters":{        "info":11111,        "content":11111,        "level":"H",        "size":500,        "fgcolor":"#000000",        "bggcolor":"#FFFFFF",        "transparent":"false",        "type":"text",        "codeimg":1    },    "expectdata":{        "status":"1",        "qrtype":"static"    }}

為了方便一套用于不同得環(huán)境運行,不用換了環(huán)境后挨個兒去改數(shù)據(jù)文件,比如

測試環(huán)境URL為:https://testcli.im/qrcode/getDefaultComponentMsg

生產(chǎn)環(huán)境URL為:https://cli.im/qrcode/getDefaultComponentMsg

因此數(shù)據(jù)文件中url只填寫后半段,不填域名。然后config》global_config.py下設(shè)置全局變量來定義域名:

# 配置HTTP接口得域名,方便一套用于多套環(huán)境運行時,只需要改這里得全局配置就OKCAOLIAO_HTTP_POST_HOST = "https://cli.im"CAOLIAO_HTTP_GET_HOST = "https://nc.cli.im"

utils文件夾下,創(chuàng)建工具類文件:read_jsonfile_utils.py, 用于讀取json文件內(nèi)容:

import jsonimport osclass ReadJsonFileUtils:    def __init__(self, file_name):        self.file_name = file_name        self.data = self.get_data()    def get_data(self):        fp = open(self.file_name,encoding='utf-8')        data = json.load(fp)        fp.close()        return data    def get_value(self, id):        return self.data[id]    @staticmethod    def get_data_path(folder, fileName):        BASE_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))        data_file_path = os.path.join(BASE_PATH, folder, fileName)        return data_file_pathif __name__ == '__main__':    opers = ReadJsonFileUtils("..\resources\test_http_post_data.json")    #讀取文件中得dataItem,是一個list列表,list列表中包含多個字典    dataitem=opers.get_value('dataItem')    print(dataitem)

運行結(jié)果如下:

4.2 封裝測試工具類

utils文件夾下,除了上面提到得讀取Json文件工具類:read_jsonfile_utils.py,還有封裝request 請求得工具類:http_utils.py

從Excel文件中讀取數(shù)據(jù)得工具類:get_excel_data_utils.py(雖然本次框架中暫時未采用存放接口數(shù)據(jù)到Excel中,但也寫了個工具類,需要得時候可以用)

http_utils.py內(nèi)容:

import requestsimport jsonclass HttpUtils:    @staticmethod    def http_post(headers, url, parameters):        print("接口請求url:" + url)        print("接口請求headers:" + json.dumps(headers))        print("接口請求parameters:" + json.dumps(parameters))        res = requests.post(url, data=parameters, headers=headers)        print("接口返回結(jié)果:"+res.text)        if res.status_code != 200:            raise Exception(u"請求異常")        result = json.loads(res.text)        return result    @staticmethod    def http_get(headers, url):        req_headers = json.dumps(headers)        print("接口請求url:" + url)        print("接口請求headers:" + req_headers)        res = requests.get(url, headers=headers)        print("接口返回結(jié)果:" + res.text)        if res.status_code != 200:            raise Exception(u"請求異常")        result = json.loads(res.text)        return result

get_excel_data_utils.py內(nèi)容:

import xlrdfrom xlrd import xldate_as_tupleimport datetimeclass ExcelData(object):    '''    xlrd中單元格得數(shù)據(jù)類型    數(shù)字一律按浮點型輸出,日期輸出成一串小數(shù),布爾型輸出0或1,所以我們必須在程序中做判斷處理轉(zhuǎn)換    成我們想要得數(shù)據(jù)類型    0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error    '''    def __init__(self, data_path, sheetname="Sheet1"):        #定義一個屬性接收文件路徑        self.data_path = data_path        # 定義一個屬性接收工作表名稱        self.sheetname = sheetname        # 使用xlrd模塊打開excel表讀取數(shù)據(jù)        self.data = xlrd.open_workbook(self.data_path)        # 根據(jù)工作表得名稱獲取工作表中得內(nèi)容        self.table = self.data.sheet_by_name(self.sheetname)        # 根據(jù)工作表得索引獲取工作表得內(nèi)容        # self.table = self.data.sheet_by_name(0)        # 獲取第一行所有內(nèi)容,如果括號中1就是第二行,這點跟列表索引類似        self.keys = self.table.row_values(0)        # 獲取工作表得有效行數(shù)        self.rowNum = self.table.nrows        # 獲取工作表得有效列數(shù)        self.colNum = self.table.ncols    # 定義一個讀取excel表得方法    def readExcel(self):        # 定義一個空列表        datas = []        for i in range(1, self.rowNum):            # 定義一個空字典            sheet_data = {}            for j in range(self.colNum):                # 獲取單元格數(shù)據(jù)類型                c_type = self.table.cell(i,j).ctype                # 獲取單元格數(shù)據(jù)                c_cell = self.table.cell_value(i, j)                if c_type == 2 and c_cell % 1 == 0:  # 如果是整形                    c_cell = int(c_cell)                elif c_type == 3:                    # 轉(zhuǎn)成datetime對象                    date = datetime.datetime(*xldate_as_tuple(c_cell, 0))                    c_cell = date.strftime('%Y/%d/%m %H:%M:%S')                elif c_type == 4:                    c_cell = True if c_cell == 1 else False                sheet_data[self.keys[j]] = c_cell                # 循環(huán)每一個有效得單元格,將字段與值對應存儲到字典中                # 字典得key就是excel表中每列第一行得字段                # sheet_data[self.keys[j]] = self.table.row_values(i)[j]            # 再將字典追加到列表中            datas.append(sheet_data)        # 返回從excel中獲取到得數(shù)據(jù):以列表存字典得形式返回        return datasif __name__ == "__main__":    data_path = "..\resources\test_http_data.xls"    sheetname = "Sheet1"    get_data = ExcelData(data_path, sheetname)    datas = get_data.readExcel()    print(datas)

4.3 測試用例代碼編寫

testcases文件夾下編寫測試用例:

test_caoliao_http_get_interface.py內(nèi)容:

import loggingimport allureimport pytestfrom utils.http_utils import HttpUtilsfrom utils.read_jsonfile_utils import ReadJsonFileUtilsfrom config.global_config import CAOLIAO_HTTP_GET_HOST@pytest.mark.httptest@allure.feature("草料二維碼get請求測試")class TestHttpInterface:    # 獲取文件相對路徑    data_file_path = ReadJsonFileUtils.get_data_path("resources", "test_http_get_data.json")    # 讀取測試數(shù)據(jù)文件    param_data = ReadJsonFileUtils(data_file_path)    data_item = param_data.get_value('dataItem')  # 是一個list列表,list列表中包含多個字典    """    @pytest.mark.parametrize是數(shù)據(jù)驅(qū)動;    data_item列表中有幾個字典,就運行幾次case    ids是用于自定義用例得名稱    """        @pytest.mark.parametrize("args", data_item, ids=['測試草料二維碼get接口1', '測試草料二維碼get接口2'])    def test_caoliao_get_demo(self, args, login_test):        # 打印用例ID和名稱到報告中顯示        print("用例ID:{}".format(args['id']))        print("用例名稱:{}".format(args['name']))        print("測試conftest傳值:{}".format(login_test))        logging.info("測試開始啦~~~~~~~")        res = HttpUtils.http_get(args['headers'], CAOLIAO_HTTP_GET_HOST+args['url'])        # assert斷言,判斷接口是否返回期望得結(jié)果數(shù)據(jù)        assert str(res.get('code')) == str(args['expectdata']['code']), "接口返回status值不等于預期"

test_caoliao_http_post_interface.py內(nèi)容:

import pytestimport loggingimport allurefrom utils.http_utils import HttpUtilsfrom utils.read_jsonfile_utils import ReadJsonFileUtilsfrom config.global_config import CAOLIAO_HTTP_POST_HOST# pytest.ini文件中要添加markers = httptest,不然會有warning,說這個Mark有問題@pytest.mark.httptest@allure.feature("草料二維碼post請求測試")class TestHttpInterface:    # 獲取文件相對路徑    data_file_path = ReadJsonFileUtils.get_data_path("resources", "test_http_post_data.json")    # 讀取測試數(shù)據(jù)文件    param_data = ReadJsonFileUtils(data_file_path)    data_item = param_data.get_value('dataItem') #是一個list列表,list列表中包含多個字典    """    @pytest.mark.parametrize是數(shù)據(jù)驅(qū)動;    data_item列表中有幾個字典,就運行幾次case    ids是用于自定義用例得名稱        """    @pytest.mark.parametrize("args", data_item, ids=['測試草料二維碼post接口1','測試草料二維碼post接口2'])    def test_caoliao_post_demo(self, args):        # 打印用例ID和名稱到報告中顯示        print("用例ID:{}".format(args['id']))        print("用例名稱:{}".format(args['name']))        logging.info("測試開始啦~~~~~~~")        res = HttpUtils.http_post(args['headers'], CAOLIAO_HTTP_POST_HOST+args['url'], args['parameters'])        # assert斷言,判斷接口是否返回期望得結(jié)果數(shù)據(jù)        assert str(res.get('status')) == str(args['expectdata']['status']), "接口返回status值不等于預期"        assert str(res.get('data').get('qrtype')) == str(args['expectdata']['qrtype']), "接口返回qrtype值不等于預期"

企業(yè)中得系統(tǒng)接口,通常都有認證,需要先登錄獲取token,后續(xù)接口調(diào)用時都需要認證token。因此框架需要能處理在運行用例前置和后置做一些動作,所以這里用到了conftest.py文件,內(nèi)容如下:

import loggingimport tracebackimport pytestimport requests"""如果用例執(zhí)行前需要先登錄獲取token值,就要用到conftest.py文件了作用:conftest.py 配置里可以實現(xiàn)數(shù)據(jù)共享,不需要import導入 conftest.py,pytest用例會自動查找scope參數(shù)為session,那么所有得測試文件執(zhí)行前執(zhí)行一次scope參數(shù)為module,那么每一個測試文件執(zhí)行前都會執(zhí)行一次conftest文件中得fixturescope參數(shù)為class,那么每一個測試文件中得測試類執(zhí)行前都會執(zhí)行一次conftest文件中得fixturescope參數(shù)為function,那么所有文件得測試用例執(zhí)行前都會執(zhí)行一次conftest文件中得fixture"""# 獲取到登錄請求返回得ticket值,@pytest.fixture裝飾后,testcase文件中直接使用函數(shù)名"login_ticket"即可得到ticket值@pytest.fixture(scope="session")def login_ticket():    header = {        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'    }    params = {        "loginId": "username",        "pwd": "password",    }    url = 'http://testxxxxx.xx.com/doLogin'    logging.info('開始調(diào)用登錄接口:{}'.format(url))    res = requests.post(url, data=params, headers=header, verify=False)  # verify:忽略https得認證    try:        ticket = res.headers['Set-Cookie']    except Exception as ex:        logging.error('登錄失?。〗涌诜祷兀簕}'.format(res.text))        traceback.print_tb(ex)    logging.info('登錄成功,ticket值為:{}'.format(ticket))    return ticket#測試一下conftest.py文件和fixture得作用@pytest.fixture(scope="session")def login_test():    print("運行用例前先登錄!")    # 使用yield關(guān)鍵字實現(xiàn)后置操作,如果上面得前置操作要返回值,在yield后面加上要返回得值    # 也就是yield既可以實現(xiàn)后置,又可以起到return返回值得作用    yield "runBeforeTestCase"    print("運行用例后退出登錄!")

由于用例中用到了@pytest.mark.httptest給用例打標,因此需要創(chuàng)建pytest.ini文件,并在里面添加markers = httptest,不然會有warning,說這個Mark有問題。并且用例中用到得日志打印logging模板也需要在pytest.ini文件中增加日志配置。pytest.ini文件內(nèi)容如下:

[pytest]markers =  httptest: run http interface test  dubbotest: run dubbo interface testlog_cli = truelog_cli_level = INFOlog_cli_format = %(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)slog_cli_date_format=%Y-%m-%d %H:%M:%Slog_format = %(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)4s: %(message)slog_date_format=%Y-%m-%d %H:%M:%S

4.4 測試用例運行生成報告 ???????

運行方式:
Terminal窗口,進入到testcases目錄下,執(zhí)行命令:


運行某一條case:pytest test_caoliao_http_post_interface.py
運行所有case: pytest
運行指定標簽得case:pytest -m httptest


運行并打印過程中得詳細信息:pytest -s test_caoliao_http_post_interface.py
運行并生成pytest-html報告:pytest test_caoliao_http_post_interface.py --html=../testoutput/report.html
運行并生成allure測試報告:
1. 先清除掉testoutput/result文件夾下得所有文件
2. 運行case,生成allure文件:pytest --alluredir ../testoutput/result
3. 根據(jù)文件生成allure報告:allure generate ../testoutput/result/ -o ../testoutput/report/ --clean
4. 如果不是在pycharm中打開,而是直接到report目錄下打開index.html文件打開得報告無法展示數(shù)據(jù),需要雙擊generateAllureReport.bat生成allure報告;

pytest-html報告:

generateAllureReport.bat文件位置:

文件內(nèi)容:

allure open report/

Allure報告:

框架中用到得一些細節(jié)知識點和問題,如:

conftest.py和@pytest.fixture()結(jié)合使用
pytest中使用logging打印日志
python中獲取文件相對路徑得方式
python虛擬環(huán)境
pytest框架下Allure得使用

我會在后續(xù)寫內(nèi)容再介紹。另外框架同樣適用于dubbo接口得自動化測試,只需要添加python調(diào)用dubbo得工具類即可,后續(xù)也會寫內(nèi)容專門介紹。

總結(jié)

到此這篇關(guān)于pytest接口自動化測試框架搭建得內(nèi)容就介紹到這了,更多相關(guān)pytest接口自動化測試內(nèi)容請搜索之家以前得內(nèi)容或繼續(xù)瀏覽下面得相關(guān)內(nèi)容希望大家以后多多支持之家!

聲明:所有內(nèi)容來自互聯(lián)網(wǎng)搜索結(jié)果,不保證100%準確性,僅供參考。如若本站內(nèi)容侵犯了原著者的合法權(quán)益,可聯(lián)系我們進行處理。
發(fā)表評論
更多 網(wǎng)友評論1 條評論)
暫無評論

返回頂部

主站蜘蛛池模板: 日韩精品无码免费一区二区三区 | 中文字幕无码人妻aaa片| 一区二区三区视频| 美女被cao免费看在线看网站| 欧美高清性色生活片免费观看| 日本一区二区三区四区五区| 国自产拍亚洲免费视频| 国产九九久久99精品影院| 亚洲熟妇久久精品| 91青青国产在线观看免费| 美女扒开尿口给男人桶视频免费| 无码精品国产一区二区三区免费 | 狠狠噜天天噜日日噜视频麻豆| 少妇无码av无码专区线| 国产在线视频一区二区三区| 亚洲精品无码久久久久久| 中文字幕一区二区日产乱码| 羞羞歪歪汗汗漫画| 日韩精品免费一线在线观看| 国产婷婷综合丁香亚洲欧洲| 久久人人爽人人爽人人片av不| 91福利国产在线观看网站| 欧美精品stoya在线| 天天操天天干天天透| 国产一区二区三区不卡在线观看| 中文字幕网伦射乱中文| 鸣人向纲手开炮| 欧美日韩视频精品一区二区| 国产精品不卡在线| 亚洲欧美黄色片| 香港三级欧美国产精品| 日韩精品一区二区三区色欲av| 国产亚洲精品精品国产亚洲综合| 亚洲av高清一区二区三区| 18分钟处破好疼高清视频| 波霸在线精品视频免费观看| 女朋友韩国电影免费完整版| 亚洲码欧美码一区二区三区| 老汉色av影院| 日本一道本在线| 免费无码黄网站在线观看|