A07_HttpRunner重定向_04_解决方案

既然 HttpRunner 是对 requests 模块的封装,那我们就试图从 requests 中寻找答案,在其官网中发现了对重定向的描述和处理:
地址:http://cn.python-requests.org/zh_CN/latest/user/quickstart.html#id9
提到:
- 默认情况下,除了 HEAD, Requests 会自动处理所有重定向。
- 可以使用响应对象的 history 方法来追踪重定向。
- 如果你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通过 allow_redirects 参数禁用重定向处理
做个试验:
- 在 post 请求方法中添加 “allow_redirects=False”参数项
- 打印获取到的 cookie
import requestsdef get_cookies():    url = 'http://192.168.1.102/wordpress/wp-login.php'    p_data = {'log': 'admin', 'pwd': '123456'}    # 添加禁止重定向的参数    r = requests.post(url, data=p_data, allow_redirects=False)    print(r.status_code)    print(r.cookies)if __name__ == "__main__":    get_cookies()执行后输出:
可以看出请求后没有自动进行重定向,而且输出了我们期盼已久的 cookie 内容。
D:A00__DevpyvirtualenvhrunScriptspython.exe D:/A00__Dev/pyprojects/wordpress/getcookie.py302, , , ]>Process finished with exit code 0HttpRunner 中对请求的封装,是通过统一调用 request() 方法来完成的:
requests.request(method, url, **kwargs)接下来我们就将“allow_redirects=False”参数项添加到测试用例中
- config:    name: WordPress 博客系统- test:    name: WP_login_no_redirect    request:      url: http://192.168.1.102/wordpress/wp-login.php      method: POST      data:        log: admin        pwd: 123456      # 禁止重定向         allow_redirects: False    extract:      - a: cookies.wordpress_test_cookie      - b: cookies.wordpress_logged_in_6e644cc1baf05aba48f07f1ff2ed9bad      - d: cookies.wordpress_6e644cc1baf05aba48f07f1ff2ed9bad    validate:      - eq: [status_code, 302]验证用例:

执行用例,成功。说明提取指定 cookie 的操作和 302 状态的断言都成功。

查看测试报告日志:预期结果和实际结果都是302,证明禁止重定向成功。

最后,我们从 httprunner 源码中也可以找到以上方式的印证
httprunnerloaderschemascommon.schema.json 请求规范:
- 在测试用例 request 下可以使用 “allow_redirects”属性
- 该属性支持的请求方法为:GET / OPTIONS / POST / PUT / PATCH / DELETE / HEAD
- 该属性默认值为:True (自动进行重定向)
"request": {    "description": "used to define a api request. properties is the same as python package `requests.request`",    "type": "object",    "properties": {        。。。。。。。。。。。。        "allow_redirects": {                    "description": "Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to True",                    "type": "boolean"        },       。。。。。。。,。。。。。