F04_HttpRunner关联:通过头域匹配方式提取 SessionID

F04_HttpRunner关联:通过头域匹配方式提取 SessionID

 

 

 

从响应结构进行分析,cookie 出现在响应的头域内(headers),而且不管服务器返回了多少个cookie,浏览器再次请求的时候,都会把这些所有的cookie附加上。

 

那么我们能否把问题简化?不再费劲的取出某个cookie的名称和值,而是一股脑提取所有cookie,不管有用没用,后面再发起新的请求的时候,将这些提取到的所有cookie全部给服务器传回去,需要哪个,服务器自己来觉得吧,反正它要的肯定在这里面呢 :)

 

接下来试一试吧

 

首先回顾一下源码:httprunner-2.5.5\httprunner\response.py

# headers
elif top_query == "headers":
    headers = self.headers
    if not sub_query:
        # extract headers
        return headers

    try:
        return headers[sub_query]
    except KeyError:
        err_msg = u"Failed to extract header! => {}\n".format(field)
        err_msg += u"response headers: {}\n".format(headers)
        logger.log_error(err_msg)
        raise exceptions.ExtractFailure(err_msg)

 

 

里面关键有这么一句,可以返回 headers 里面的任意一个头域:

  return headers[sub_query]

 

 

那么我们来取出头中的所有的cookie,就可以这么表示了:

headers.Set-Cookie

 

 

重新调整测试用例:

- config:
    name: index

- test:
    name: Get SessionID
    request:
      url: http://localhost/myweb/jxc/index.asp
      method: GET
    extract:
      # 从请求头域中获取所有 cookie  
      - sid: headers.Set-Cookie
      - form: <FORM ACTION=\"(.*)\?action=login\" METHOD=\"post\" name=\"loginform\">
    validate:
      - eq: [status_code, 200]
      - eq: [$form, index.asp]

 

 

重新验证用例格式:

 

 

执行测试用例,成功。

 

用例执行通过,但是从命令行提示中,或者从测试报告中,并没有直接告诉我们提取 cookie 的情况如何。虽然没有报错就意味着成功,但是直观看到提取的内容会更加放心的,不是么?

 

 

解决办法也简单,使用 debug 日志级别来执行。

命令: hrun <用例名称> --log-level debug

 

在 HttpRunner 中可以选择五种日志模式,分别是:

  • DEBUG -> INFO -> WARNING -> ERROR -> CRITICAL
  • 默认级别: INFO

 

其中:

  • debug: 级别最低,打印日志信息最为详细,可用于代码调试
  • info:打印正常信息
  • warn: 打印警告信息
  • error: 打印错误信息
  • critical: 打印严重信息

 

源码:\httprunner-2.5.5\docs\run-tests\load-test.md

-L LOGLEVEL, --loglevel=LOGLEVEL
    Choose between DEBUG/INFO/WARNING/ERROR/CRITICAL.
    Default is INFO.

 

 

按 debug 模式执行后,在日志中有这么一行,可以看到提取出来我们想要的 cookie 了,而且这时候 cookie 的 “键名称” 无论如何变化也不用我们去操心了。


DEBUG    start to extract from response object.
DEBUG    extract: headers.Set-Cookie    => ASPSESSIONIDQCARSBQQ=LOBLJMGDKIGMKPIEBKHGDONJ; path=/

 

 

完整的 debug 日志如下:

D:\A00__Dev\HTTPRunnerTest\nostore>hrun t1.yml --log-level debug
INFO     HttpRunner version: 2.5.5
INFO     Start to run testcase: index
Get SessionID
INFO     GET http://localhost/myweb/jxc/index.asp
DEBUG    request kwargs(raw): {'verify': True}
DEBUG    processed request:
> GET http://localhost/myweb/jxc/index.asp
> kwargs: {'verify': True, 'timeout': 120}
DEBUG
================== request details ==================
url              : 'http://localhost/myweb/jxc/index.asp'
method           : 'GET'
headers          : {'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, defl
ate', 'Accept': '*/*', 'Connection': 'keep-alive'}

DEBUG
================== response details ==================
ok               : True
url              : 'http://localhost/myweb/jxc/index.asp'
status_code      : 200
reason           : 'OK'
cookies          : <RequestsCookieJar[Cookie(version=0, name='ASPSESSIONIDQCARSBQQ', value='LOBLJMGDKIGMKPIEBKHGDONJ'........., rfc2109=False)]>
encoding         : 'ISO-8859-1'
headers          : {'Cache-Control': 'no-cache', 'Content-Type': 'text/html', ...... 'Content-Length': '1902'}
content_type     : 'text/html'
body             : '\r\n<HTML>\r\n<HEAD>\r\n<TITLE> ......'

INFO     status_code: 200, response_time(ms): 49.0 ms, response_length: 4046 bytes

DEBUG    start to extract from response object.
DEBUG    extract: headers.Set-Cookie    => ASPSESSIONIDQCARSBQQ=LOBLJMGDKIGMKPIEBKHGDONJ;path=/
DEBUG    extract: <FORM ACTION=\"(.*)\?action=login\" METHOD=\"post\" name=\"loginform\">=> index.asp
DEBUG    start to validate.
DEBUG    extract: status_code   => 200
DEBUG
validate: status_code equals 200(int)   ==> pass
DEBUG
validate: LazyString($form) equals index.asp(str)       ==> pass
.

----------------------------------------------------------------------
Ran 1 test in 0.123s

OK
DEBUG    No html report template specified, use default.
INFO     Start to render Html report ...
INFO     Generated Html report: D:\A00__Dev\HTTPRunnerTest\nostore\reports\20200403T063629.057808.html
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-Break to quit

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值