首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >pytest+requests+allure实现接口自动化测试系列(2)-requests封装

pytest+requests+allure实现接口自动化测试系列(2)-requests封装

作者头像
搁浅同学
发布2022-07-21 14:59:30
5420
发布2022-07-21 14:59:30
举报

接着上一篇继续分享

接着分享如何封装requests的,让它更符合我们的业务。因为如果不封装的话,每次都单独调用调用requests的方法,肯定会造成很多代码冗余。

我们先通过pycharm查看源码的方式,可以看到reuests.post/requests.get,最终调用的方法是requests.request

def request(method, url, **kwargs):
    """Constructs and sends a :class:`Request <Request>`.
    :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param data: (optional) Dictionary, list of tuples, bytes, or file-like
        object to send in the body of the :class:`Request`.
    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
        to add for the file.
    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
    :param timeout: (optional) How many seconds to wait for the server to send data
        before giving up, as a float, or a :ref:`(connect timeout, read
        timeout) <timeouts>` tuple.
    :type timeout: float or tuple
    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
    :type allow_redirects: bool
    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
    :param verify: (optional) Either a boolean, in which case it controls whether we verify
            the server's TLS certificate, or a string, in which case it must be a path
            to a CA bundle to use. Defaults to ``True``.
    :param stream: (optional) if ``False``, the response content will be immediately downloaded.
    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response

    Usage::

      >>> import requests
      >>> req = requests.request('GET', 'https://httpbin.org/get')
      >>> req
      <Response [200]>
    """

可以通过以上方式,可以看到request的各个参数的说明,然后根据方法的不同进行简单封装,因此我们可以新建一个文件request_handler,如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests


def request_handler(method: str, url: str, data: dict):
    """
    :param method: 方法字符串,'GET','POST'
    :param url: 请求地址
    :param data: 要传递的参数
    :return: 返回响应的数据
    """
    try:
        method = method.upper()
        if method == "GET" or method == "DELETE":
            return requests.request(method=method, url=url, params=data, verify=False)
        elif method == "POST" or method == "PUT":
            return requests.request(method=method, url=url, json=data, verify=False)
        else:
            print(f"暂不支持{method}")
    except Exception as e:
        raise e

上述目前只考虑了Content-Type是application/json的情况,可能实际上会有更复杂的情况,到时候需要根据实际情况进行修改

那下面我们根据上面封装的request重新改造下我们的测试用例,今天换个接口

#!/usr/bin/python
# -*- coding: utf-8 -*-

import requests
from request_handler import request_handler


class Testrequests:

    def test_requests(self):
        url = "https://api2.mubu.com/v3/api/user/phone_login"
        method = 'post'
        data = {"phone": "*********", "password": "123456abc", "callbackType": 0}
        r = request_handler(method, url, data)
        print(r.json())
        assert r.status_code == 200
        
   # 为了方便,我把我个人的手机号屏蔽了,大家可以到幕布注册账号,然后通过抓包工具,可得到该登录接口
   

再次运行接口可看到测试用例是正常的,说明我们封装的requests是正确的

今天分享就到这里,明天分享从yaml文件读取数据到并且参数化到测试方法。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-12-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 暴走的软件测试Tester 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档