欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Pytest+request+Allure實現(xiàn)接口自動化框架

 更新時間:2021年07月21日 14:25:36   作者:程序媛圓圓  
接口自動化是指模擬程序接口層面的自動化,由于接口不易變更,維護(hù)成本更小,所以深受各大公司的喜愛,本文主要介紹了Pytest+request+Allure實現(xiàn)接口自動化框架,感興趣的可以了解一下

前言:

接口自動化是指模擬程序接口層面的自動化,由于接口不易變更,維護(hù)成本更小,所以深受各大公司的喜愛。
接口自動化包含2個部分,功能性的接口自動化測試和并發(fā)接口自動化測試。
本次文章著重介紹第一種,功能性的接口自動化框架。

一、簡單介紹

環(huán)境:Mac、Python 3,Pytest,Allure,Request

pytest==3.6.0
pytest-allure-adaptor==1.7.10(棄用)
pytest-rerunfailures==5.0
configparser==3.5.0
PyYAML==3.12
requests==2.18.4
simplejson==3.16.0
----------------------------------------
2020-4-30更新
pytest==5.3.1
allure-pytest==2.8.6
allure-python-commons==2.8.6
⚠️注:pytest-allure-adaptor已棄用,改為allure-pytest;
安裝allure-pytest時,需將pytest-allure-adaptor卸載

流程:讀取Yaml測試數(shù)據(jù)-生成測試用例-執(zhí)行測試用例-生成Allure報告
模塊類的設(shè)計說明:

Request.py 封裝request方法,可以支持多協(xié)議擴展(get\post\put)
Config.py讀取配置文件,包括:不同環(huán)境的配置,email相關(guān)配置
Log.py 封裝記錄log方法,分為:debug、info、warning、error、critical
Email.py 封裝smtplib方法,運行結(jié)果發(fā)送郵件通知
Assert.py 封裝assert方法
run.py 核心代碼。定義并執(zhí)行用例集,生成報告

Yaml測試數(shù)據(jù)格式如下:

---
Basic:
  dec: "基礎(chǔ)設(shè)置"
  parameters:
    -
      url: /settings/basic.json
      data: slug=da1677475c27
      header: {
                 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko)\
                  Chrome/67.0.3396.99 Safari/537.36",
                 "Content-Type": "keep-alive"
              }

二、代碼結(jié)構(gòu)與框架流程

1、代碼結(jié)構(gòu)見下圖:

代碼結(jié)構(gòu).jpg

2、框架流程見下圖:

框架流程.jpg

三、詳細(xì)功能和使用說明

1、定義配置文件config.ini

該文件中區(qū)分測試環(huán)境[private_debug]和正式環(huán)境[online_release]分別定義相關(guān)配置項,[mail]部分為郵件相關(guān)配置項

# http接口測試框架配置信息
 
[private_debug]
# debug測試服務(wù)
tester = your name
environment = debug
versionCode = your version
host = www.jianshu.com
loginHost = /Login
loginInfo = email=wang@user.com&password=123456
 
[online_release]
# release正式服務(wù)
tester = your name
environment = release
versionCode = v1.0
host = www.jianshu.com
loginHost = /Login
loginInfo = email=wang@user.com&password=123456
 
[mail]
#發(fā)送郵件信息
smtpserver = smtp.163.com
sender = test1@163.com
receiver = wang@user.com
username = wang@user.com
password = 123456

2、讀取yaml測試數(shù)據(jù)后封裝

yaml測試數(shù)據(jù)例子見第一節(jié),一條接口可定義多條case數(shù)據(jù),get_parameter為已封裝好的讀取yaml數(shù)據(jù)方法,循環(huán)讀取后將多條case數(shù)據(jù)存在list中。

class Basic:
    params = get_parameter('Basic')
    url = []
    data = []
    header = []
    for i in range(0, len(params)):
        url.append(params[i]['url'])
        data.append(params[i]['data'])
        header.append(params[i]['header'])

3、編寫用例

class TestBasic:
    @allure.feature('Home')
    @allure.severity('blocker')
    @allure.story('Basic')
    def test_basic_01(self, action):
        """
            用例描述:未登陸狀態(tài)下查看基礎(chǔ)設(shè)置
        """
        conf = Config()
        data = Basic()
        test = Assert.Assertions()
        request = Request.Request(action)
 
        host = conf.host_debug
        req_url = 'http://' + host
        urls = data.url
        params = data.data
        headers = data.header
 
        api_url = req_url + urls[0]
        response = request.get_request(api_url, params[0], headers[0])
 
        assert test.assert_code(response['code'], 401)
        assert test.assert_body(response['body'], 'error', u'繼續(xù)操作前請注冊或者登錄.')
        assert test.assert_time(response['time_consuming'], 400)
        Consts.RESULT_LIST.append('True')

4、運行整個框架run.py

if __name__ == '__main__':
    # 定義測試集
    args = ['-s', '-q', '--alluredir', xml_report_path]
    self_args = sys.argv[1:]
    pytest.main(args)
    cmd = 'allure generate %s -o %s' % (xml_report_path, html_report_path)
 
    try:
        shell.invoke(cmd)
    except:
        log.error('執(zhí)行用例失敗,請檢查環(huán)境配置')
        raise
 
    try:
        mail = Email.SendMail()
        mail.sendMail()
    except:
        log.error('發(fā)送郵件失敗,請檢查郵件配置')
        raise

5、err.log實例

[ERROR 2018-08-24 09:55:37]Response body != expected_msg, expected_msg is {"error":"繼續(xù)操作前請注冊或者登錄9."}, body is {"error":"繼續(xù)操作前請注冊或者登錄."}
[ERROR 2018-08-24 10:00:11]Response time > expected_time, expected_time is 400, time is 482.745
[ERROR 2018-08-25 21:49:41]statusCode error, expected_code is 208, statusCode is 200

6、Assert部分代碼

    def assert_body(self, body, body_msg, expected_msg):
        """
        驗證response body中任意屬性的值
        :param body:
        :param body_msg:
        :param expected_msg:
        :return:
        """
        try:
            msg = body[body_msg]
            assert msg == expected_msg
            return True
 
        except:
            self.log.error("Response body msg != expected_msg, expected_msg is %s, body_msg is %s" % (expected_msg, body_msg))
            Consts.RESULT_LIST.append('fail')
 
            raise
 
    def assert_in_text(self, body, expected_msg):
        """
        驗證response body中是否包含預(yù)期字符串
        :param body:
        :param expected_msg:
        :return:
        """
        try:
            text = json.dumps(body, ensure_ascii=False)
            # print(text)
            assert expected_msg in text
            return True
 
        except:
            self.log.error("Response body Does not contain expected_msg, expected_msg is %s" % expected_msg)
            Consts.RESULT_LIST.append('fail')
 
            raise

7、Request部分代碼

    def post_request(self, url, data, header):
        """
        Post請求
        :param url:
        :param data:
        :param header:
        :return:
        """
        if not url.startswith('http://'):
            url = '%s%s' % ('http://', url)
            print(url)
        try:
            if data is None:
                response = self.get_session.post(url=url, headers=header)
            else:
                response = self.get_session.post(url=url, params=data, headers=header)
 
        except requests.RequestException as e:
            print('%s%s' % ('RequestException url: ', url))
            print(e)
            return ()
 
        except Exception as e:
            print('%s%s' % ('Exception url: ', url))
            print(e)
            return ()
 
        # time_consuming為響應(yīng)時間,單位為毫秒
        time_consuming = response.elapsed.microseconds/1000
        # time_total為響應(yīng)時間,單位為秒
        time_total = response.elapsed.total_seconds()
 
        Common.Consts.STRESS_LIST.append(time_consuming)
 
        response_dicts = dict()
        response_dicts['code'] = response.status_code
        try:
            response_dicts['body'] = response.json()
        except Exception as e:
            print(e)
            response_dicts['body'] = ''
 
        response_dicts['text'] = response.text
        response_dicts['time_consuming'] = time_consuming
        response_dicts['time_total'] = time_total
 
        return response_dicts

四、Allure報告及Email

1、Allure報告總覽,見下圖:

Allure報告.jpg

2、Email見下圖:

Email.jpg

五、后續(xù)優(yōu)化

1、集成Jenkins,使用Jenkins插件生成Allure報告
2、多線程并發(fā)接口自動化測試
3、接口加密,參數(shù)加密

到此這篇關(guān)于Pytest+request+Allure實現(xiàn)接口自動化框架 的文章就介紹到這了,更多相關(guān)Pytest接口自動化框架 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python在命令行中使用?pdb?實現(xiàn)斷點調(diào)試功能

    python在命令行中使用?pdb?實現(xiàn)斷點調(diào)試功能

    在命令行中設(shè)置斷點通常需要使用調(diào)試工具來實現(xiàn),下面以 Python 為例介紹如何在命令行中使用pdb實現(xiàn)斷點調(diào)試,這篇文章主要介紹了python在命令行中使用pdb實現(xiàn)斷點調(diào)試,需要的朋友可以參考下
    2023-06-06
  • python 3.6 +pyMysql 操作mysql數(shù)據(jù)庫(實例講解)

    python 3.6 +pyMysql 操作mysql數(shù)據(jù)庫(實例講解)

    下面小編就為大家分享一篇python 3.6 +pyMysql 操作mysql數(shù)據(jù)庫的實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-12-12
  • python logging日志模塊以及多進(jìn)程日志詳解

    python logging日志模塊以及多進(jìn)程日志詳解

    本篇文章主要介紹了python logging日志模塊以及多進(jìn)程日志詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-04-04
  • Python ollama的搭建與使用流程分析

    Python ollama的搭建與使用流程分析

    這篇文章主要介紹了Python ollama的搭建與使用流程分析,詳細(xì)介紹了ollama的安裝方式,本文結(jié)合實例給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-04-04
  • Python+OCR實現(xiàn)文檔解析的示例代碼

    Python+OCR實現(xiàn)文檔解析的示例代碼

    本文是一個簡單教程,主要介紹了如何使用OCR進(jìn)行文檔解析以及使用Layoutpars軟件包進(jìn)行了整個檢測和提取過程,感興趣的可以了解一下
    2022-09-09
  • PyCharm License Activation激活碼失效問題的解決方法(圖文詳解)

    PyCharm License Activation激活碼失效問題的解決方法(圖文詳解)

    這篇文章主要介紹了PyCharm License Activation激活碼失效問題的解決方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-03-03
  • pycharm引入其他目錄的包報錯,import報錯的解決

    pycharm引入其他目錄的包報錯,import報錯的解決

    這篇文章主要介紹了pycharm引入其他目錄的包報錯,import報錯的解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-08-08
  • Python實現(xiàn)簡單猜數(shù)字游戲

    Python實現(xiàn)簡單猜數(shù)字游戲

    這篇文章主要為大家詳細(xì)介紹了Python實現(xiàn)猜數(shù)字游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-02-02
  • django inspectdb 操作已有數(shù)據(jù)庫數(shù)據(jù)的使用步驟

    django inspectdb 操作已有數(shù)據(jù)庫數(shù)據(jù)的使用步驟

    這篇文章主要介紹了django inspectdb 操作已有數(shù)據(jù)庫數(shù)據(jù)的使用步驟,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-02-02
  • python實現(xiàn)三階魔方還原的示例代碼

    python實現(xiàn)三階魔方還原的示例代碼

    這篇文章主要介紹了python實現(xiàn)三階魔方還原的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04

最新評論