接口和协议组成 API (接口) 自动化测试 Requests + unittest (二)

阿东 · 2019年03月13日 · 1360 次阅读

接着第一章内容继续总结 request 的使用,还是使用 Jupyter 格式记录的,需要实战的从 github 下载原文件执行。

脑图部分:

enter description here

enter description here

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: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
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 的请求过程,或者信号处理

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

https://httpbin.org/

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

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

https://httpbin.org/

True

公众号:自动化测试工作坊

暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册