接口测试 复杂数据解析 结构化响应断言JSON XML hamcrest断言体系 schema校验

测试框架基本能力

项目管理:pip、virtualenv
用例编写:pytest
领域能力:app、web
执行调度:pytest、pycharm、shell、jenkins
测试报告:allure2

HTTP测试能力

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

架构特点(requests)

功能全面:http / https支持全面
使用简单:简单易用,不用关心底层细节
定制性高:借助于hook机制完成通用处理
requests使用文档https://requests.readthedocs.io/zh_CN/latest/
简书介绍的基本使用https://www.jianshu.com/p/2065f0292de6

请求参数构造

get query :path 、query
post body:
form:
结构化请求:json、xml、json rpc
binary

Cookie简介

cookie使用场景
在接口测试过程中,很多情况下,需要发送的请求附带cookies,才会得到正常的相应的结果。所以使用python+requests进行接口自动化测试也是同理,需要在构造接口测试用例时加入cookie。
传递cookie的两种方式
通过请求头信息传递
通过请求的关键字参数cookies传递
使用headers传递

import requests
def test_header():
    url = 'url....'
    header = {
        "Cookie": "cookiesValue"
    }
    r = requests.get(url=url, headers=header)  # 使用headers传递
    print(r.request.headers)

使用cookies传递

import requests
def test_header():
    url = 'url....'
    cookie_data = {"Cookie": "cookiesValue"}
    r = requests.get(url=url, cookies=cookie_data)  # 使用cookies传递
    print(r.request.headers)

http basic

基本认证(英文:Basic access authentication)是允许http用户代理(如:网页浏览器)在请求时,提供用户名和密码的一种方式。
在这里插入图片描述
解决方式:在自动化测试过程中,使用auth参数传递认证信息

import requests
from requests.auth import HTTPBasicAuth
def test_login_auth():
    r = requests.get(url="xxxxURLxxxx",
                 auth=HTTPBasicAuth("name","password"))
    print(r.text)

get请求
样例:

payload = {}
requests.get(URL,params=payload)
    def test_get(self):
    	headers = {}
    	cookies = dict(cookie_are='cookies')
        payload = {}
        r = requests.get('https://www.baidu.com/',headers=headers,cookies=cookies,params=payload)
        print(r.status_code)
        assert r.status_code == 200

post请求
样例:form格式

headers = {}
cookies = dict(cookie_are='cookies')
payload = {}
requests.post(URL,headers=headers,cookies=cookies,data=payload)  # 注意这里变成了data 
    def test_post(self):
    	headers = {}
        payload = {"name": "新年"}       	      r=requests.post('https://api.alibabadesign.com/trade/supplier/settledSuppliersQueryByName',headers=headers,data=payload)
        print(r.status_code)
        print(r.text)
        assert r.status_code == 200

文件上传

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

响应结果

基本信息:r.url、r.status_code、r.headers、r.cookies
响应结果:
r.text = r.encoding + r.content
r.json() = r.encoding + r.content + content type json
r.raw.read(10)
对应的请求内容:r.request

结构化请求体构造JSON XML

JSON请求体

payload = {"key":"value"}
r = requests.post(url,json=payload)  # 发送出去的时候,说句是一个json的格式发出
    def test_post(self):
    	headers = {}
        payload = {"name": "新年"}       	       r=requests.post('https://api.alibabadesign.com/trade/supplier/settledSuppliersQueryByName',headers=headers,json=payload)
        print(r.status_code)
        print(r.text)
        assert r.status_code == 200

XML请求

xml=<?xml></xml>
headers={'Content-Type':'application/xml'}
requests.post(URL,headers=headers,cookies=cookies,data=xml).text 

复杂数据解析

数据保存:将复杂的xml或者json请求体保存到文件模版中
数据处理
使用mustache、freemaker等工具解析
简单的字符串替换
使用json xml api 进行结构化解析
数据生成:输出最终结果

模版技术mustache

在这里插入图片描述

结构化响应断言JSON XML

JSON断言

    def test_post(self):
    	headers = {}
        payload = {"name": "新年"}       	       r=requests.post('https://api.alibabadesign.com/trade/supplier/settledSuppliersQueryByName',headers=headers,json=payload)
        print(r.status_code)
        print(r.text)
        assert r.status_code == 200
        assert r.json()['json']['name'] == '新年'  # JSON断言

json path
安装: pip install jsonpath
在这里插入图片描述

assert jsonpath(r.json(),'$..name')[0] == "测试"

XML断言

from requests_xml import XMLSession   # 首先安装 requests_xml
session = XMLSession()
r = session.get('url')
r.xml.links

xpath断言

from requests_xml import XMLSession
session = XMLSession()
r = session.get('url')
r.xml.links
r.xml.xpath('//item',first=True)
print(item.text)

xml解析

import xml.etree.ElementTree as ET
root = ET.fromstring(countrydata)  # 对获取到的内容countrydata解析成xml
root.findall(".")
root.findall("./country/neighbor")
root.findall(".//year/..[@name='Singapore']")
root.findall(".//*[@name='Singapore']/year")
root.findall(".//neighbor[2]")
hamcrest断言体系

框架自带assert体系:assert、assertEqual
Hamcrest体系:assertThat
使用文档:http://hamcrest.org/
GitHub地址:https://github.com/hamcrest/PyHamcrest

from hamcrest import *
import unittest

class BiscuitTest(unittest.TestCase):
    def testEquals(self):
        theBiscuit = Biscuit("Ginger")
        myBiscuit = Biscuit("Ginger")
        assert_that(theBiscuit, equal_to(myBiscuit))

if __name__ == "__main__":
    unittest.main()

在这里插入图片描述

schema校验

schema网址:https://jsonschema.net/home
schema官网说明:https://json-schema.org/understanding-json-schema/

from jsonschema import validate
def test_get_jsonschema(self):
    url = 'https://www.baidu.com/'
    requests.get(url,params={limit:'2'}).json
    schema = json.load(open("topic_schema.json"))
    validate(data,schema=schema)

schema自动校验
每次运行的时候自动保存当前的schema。
下次运行对比上次的schema如果发现变更就报错。
saveSchema + diffSchema

小结:接口测试这里使用requests方法,在发送请求的过程中,会根据需要填写请求方法,url,headers等信息,当使用cookies时,有两种方式,headers传递和cookies传递。当遇到基本认证basic,可以使用auth。
对于传递参数,有多种格式,json、xml和form。对于复杂传参数据可以使用解析模版技术mustache。
断言:我们通常使用JSON断言,XML断言,xpath断言。对于自定的可以使用hamcrest断言体系。和schema校验

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值