python内置了HTTP库 urllib,可以用于发送http请求。基于Python的第三方库Requests是对urllib的再次封装,相比urllib更加简洁易用。Requests库不仅用于接口测试,还用在Python爬虫、量化交易等。本文介绍Requests库的使用方法。

Requests

HTTP接口测试涉及到以下几个方面:

  • 构造请求方法:get、post、put、 delete、head ......
  • 构造请求体:form、json、xml、 binary
  • 分析响应结果:status code、 response body、 json path、 xpath

下面介绍使用Requests怎么实现这些步骤。

Requests安装

Github地址:Python HTTP Requests for Humans

requests官方文档: https://requests.readthedocs.io/zh_CN/latest/index.html

安装:

pip install requests

http请求响应测试接口:https://httpbin.testing-studio.com/

也可以自己本地搭建,GitHub地址:https://github.com/postmanlabs/httpbin

Requests常见接口请求方法构造

常见接口请求方法:

r = requests.get('https://api.github.com/events') #get请求
r = requests.post('http://httpbin.org/post', data = {'key':'value'}) #post请求
r = requests.put('http://httpbin.org/put', data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')

请求目标构造

请求URL

import requests
r = requests.get('https://api.github.com/events') #get请求
print(r.status_code)

输出:

200

header构造

普通的 header

url = 'https://api.github.com/some/endpoint'
headers ={user-agent': 'my-app/0.0.1'}
r= requests.get(url, headers=headers)

cookie

url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)

构造请求体

请求体通过键值对的形式编码,有多种形式的请求体,比如query参数、form请求、binary请求(上传文件)以及结构化请求:json、xml、 json rpc等。

Get Query请求

payload= {'key':'valuel','key2':'value2'}
r = requests.get('https://httpbin.org/get', params=payload)

Form请求参数

payload = {'key':'valuel','key2':'value2'}
r = requests.post("https://httpbin.org/post", data=payload)

JSON请求体构造

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)

xml请求

import requests
xml ="""<?xml version='1.0' encoding='utf-8'?><a>6</a>"""
headers={'Content-type':'application/xml'}
r = requests.post('http://httpbin.org/post', data=xml, headers=headers).text

binary请求

上传文件

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

接口测试断言

接口测试中需要通过检查响应是否符合预期来测试接口有效性,也就是对接口响应进行断言。

响应

  • r.url:
  • r.status_code
  • r.headers
  • r.cookies
  • r.encoding
  • r.content
  • r.text
  • r.json()
import requests

class TestRequest():
def test_get(self):
r = requests.get('https://api.github.com/events') #get请求
assert r.status_code == 200

结构化响应断言

下面是请求Github项目仓库API,GitHub API可参考:https://docs.github.com/cn/rest/overview

import requests
import json r = requests.get('https://api.github.com/repos/hiyongz/DjangoDemo')
json_data = r.json()
print(json.dumps(json_data, indent=4))

响应的部分json数据如下:

{
"id": 272401302,
"node_id": "MDEwOlJlcG9zaXRvcnkyNzI0MDEzMDI=",
"name": "DjangoDemo",
"full_name": "hiyongz/DjangoDemo",
"private": false,
"owner": {
"login": "hiyongz",
"id": 20513021,
"node_id": "MDQ6VXNlcjIwNTEzMDIx",
"avatar_url": "https://avatars0.githubusercontent.com/u/20513021?v=4",
"gravatar_id": "",
...................
}

接下来介绍不同方法对这个json响应进行断言。

json断言

json断言

import requests

def test_json(self):
r = requests.get('https://api.github.com/repos/hiyongz/DjangoDemo')
assert r.json()['owner']['login'] == "hiyongz"

JSONPath断言

JSONPath文档:https://goessner.net/articles/JsonPath/

JSONPath表达式与XPath类似,是XPath在json中的应用,全称XPath for JSON,用于从JSON文档中提取数据。JSONPath表达式和XPath语法对比如下:

XPath JSONPath Description
/ $ 跟节点
. @ 当前节点
/ . or [] 儿子节点
.. N/A 父节点
// .. 子孙节点
* * 匹配所有节点
@ N/A 属性
[] [] 下标操作符
| [,] 多选
N/A [start​ : end : ​step] 切片
[] ?() 过滤表达式
N/A () script 表达式
() N/A 分组

Python中有个jsonpath库可用于处理json数据:https://pypi.org/project/jsonpath/

安装:

pip install jsonpath

和前面一样,断言登录名:

import requests
from jsonpath import jsonpath def test_json(self):
r = requests.get('https://api.github.com/repos/hiyongz/DjangoDemo')
assert jsonpath(r.json(), '$..login')[0] == "hiyongz"

schema断言

JSON Schema可以用来注释和验证 JSON 文档,官网:http://json-schema.org/

JSON Schema可用来添加自定义规则,可以自定义数据类型:

schema = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
},
}

可以看到,除了字段值断言外,可以使用JSON Schema来断言接口返回值的类型。

把json格式转成schema,在线生成schema网址:https://jsonschema.net/

jsonschema是使用JSON Schema的Python库,通过 pip install jsonschema 命令安装。

import requests
from jsonschema import validate def test_get_login_jsonschema(self):
url = "https://api.github.com/repos/hiyongz/DjangoDemo"
r = requests.get(url)
data = r.json()
schema = {
"name" : "DjangoDemo",
"owner" : {
"login" : "hiyongz",
},
}
validate(data, schema=schema)

JSON Schema可以用来进行自动校验:在接口测试中,每次运行的时候自动保存当前的 schema,下次运行对比上次的 schema,如果发现变更就报错

xml解析断言

xml文件解析可以使用requests_xml,参考:https://github.com/erinxocon/requests-xml

也可以使用Python xml.etree.ElementTree模块解析xml数据,可以使用Xpath定位,使用方法参考Web自动化测试:xpath & CSS Selector定位

xml.etree.ElementTree模块xml解析举例:

import xml.etree.ElementTree as ET
root = ET.fromstring(countrydata)
root.findall(".")
root.findall("./country/neighbor")
root.findall(".//year/..[@name='Singapore']")
root.findall(".//*[@name='Singapore']/year")
root.findall(".//neighbor[2]")

和JSON Schema一样,也有一个XML Schema,用于解析xml文档,文档参考:https://www.w3.org/2001/XMLSchema

Python库安装: pip install xmlschema

hamcrest断言

除了常用的Assert断言以外,有一个功能更加强大的断言方法叫Hamcrest 断言,具有丰富的断言匹配器,支持多种语言,官网地址:http://hamcrest.org/

下面简单介绍一下Python中的hamcrest断言使用方法

PyHamcrest GitHub仓库地址:https://github.com/hamcrest/PyHamcrest

文档:https://pyhamcrest.readthedocs.io/en/v2.0.2/tutorial/

安装PyHamcrest:

pip install PyHamcrest

断言登录名:

import requests
from hamcrest import * def test_hamcrest(self):
r = requests.get('https://api.github.com/repos/hiyongz/DjangoDemo')
data = r.json()
assert_that(data['owner']['login'], equal_to("hiyongz"))

--THE END--

文章标题:接口测试框架Requests

本文作者:hiyo

本文链接:https://www.cnblogs.com/hiyong/p/14288463.html

欢迎关注公众号:「测试开发小记」及时接收最新技术文章!

接口测试框架Requests的更多相关文章

  1. requests库写接口测试框架初学习

    学习网址:    https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dscpm/ff75b907-415d-4220-89 ...

  2. 接口测试框架实战(一) | Requests 与接口请求构造

    1080×388 33.4 KB Requests 是一个优雅而简单的 Python HTTP 库,其实 Python 内置了用于访问网络的资源模块,比如urllib,但是它远不如 Requests ...

  3. 【转】基于Python的接口测试框架实例

    下面小编就为大家带来一篇基于Python的接口测试框架实例.小编觉得挺不错的,现在就分享给大家,也给大家做个参考.一起跟随小编过来看看吧   背景 最近公司在做消息推送,那么自然就会产生很多接口,测试 ...

  4. 基于python的接口测试框架设计(三)接口测试的框架

    基于python的接口测试框架设计(三)接口测试的框架 其实我这里用到的是unittest单元测试框架,,这个框架好就好在比较清楚,,setup terdown都可以处理一些初始化及完成后的工作 主要 ...

  5. Python接口测试实战4(上) - 接口测试框架实战

    如有任何学习问题,可以添加作者微信:lockingfree 课程目录 Python接口测试实战1(上)- 接口测试理论 Python接口测试实战1(下)- 接口测试工具的使用 Python接口测试实战 ...

  6. 基于Python的接口测试框架实例

    文章来源:http://www.jb51.net/article/96481.htm 下面小编就为大家带来一篇基于Python的接口测试框架实例.小编觉得挺不错的,现在就分享给大家,也给大家做个参考. ...

  7. http接口测试框架-python

    简单分解一下 接口测试框架设计: 主入口 -> 遍历接口/用例 -> 发送请求+接收响应 ->结果的对比 -> 生成报告 ->发送email 分成几大类:主入口的py文件 ...

  8. 基于HttpRunner,解析swagger数据,快速生成接口测试框架

    使用HttpRunner默认生成的项目是这样的 命令:httprunner --startproject  项目名称 so,根据这个项目的目录结构,使用python解析swagger接口参数,可以快速 ...

  9. yamlpy接口测试框架

    1.思路: yamlpy即为yaml文件+pytest单元测试框架的缩写, 可以看作是一个脚手架工具, 可以快速生成项目的各个目录与文件, 只需维护一份或者多份yaml文件即可, 不需要大量写代码. ...

随机推荐

  1. C语言目的概念(C语言学习笔记)

    什么是目 目是针对操作符来说的,一个操作符影响两个操作数就表示该操作符为双目运算符 举个例子: 1+2 这里的加号影响了1和2两个操作数,所以"+"就是双目运算符 +1,-1 这里 ...

  2. Python eval 函数用途

    Python eval 函数用途: eval 函数可将字符串转换成列表,元组和字典 实例如下: 可以把list,tuple,dict和string相互转化. ##################### ...

  3. 通过logmnr找到被修改前的存储过程

    1.找到存储过程被修改时的归档日志 SELECT NAME FROM V$ARCHIVED_LOG WHERE FIRST_TIME BETWEEN TO_DATE('20191118080000', ...

  4. SAP RFC的相关的术语说明

    工作比较忙,很少有时间写点文章,抽空写点吧,给需要的人看看,虽然徒弟很多了,不过还是不要固步自封,在这里也指导更多的人进步吧. RFC(Remote Function Call)是SAP系统和其他(S ...

  5. Django中多表关联的展示问题:

    增加一个知识点,当表中有多对多关联时,在前端展示的时候是一个列表,所以在展示的时候需要这样做: 表结构: class ProjectEnv(models.Model): project = model ...

  6. uni-app开发经验分享十六:发布android版App的详细过程

    开发环境 1. Android Studio下载地址:Android Studio官网 OR Android Studio中文社区 2. HBuilderX(开发工具) 3. App离线SDK下载:最 ...

  7. ORB-SLAM2-tracking线程

    tracking线程 Tracking线程的主要工作是从图像中提取ORB特征,根据上一帧进行姿态估计或者进行通过全局重定位初始化位姿,然后跟踪已经重建的局部地图,优化位姿,再根据一些规则确定新的关键帧 ...

  8. 聊聊.net应用程序的Docker镜像

    ​要在容器中运行.net应用程序,你需要在容器镜像中安装.net Framework或.net Core 运行时.这不是你需要自己管理的东西,因为微软提供的Docker镜像已经安装了运行时,你可以使用 ...

  9. 【Android初级】使用TypeFace设置TextView的文字字体(附源码)

    在Android里面设置一个TextView的文字颜色和文字大小,都很简单,也是一个常用的基本功能.但很少有设置文字字体的,今天要分享的是通过TypeFace去设置TextView的文字字体,布局里面 ...

  10. Mybatis plus通用字段自动填充的最佳实践总结

    在进行持久层数据维护(新增或修改)的时候,我们通常需要记录一些非业务字段,比如:create_time.update_time.update_by.create_by等用来维护数据记录的创建时间.修改 ...