zoukankan      html  css  js  c++  java
  • 接口测试-requests实例

    requests实例-带参数的

    1.使用moco搭建一个接口

    创建一个文件夹moco2
    放入文件:moco-runner-1.0.0-standalone.jar , configure.json以及一个res.py文件

    2.configure.json

    [
      {
        "description": "模拟获取某个功能的具体信息接口,get请求和响应,返回json格式数据,无参数",
        "request": {
          "method": "get",
          "uri": "/book_list"
        },
        "response": {
          "json": {
            "error_code": 0,
            "reason": "successed",
            "books": "软件测试",
            "checkstatus": "on"
          },
          "status": 200
        }
      },
      {
        "description": "模拟获取某个功能的具体信息接口,get请求和响应,返回json格式数据,有参数",
        "request": {
          "method": "get",
          "uri": "/book_info",
          "queries": {
            "bookname": "软件测试",
            "checkstatus": "on"
          }
        },
        "response": {
          "json": {
            "error_code": 0,
            "reason": "successed",
            "name": "软件测试",
            "price": "666"
          },
          "status": 200
        }
      },
      {
        "description": "模拟接口,post_form请求和响应,入参是form形式,返回是json数据",
        "request": {
          "headers": {
            "content-type": "application/x-www-form-urlencoded"
          },
          "method": "post",
          "uri": "/login01",
          "forms": {
            "username": "zhangshan",
            "password": "123456"
          }
        },
        "response": {
          "json": {
            "error_code": 0,
            "reason": "successed",
            "username": "zhangshan",
            "checkstatus": "on"
          },
          "status": 200
        }
      },
      {
        "description": "模拟接口,post_json请求和响应,入参是json形式,返回是json数据",
        "request": {
          "method": "post",
          "uri": "/login02",
          "json": {
            "username": "zhangshan",
            "password": "123456"
          }
        },
        "response": {
          "headers": {
            "Content-Type": "application/json;charset=utf-8"
          },
          "json": {
            "error_code": 0,
            "reason": "successed",
            "username": "zhangshan",
            "checkstatus": "on"
          },
          "status": 200
        }
      }
    ]
    
    浏览器访问网址
    http://127.0.0.1:8888/book_list
    http://127.0.0.1:8888/book_info?bookname=软件测试&checkstatus=on
    


    3.代码实例

    1.get请求

    import json
    import requests
    # get
    url = 'http://127.0.0.1:8888'
    path = '/book_list'
    full_url = url + path
    print('GET 请求完整的url', full_url)
    headers_dict = {}
    print('GET 请求完整的请求头', headers_dict)
    res = requests.get(full_url, headers=headers_dict, )
    print('GET 响应状态码', res.status_code)
    print('GET 响应头', res.headers)
    print('GET 响应结果', res.text)
    print('GET 响应时间', res.elapsed.total_seconds(), '秒')
    
    json_res = res.json()
    print('GET 响应结果', json_res)
    
    # get_queries
    url = 'http://127.0.0.1:8888'
    path = '/book_info'
    full_url = url + path
    print('GET 请求完整的url', full_url)
    # 'checkstatus'='on' 是get与get_queries的关联依赖参数
    data = json.loads(res.text) # 把json转成字典类型
    checkstatus = data['checkstatus'] # 字典取值
    params_dict = {'bookname': '软件测试', 'checkstatus': checkstatus}
    print('GET 请求完整的参数', params_dict)
    headers_dict = {}
    print('GET 请求完整的请求头', headers_dict)
    res = requests.get(full_url, params=params_dict, headers=headers_dict, )
    print('GET 响应状态码', res.status_code)
    print('GET 响应头', res.headers)
    print('GET 响应结果', res.text)
    print('GET 响应时间', res.elapsed.total_seconds(), '秒')
    
    json_res = res.json()
    print('GET 响应结果', json_res)
    

    2.post请求

    import json
    import requests
    # post_forms
    url = 'http://127.0.0.1:8888'
    path = '/login01'
    full_url = url + path
    print('POST 请求的完整url', full_url)
    
    data = {"username": "zhangshan", "password": "123456"}  # 传入json格式
    print('POST 请求参数', data)
    headers_dict = {'Content_Type': 'application/x-www-form-urlencoded'} # forms格式
    res2 = requests.post(full_url, data=data, headers=headers_dict)
    print('POST 响应状态码', res2.status_code)
    print('POST 响应头', res2.headers)
    print('POST 响应结果', res2.text)
    print('POST 响应时间', res2.elapsed.total_seconds(), '秒')
    json_res2 = res2.json()
    print('POST 响应结果', json_res2)
    
    # post_json
    url = 'http://127.0.0.1:8888'
    path = '/login02'
    full_url = url + path
    print('POST 请求的完整url', full_url)
    
    data = {"username": "zhangshan", "password": "123456"}  # 传入json格式
    data = json.dumps(data) # python类型转化为json字符串
    print('POST 请求参数', data)
    headers_dict = {'Content_Type': 'application/json'} # json格式
    res3 = requests.post(full_url, data=data, headers=headers_dict)
    print('POST 响应状态码', res3.status_code)
    print('POST 响应头', res3.headers)
    print('POST 响应结果', res3.text)
    print('POST 响应时间', res3.elapsed.total_seconds(), '秒')
    json_res3 = res3.json()
    print('POST 响应结果', json_res3)
    

    4.封装成函数

    1.get请求

    import requests
    
    
    def get(full_url, headers_dict):
        # try 抛出异常
        try:
            res = requests.get(full_url, headers=headers_dict, )
            print('GET 响应状态码', res.status_code)
            print('GET 响应头', res.headers)
            print('GET 响应结果', res.text)
            print('GET 响应时间', res.elapsed.total_seconds(), '秒')
            json_res = res.json()
            print('GET 响应结果', json_res)
            return json_res
        except Exception as e:
            print('get错误')
    
    
    url = 'http://localhost:8888'
    path = '/book_list'
    full_url = url + path
    headers_dict = {}
    res = get(full_url, headers_dict)
    # 通过业务状态码判断是否成功
    if res['error_code'] == 0:
        print('成功')
    else:
        print('失败')
    def get_queries(full_url, params_dict, headers_dict):
        # try 抛出异常
        try:
            res1 = requests.get(full_url, params=params_dict, headers=headers_dict, )
            print('GET 响应状态码', res1.status_code)
            print('GET 响应头', res1.headers)
            print('GET 响应结果', res1.text)
            print('GET 响应时间', res1.elapsed.total_seconds(), '秒')
            json_res1 = res1.json()
            print('GET 响应结果', json_res1)
            return json_res1
        except Exception as e:
            print('get错误')
    
    
    url = 'http://localhost:8888'
    path = '/book_info'
    full_url = url + path
    params_dict = {'bookname': '软件测试', 'checkstatus': 'on'}
    headers_dict = {}
    res1 = get_queries(full_url, params_dict, headers_dict)
    # 通过业务状态码判断是否成功
    if res1['error_code'] == 0:
        print('成功')
    else:
        print('失败')
    

    2.post请求

    import requests
    import json
    def post_forms(full_url, data, headers_dict):
        try:
            res2 = requests.post(full_url, data=data, headers=headers_dict)
            print('POST 响应状态码', res2.status_code)
            print('POST 响应头', res2.headers)
            print('POST 响应结果', res2.text)
            print('POST 响应时间', res2.elapsed.total_seconds(), '秒')
            json_res2 = res2.json()
            print('POST 响应结果', json_res2)
            return json_res2
        except Exception as e:
            print('post_forms 错误')
    
    
    url = 'http://localhost:8888'
    path = '/login01'
    full_url = url + path
    data = {"username": "zhangshan", "password": "123456"}
    headers_dict = {'content_type': 'application/x-www-form-urlencoded'} # forms格式
    res2 = post_forms(full_url, data, headers_dict)
    if res2['checkstatus'] == 'on':
        print('成功')
    else:
        print('失败')
    
    
    def post_json(full_url, data, headers_dict):
        try:
            res3 = requests.post(full_url, data=data, headers=headers_dict)
            print('POST 响应状态码', res3.status_code)
            print('POST 响应头', res3.headers)
            print('POST 响应结果', res3.text)
            print('POST 响应时间', res3.elapsed.total_seconds(), '秒')
            json_res3 = res3.json()
            print('POST 响应结果', json_res3)
            return json_res3
        except Exception as e:
            print('post_json错误')
    
    
    url = 'http://localhost:8888'
    path = '/login02'
    full_url = url + path
    data = {"username": "zhangshan", "password": "123456"}
    data = json.dumps(data)
    headers_dict = {'content_type': 'application/json'} # json 格式
    res3 = post_json(full_url, data, headers_dict)
    if res3['checkstatus'] == 'on':
        print('成功')
    else:
        print('失败')
    
    

    5.封装成类

    类中有四个方法

    import json
    import requests
    
    
    class Httprequests():
        def get(self, full_url, headers_dict):
            # try 抛出异常
            try:
                res = requests.get(full_url,  headers=headers_dict, )
                print('GET 响应状态码', res.status_code)
                print('GET 响应头', res.headers)
                print('GET 响应结果', res.text)
                print('GET 响应时间', res.elapsed.total_seconds(), '秒')
                json_res = res.json()
                print('GET 响应结果', json_res)
                return json_res
            except Exception as e:
                print('get错误')
        def get_queries(self, full_url, params_dict, headers_dict):
            # try 抛出异常
            try:
                res1 = requests.get(full_url, params=params_dict, headers=headers_dict, )
                print('GET 响应状态码', res1.status_code)
                print('GET 响应头', res1.headers)
                print('GET 响应结果', res1.text)
                print('GET 响应时间', res1.elapsed.total_seconds(), '秒')
                json_res1 = res1.json()
                print('GET 响应结果', json_res1)
                return json_res1
            except Exception as e:
                print('get错误')
    
        def post_forms(self, full_url, data, headers_dict):
            try:
                res2 = requests.post(full_url, data=data, headers=headers_dict)
                print('POST 响应状态码', res2.status_code)
                print('POST 响应头', res2.headers)
                print('POST 响应结果', res2.text)
                print('POST 响应时间', res2.elapsed.total_seconds(), '秒')
                json_res2 = res2.json()
                print('POST 响应结果', json_res2)
                return json_res2
            except Exception as e:
                print('post_forms 错误')
    
        def post_json(self, full_url, data, headers_dict):
            try:
                res3 = requests.post(full_url, data=data, headers=headers_dict)
                print('POST 响应状态码', res3.status_code)
                print('POST 响应头', res3.headers)
                print('POST 响应结果', res3.text)
                print('POST 响应时间', res3.elapsed.total_seconds(), '秒')
                json_res3 = res3.json()
                print('POST 响应结果', json_res3)
                return json_res3
            except Exception as e:
                print('post_json错误')
    obj = Httprequests()  # 实例化对象 类名()
    url = 'http://localhost:8888'
    path = '/book_list'
    full_url = url + path
    headers_dict = {}
    res = obj.get(full_url, headers_dict)  # 通过实例化的对象.
    # 通过业务状态码判断是否成功
    if res['error_code'] == 0:
        print('成功')
    else:
        print('失败')
    
    
    obj1 = Httprequests()  # 实例化对象 类名()
    url = 'http://localhost:8888'
    path = '/book_info'
    full_url = url + path
    params_dict = {'bookname': '软件测试', 'checkstatus': 'on'}
    headers_dict = {}
    res1 = obj1.get_queries(full_url, params_dict, headers_dict)  # 通过实例化的对象.
    # 通过业务状态码判断是否成功
    if res1['error_code'] == 0:
        print('成功')
    else:
        print('失败')
    
    obj2 = Httprequests()  # 实例化对象 类名()
    url = 'http://localhost:8888'
    path = '/login01'
    full_url = url + path
    data = {"username": "zhangshan", "password": "123456"}
    headers_dict = {'content_type': 'application/x-www-form-urlencoded'}  # forms格式
    res2 = obj2.post_forms(full_url, data, headers_dict)
    if res2['checkstatus'] == 'on':
        print('成功')
    else:
        print('失败')
    
    obj3 = Httprequests()  # 实例化对象 类名()
    url = 'http://localhost:8888'
    path = '/login02'
    full_url = url + path
    data = {"username": "zhangshan", "password": "123456"}
    data = json.dumps(data)
    headers_dict = {'content_type': 'application/json'}  # json 格式
    res3 = obj3.post_json(full_url, data, headers_dict)
    if res3['checkstatus'] == 'on':
        print('成功')
    else:
        print('失败')
    
    
    

  • 相关阅读:
    Nginx配置虚拟主机
    TCP有限状态机
    一次完整的HTTP请求过程
    129 爬虫 requests request 爬图片
    算法: 二分查找 冒泡 插入 选择排序
    121 monogdb安装, 增删改查, mongodb中的update修改器 pymomgo
    119 websocket 群聊 单聊 websocket的握手 加密解密
    118 falsk智能机器人 语音合成 语音识别
    117 flask中的上下文实现原理 偏函数 线程 setattr
    python基础中的内置方法:
  • 原文地址:https://www.cnblogs.com/zhangshan33/p/11990835.html
Copyright © 2011-2022 走看看