• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

pytest三requests

武飞扬头像
陈皮话没
帮助1

一、requests简介

requests用来发送http请求以及接受http响应的python第三方库,主要用于接口自动化测试。

  • 安装:pip install requests

二、requests库常用的方法

  • requests.get()         url是接口地址,params用于传参
  • requests.post()       url是接口地址,data用于传参,json也用于传参
    • data和json传参的区别只要是通过请求头Content-Type来区分。
    • 请求:请求方式、请求路径、请求头、请求正文。
    • Content-Type
      • multipart/form-data 文件上传
      • application/x-www-form-urlencoded  表单提交
      • application/json 
      • application/xml
      • application/javascript
      • application/binary
      • text/html
    • data和json传参以及Content-Type的关系如下:
      • data传参:
        • 报文是dict类型,那么默认是Content-Type:applocation/x-www-form-urlencoded
        • 报文是str类型,那么默认是Content-Type:text/plain
      • json传参:报文可以是dict类型,默认是Context-Type:application/json
      • 所以:
        • data:可以传纯键值对的dict(非嵌套的),也可以传str格式。
        • json:可以传任何形式的dict(包括嵌套的dict)
      • json与dict转换:
        • json.loads()  把json字符串转化成dict格式
        • json.dumps() 把dict格式转化成json字符串
  • requests.put()
  • requests.delete()
  • requests.request() 可以发送所有类型的请求:get、post、put、delete

不管是get还是post还是put和delete,底层都是调用的requests.request()方法。

而requests.request()调的是session.request()方法。主要参数:

method,                                 请求方式

url,                                         请求路径

params=None,                      get方式传参

data=None,                           post方式传参

json=None,                           post方式传参

headers=None,                     请求头

cookies=None,                      请求cookie

files=None,                            文件上传

三、requests模块返回的response对象详解

  • response.json()       获得返回的字典格式的数据
  • response.text          获得返回的字符串格式的数据
  • response.content     获得返回的bytes格式的数据
  • response.status_code 状态码
  • response.reason          状态信息
  • response.cookies         cookies信息
  • response.headers         响应头
  • response.request.xxx    返回请求的数据,如:请求头、请求参数..

四、请求必须带请求头的接口,以及需要cookie鉴权和session鉴权的接口

90%以上的基于web的接口都有cookie鉴权。

两种解决方式:

1.使用cookie关联

2.使用session关联

        requests.session().request()       使用同一个会话发起请求。

  1.  
    import json
  2.  
    import re
  3.  
     
  4.  
    import requests
  5.  
     
  6.  
     
  7.  
    class TestRequest:
  8.  
    # 全局变量,类变量
  9.  
    access_token = ""
  10.  
    csrf_token = ""
  11.  
    php_cookie = ""
  12.  
    sess = requests.session()
  13.  
     
  14.  
    # get请求:获取统一鉴权码token接口
  15.  
    def test_get_token(self):
  16.  
    url = "https://api.weixin.qq.com/cgi-bin/token"
  17.  
    data = {
  18.  
    "grant_type": "client_credential",
  19.  
    "appid": "wx7ff6c1d5ba45d17e",
  20.  
    "secret": "4b5fe134130b7c292d6a6c22f38b56d0"
  21.  
    }
  22.  
    res = requests.request(method="get", url=url, params=data)
  23.  
    print(res.json())
  24.  
    TestRequest.access_token = res.json()['access_token']
  25.  
     
  26.  
    # post请求:编辑标签接口
  27.  
    def test_edit_flag(self):
  28.  
    url = "https://api.weixin.qq.com/cgi-bin/tags/update?access_token=" TestRequest.access_token
  29.  
    data = {"tag": {"id": 101, "name": "广东人"}}
  30.  
    str_date = json.dumps(data)
  31.  
    res = requests.request(method="post", url=url, data=str_date)
  32.  
    print(res.json())
  33.  
     
  34.  
    # 文件上传
  35.  
    def test_file_upload(self):
  36.  
    url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" TestRequest.access_token
  37.  
    data = {
  38.  
    "media": open(r"E:\developer\idea\workspace\autotest_pytest\image.png", "rb")
  39.  
    }
  40.  
    res = requests.request(method="post", url=url, files=data)
  41.  
    print(res.json())
  42.  
     
  43.  
    # 访问首页接口
  44.  
    def test_start(self):
  45.  
    url = "http://47.107.116.139/phpwind/"
  46.  
    # res = requests.request(method="get", url=url)
  47.  
    # 通过sess请求,就不用cookies
  48.  
    res = TestRequest.sess.request(method="get", url=url)
  49.  
    # print(res.text)
  50.  
    # 正则提取提取鉴权码
  51.  
    # re.search("正则表达式",res.text)
  52.  
    obj = re.search('name="csrf_token" value="(.*?)"', res.text)
  53.  
    # 取匹配到的第1个值
  54.  
    print(obj.group(1))
  55.  
    TestRequest.csrf_token = obj.group(1)
  56.  
     
  57.  
    # # 提取cookies
  58.  
    # TestRequest.php_cookie = res.cookies
  59.  
     
  60.  
    def test_login(self):
  61.  
    url = "http://47.107.116.139/phpwind/index.php?m=u&c=login&a=dorun"
  62.  
    data = {
  63.  
    "username": "xxx",
  64.  
    "password": "xxx",
  65.  
    "csrf_token": TestRequest.csrf_token, # 鉴权码,从首页获取
  66.  
    "backurl": "http://47.107.116.139/phpwind/",
  67.  
    "invite": ""
  68.  
    }
  69.  
    headers = {
  70.  
    "Accept": "application/json,text/javascript,/; q=0.01",
  71.  
    "X-Requested-With": "XMLHttpRequest"
  72.  
    }
  73.  
    # res = requests.request(method="post", url=url, data=data, headers=headers, cookies=TestRequest.php_cookie)
  74.  
    # 使用session请求
  75.  
    res = TestRequest.sess.request(method="post", url=url, data=data, headers=headers)
  76.  
    print(res.json())
  77.  
     
  78.  
     
  79.  
    if __name__ == '__main__':
  80.  
    TestRequest.test_get_token()
  81.  
    TestRequest.test_edit_flag()
  82.  
    TestRequest.test_file_upload()
  83.  
    TestRequest.test_start()
  84.  
    TestRequest.test_login()
学新通

四、接口自动化测试框架关于接口关联的封装

策略:去掉全局变量,用YAML文件代替保存。

yaml_util.py 操作yaml文件的工具模块。

  1.  
    # 对yaml操作的工具
  2.  
     
  3.  
    # 读取
  4.  
    import os
  5.  
     
  6.  
    import yaml
  7.  
     
  8.  
     
  9.  
    def read_yaml(key):
  10.  
    with open(os.getcwd() "/extract.yaml", mode="r", encoding="utf-8") as f:
  11.  
    # FullLoader 全局加载
  12.  
    value = yaml.load(stream=f, Loader=yaml.FullLoader)
  13.  
    return value[key]
  14.  
     
  15.  
     
  16.  
    # 写入
  17.  
    def write_yaml(data):
  18.  
    # 以追加的模式打开,编码格式为utf-8
  19.  
    with open(os.getcwd() "/extract.yaml", mode="a", encoding="utf-8") as f:
  20.  
    yaml.dump(data, stream=f, allow_unicode=True)
  21.  
     
  22.  
     
  23.  
    # 清空
  24.  
    def clean_yaml():
  25.  
    # 以追加的模式打开,编码格式为utf-8
  26.  
    with open(os.getcwd() "/extract.yaml", mode="w", encoding="utf-8") as f:
  27.  
    f.truncate()
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggbhkh
系列文章
更多 icon
同类精品
更多 icon
继续加载