API自动化测试1

 1

 2

检查post请求

3

 4查看requests库

http://cn.python-requests.org/zh_CN/latest/

5.以列出课程为列子构建请求参数

构建请求消息 定义url参数

 

查看响应内容

查看响应消息头:

查看响应消息体:

json格式的消息转换为python中的数据对象

判断id是否存在

post请求:

url参数

请求参数 格式为表单格式(键值对)

复制创建课程值

如果是自定义格式 可以这样写

 如果是json格式

自己转码json格式

例子:

Request使用方法快速介绍

Request是第三方库,需要手动安装:

pip install requests

需要导入requests模块

import requests

构建各种http请求

http.get请求

requests.get('https://api.github.com/events')

http.post请求

requests.post('http://httpbin.org/post', data = {'key':'value'})

http.put请求

requests.put('http://httpbin.org/put', data = {'key':'value'})

http.delete请求

requests.delete('http://httpbin.org/delete')

构建URL参数

payload = {'key1': 'value1', 'key2': 'value2'}
requests.get("http://httpbin.org/get", params=payload)

params参数接收的是一个字典

构建请求头

只需要简单地传递一个 字典给 headers 参数就可以了

例如:

h1={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36',

   
}

requests.get('http://localhost/api/mgr/sq_mgr/',
             headers=h1,
             params=payload)

定制请求体

请求体类型:Content-Type:   application/x-www-form-urlencoded

只需简单地传递一个字典给 data 参数

payload={'action':'add_course',
         'data':'''{
              "name":"初中化学
",
              "desc":"初中化学课程
",
              "display_idx":"4"
            }'''
        
}
resp=requests.post("http://localhost/api/mgr/sq_mgr/", data=payload)
请求体类型:Content-Type: application/json

可以将字典直接传递给json参数

payload2={
      "action" : "add_course_json",
      "data" : {
        "name":"初中化学",
        "desc":"初中化学课程",
        "display_idx":"4"
     
}
    }
resp=requests.post("http://localhost/apijson/mgr/sq_mgr/", json=payload2)

注意参数和URL的区别!!!!

查看响应内容

先获取到响应对象response

resp=requests.post("http://localhost/api/mgr/sq_mgr/", data=payload)

拿到响应对象就可以查看服务器返回的各种消息内容了

查看响应体:

resp.text

查看响应头:

resp.headers

如果响应体恰巧是json格式:

resp.json()

自动把json格式的字符串转成python对象,通常都是字典类型

那么再获取字典里面具体的值就很好操作了

retObj=resp.json()
 
if retObj['retcode'] == 0:
    print('pass')
else:
    print(retObj['retcode'])

附录

Postman JS代码示例:

https://learning.getpostman.com/docs/postman/scripts/test_examples/

request中文官方文档:

http://docs.python-requests.org/zh_CN/latest/

原文地址:https://www.cnblogs.com/iamshasha/p/11129491.html