API (接口) 自动化测试 Requests + unittest

本文详细介绍了如何使用Requests库结合unittest进行API自动化测试,包括设置超时、session管理、SSL证书验证、流媒体上传及事件钩子等功能,并强调了API测试的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

enter description here

enter description here

目录

前言:

jupyter 笔记部分

返回状态码

返回 headers

headers 是一个字典数据,可以获取指定字段值

跳转和历史

超时

通过设置 timeouts 可以设置超时时间,如果没有设置,默认不会超时

高级部分

session 对象

session 对象允许你保存跨 requests 请求的特定参数。它也可以保持回话实例,简单说,当你 API 需要登录验证之后保持会话或者带上 cookie 信息,先调用 Session 方法,再调用后面的 API 方法

session 也可以用来提供默认的参数

下面这个例子设置了 auth 和 header 里面的默认参数

需要注意的是,通过方法显示传递的参数不会被提交,下面的这个例子第二个 get 方法不会带上第一个 cookie 参数

如果你需要手动设置参数,可以通过 session.cookies 设置

session 也可以被上下文管理器使用

预置参数

当发起 request 请求时候,request 的参数实际上被存储在 PreparedRequest 里面。你可以根据你的需求来修改预置参数。

SSL 证书

默认开始 SSL 证书验证

你可以将用受信任的 CAs 证书将验证路径传递到 CA_BUNDLE 文件或目录:

忽略证书验证

客户端证书验证

如果使用错误证书或者错误路径,会得到一个 SSLerror

流媒体上传

request 允许你直接上传文件

事件钩子

requests 有个一钩子系统,允许你操纵 request 的请求过程,或者信号处理

你也可以同时操纵多个钩子函数


前言:

API 自动化测试是一种针对 API 接口进行测试的方法。API 接口是应用程序与外部系统之间交互的桥梁,因此其正确性和稳定性非常重要。API 自动化测试可以帮助我们快速地验证 API 接口的功能和性能,从而保证应用程序的质量和稳定性。

jupyter 笔记部分

返回状态码

import requests
r = requests.get('https://httpbin.org/get')
r.status_code

requests 还有一个等同的内建对象

r.status_code == requests.codes.ok

返回 headers

r.headers

headers 是一个字典数据,可以获取指定字段值

r.headers.get('content-type')
r.headers['Content-Type']

跳转和历史

r = requests.get('http://github.com/')
r.history
### 通过设置allow_redirects参数可以设置跳转,默认为false
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code

超时

通过设置 timeouts 可以设置超时时间,如果没有设置,默认不会超时

requests.get('https://github.com/', timeout=0.001)

高级部分

session 对象

session 对象允许你保存跨 requests 请求的特定参数。它也可以保持回话实例,简单说,当你 API 需要登录验证之后保持会话或者带上 cookie 信息,先调用 Session 方法,再调用后面的 API 方法

import requests
s = requests.Session()
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('https://httpbin.org/cookies')
r.text

'{\n "cookies": {\n "sessioncookie": "123456789"\n }\n}\n'

session 也可以用来提供默认的参数

下面这个例子设置了 auth 和 header 里面的默认参数

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

#  'x-test' 和 'x-test2' 都会被提交
r=s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})
r.text

需要注意的是,通过方法显示传递的参数不会被提交,下面的这个例子第二个 get 方法不会带上第一个 cookie 参数

如果你需要手动设置参数,可以通过 session.cookies 设置

s = requests.Session()
r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})
print(r.text)

r = s.get('https://httpbin.org/cookies')
r.text

session 也可以被上下文管理器使用

下面这个 session 将会随着 with 这个代码块结束而结束

with requests.Session() as s:
    s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')

预置参数

当发起 request 请求时候,request 的参数实际上被存储在 PreparedRequest 里面。你可以根据你的需求来修改预置参数。

from requests import Request, Session

s = Session()
payload = {'key1': 'value1', 'key2': 'value2'}
req = Request('POST',"https://httpbin.org/post", data=payload)
# 获取预置参数
prepped = req.prepare()

# do something with prepped.body
prepped.body = 'No, I want exactly this as the body.'

# do something with prepped.headers
del prepped.headers['Content-Type']

resp = s.send(prepped,
    timeout=10
)
resp.status_code

200

SSL 证书

默认开始 SSL 证书验证

#需要填入一个无效证书的URL,则会抛出异常
r=requests.get('https://example')

你可以将用受信任的 CAs 证书将验证路径传递到 CA_BUNDLE 文件或目录:

requests.get('https://github.com', verify='/path/to/certfile')

忽略证书验证

requests.get('https://kennethreitz.org', verify=False)

/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: Advanced Usage - urllib3 2.0.4 documentation
InsecureRequestWarning)

客户端证书验证

requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))

如果使用错误证书或者错误路径,会得到一个 SSLerror

requests.get('https://kennethreitz.org', cert='/wrong_path/client.pem')

流媒体上传

request 允许你直接上传文件

with open('massive-body', 'rb') as f:
    requests.post('http://some.url/streamed', data=f)

事件钩子

requests 有个一钩子系统,允许你操纵 request 的请求过程,或者信号处理

参数定义 hooks={'response': print_url}

# 方法定义,一个打印url的钩子函数
def print_url(r, *args, **kwargs):
    print(r.url)
# 使用钩子
requests.get('https://httpbin.org/', hooks={'response': print_url})

你也可以同时操纵多个钩子函数

def record_hook(r, *args, **kwargs):
    r.hook_called = True
    return r
r = requests.get('https://httpbin.org/', hooks={'response': [print_url, record_hook]})
r.hook_called

  作为一位过来人也是希望大家少走一些弯路

在这里我给大家分享一些自动化测试前进之路的必须品,希望能对你带来帮助。

(软件测试相关资料,自动化测试相关资料,技术问题答疑等等)

相信能使你更好的进步!

点击下方小卡片

【自动化测试交流】:574737577(备注ccc)icon-default.png?t=N6B9http://qm.qq.com/cgi-bin/qm/qr?_wv=1027&k=8J30vUQ4Dwe-Bi6g7S7DSz8H0yLtnwiy&authKey=hx0%2BVuvMtmByHmuBIh0PIsaP55U45oHRQeQi9su5xrtqQvx2cqoeqUDYRYlity4c&noverify=0&group_code=574737577 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值