httprunner学习26-cookies关联(403 Forbidden问题解决)
作者:互联网
前言
在使用httprunner写接口自动化用例时,遇到有些接口需要用到cookies,如果cookie没关联起来的话,会出现403 Forbidden的问题
问题描述用httprunner写了个网页的登录用例,以下是相关的脚本参考test_cookie_demo.yml
# 作者:上海-悠悠 qq交流群:874033608 - config: name: test login api demo variables: {} request: base_url: http://49.235.x.x:80xx - test: name: 测试用例名称 request: headers: Content-Type: application/x-www-form-urlencoded data: csrfmiddlewaretoken: ChMBwCgvH04sOA1XhPkPzUbfKDD5O8lmqAYR0oWIvSH2waMWpnzaxytvj8EUQgCF username: admin1 password: 1111111***** method: POST url: /xadmin/ validate: - eq: - status_code - 200
运行结果
D:\soft\code\demo>hrun test_cookie_demo.yml 测试用例名称 INFO POST /xadmin/ ERROR 403 Client Error: Forbidden for url: http://49.235.x.x:80xx/xadmin/ INFO start to validate. ERROR validate: status_code equals 200(int) ==> fail 403(int) equals 200(int) ERROR request: headers: {'content-type': 'application/x-www-form-urlencoded'} json: {'data': 'ChMBwCgvH04sOA1XhPkPzUbfKDD5O8lmqAYR0oWIvSH2waMWpnzaxytvj8EUQgCF', 'username': 'admin', 'password': '11111111***'} ERROR response: status_code: 403
运行结果出现:403 Forbidden
出现403 Forbidden问题,一般是网站处于安全考虑,缺少cookies导致,可以在页面登录的时候,用fiddler抓一个登陆成功的包对比下就知道了
那么这个cookies从哪来的呢,一般是浏览器打开登录首页的时候(还没输入账号和密码的时候),服务端会返回cookies过来,浏览器会记住缓存。
所以解决这个问题就模拟浏览器打开登录页一样,先发个get请求访问登录首页,获取到cookie后再去登录
httprunner框架继承了requests库的优良特征,会自动管理cookie(看到有些同学费尽周折去提取cookies,又去关联cookies,其实没必要)
# 作者:上海-悠悠 qq交流群:874033608 - config: name: test login api demo variables: {} request: base_url: http://49.235.x.x:80xx - test: name: 先访GET问登录首页,获取cookies request: method: GET url: /xadmin/ extract: - csrfmiddlewaretoken: name='csrfmiddlewaretoken' value='(.+?)' # 页面正则提取隐藏参数csrfmiddlewaretoken validate: - eq: - status_code - 200 - test: name: 登录用例 request: headers: Content-Type: application/x-www-form-urlencoded data: csrfmiddlewaretoken: $csrfmiddlewaretoken username: admin1 password: 1111111***** this_is_the_login_form: "1" next: /xadmin/ method: POST url: /xadmin/ validate: - eq: - status_code - 200
运行结果
D:\soft\code\demo>hrun test_cookie_demo.yml 先访GET问登录首页,获取cookies INFO GET /xadmin/ INFO status_code: 200, response_time(ms): 34.57 ms, response_length: 4163 bytes INFO start to extract from response object. INFO start to validate. . 登录用例 INFO POST /xadmin/ INFO status_code: 200, response_time(ms): 132.31 ms, response_length: 4400 bytes INFO start to validate. . ---------------------------------------------------------------------- Ran 2 tests in 0.181s OK INFO Start to render Html report ... INFO Generated Html report: D:\soft\code\demo\reports\2020_02_21 23_21_19.html
使用fiddler抓包查看,会发现cookie已经关联成功了
csrfmiddlewaretoken参数是html页面上的隐藏参数,这个在django系列教程里面提到过,是为了防止跨域伪造请求。
每次刷新页面都会自动变的,所以需要先把此参数提取出来,动态关联到请求参数的body里面去
标签:INFO,26,code,httprunner,demo,Forbidden,cookies,xadmin,test 来源: https://blog.51cto.com/u_15249893/2850502