pytest+yaml+allure接口自動化測試框架04.處理request


前言

​ 環境搭建配置、封裝日志緩存、讀取yaml測試文件,這些工作我們上幾個章節已經都做完了,讀取文件之后,我們已經成功拿到了測試yaml文件中的測試數據了,那我們接下來就通過這些數據去執行測試,主要就是對這些數據做HTTP請求的請求和響應。

​ 談到HTTP請求,我們首先就會想到requests庫,這個第三方庫,以極其優雅的封裝方式和簡易的寫法,在python界有着重要的地位,在這個接口自動化測試框架中,我們也會使用這個庫進行二次封裝。讓其融入到我們的測試框架中來。

​ 對於這個庫我就不做過多的介紹了,之前有一篇文章專門介紹,感興趣可以點擊:python requests由淺入深 - 隨風揮手 - 博客園 (cnblogs.com)

執行測試的代碼

上一章節已經講了怎么讀取測試用例數據,根據pytest官網的non-python test內容,我們還需要編寫一個YamlTest類來執行測試。

繼續打開conftest.py文件,在里面加上如下內容:

# +++
from common.request import HttpRequest
from common.exceptions import RequestException

# +++

class YamlTest(pytest.Item):
    def __init__(self, name, parent, spec):
        super(YamlTest, self).__init__(name, parent)
        self.spec = spec
        self.request = HttpRequest(exception=(RequestException, Exception))

    def runtest(self):
        """Some custom test execution (dumb example follows)."""
        self.request.send_request(**self.spec)

    def repr_failure(self, excinfo):
        """Called when self.runtest() raises an exception."""
        logger.critical(excinfo.value)
        logger.critical(excinfo.traceback[-6:-1])            

    def reportinfo(self):
        return self.fspath, 0, f"usecase: {self.name}"

通過繼承pytest.Item類我們可以使用父類的運行測試的方法來執行測試。

__init__方法

在這個里面我們接收來自yamlfile類中collect方法的yield生成器傳給我們的測試數據。

runtest

繼承父類的runtest方法我們可以在這個里面執行我們的測試,把接受到的參數傳入我們二次封裝的HttpRequest類,就可以對我們在yaml文件中添加的接口進行測試了。

repr_failure

如果在運行中發生了用例失敗的現象我們可以在這個方法中攔截並打印出相應的報錯信息,方便我們排查問題。

reportinfo

通過reportinfo方法重寫我們傳入的name信息,就是我們在yaml文件中的測試用例名稱信息。

這個就是我們通過對YamlTest的改造,組成了一個測試過程。這個類的核心是對requests的二次封裝類。

二次封裝requests

我們打開common/request.py,我們鍵入以下內容。

# -*- coding: utf-8 -*-
__author__ = 'wxhou'
__email__ = '1084502012@qq.com'
"""
requests二次封裝
"""
import urllib3
from requests import Session, Response
from common.cache import cache
from utils.logger import logger

urllib3.disable_warnings()


class HttpRequest(Session):
    """requests方法二次封裝"""

    def __init__(self, *args: t.Union[t.Set, t.List], **kwargs: t.Dict[t.Text, t.Any]):
        super(HttpRequest, self).__init__()
        self.exception = kwargs.get("exception", Exception)

    def send_request(self, **kwargs: t.Dict[t.Text, t.Any]) -> Response:
        """發送請求
        """
        try:
            logger.info("request data: {}".format(kwargs))
            method = kwargs.get('method', 'GET').upper()
            url = cache.get('baseurl') + kwargs.get('route')
            logger.info("Request Url: {}".format(url))
            logger.info("Request Method: {}".format(method))
            logger.info("Request Data: {}".format(kwargs))
            request_data = HttpRequest.mergedict(kwargs.get('RequestData'),
                                                 headers=cache.get('headers'),
                                                 timeout=cache.get('timeout'))
            response = self.dispatch(method, url, **request_data)
            logger.info("Request Result: {}{}".format(response, response.text))
            return response
        except self.exception as e:
            logger.exception(format(e))
            raise e

    def dispatch(self, method, *args, **kwargs):
        """請求分發"""
        handler = getattr(self, method.lower())
        return handler(*args, **kwargs)

    @staticmethod
    def mergedict(args, **kwargs):
        """合並字典"""
        for k, v in args.items():
            if k in kwargs:
                kwargs[k] = {**args[k], **kwargs.pop(k)}
        args.update(kwargs)
        return args

我們通過繼承requests庫的Session類,添加我們的定制化的一些方法。

send_request方法

我們把YamlTest類中的測試用例數據傳入到我們的這個方法中來,然后打印日志記錄,並將結果進行返回。

dispatch

在這個方法中我們根據傳入的用例請求方法,去反射我們Session類中的相應的請求方法,從而實現get,post等HTTP請求。

mergedict

編寫了一個合並字典的方法,用來合並我們定義的請求體或者請求參數,和我們自定義的一些測試配置,比如headers,timeout等。

對於requests的封裝暫時就介紹到這里。

好幾天沒更新了是因為最近有點懶。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM