D07_用例中提取数据:elapsed 响应时间提取案例
在 HttpRunner 中提取数据时,根据界定符的方式进行提取,涉及到的内容包括如下:
- ["status_code", "encoding", "ok", "reason", "url"]
- cookies
- elapsed
- headers
- ["body", "content", "text", "json"]
获取的 elapsed 代表 “响应时间”
可用时间表示方式:days, seconds, microseconds, total_seconds
关于 elapsed 的使用,HttpRunner 直接继承自 request 模块:
更新相关说明:https://requests.readthedocs.io/zh_CN/latest/community/updates.html#updates
2.14.0 (2017-05-09)
Improvements
Changed the internal calculation of elapsed request time to have higher resolution on Windows.
1.2.0 (2013-03-31)
Add elapsed attribute to Response objects to time how long a request took.
源码:requests-2.23.0\requests\models.py
#: The amount of time elapsed between sending the request
#: and the arrival of the response (as a timedelta).
#: This property specifically measures the time taken between sending
#: the first byte of the request and finishing parsing the headers. It
#: is therefore unaffected by consuming the response content or the
#: value of the ``stream`` keyword argument.
self.elapsed = datetime.timedelta(0)
注意:
- 此属性专门度量从发送请求的第一个字节到完成对响应标头的解析所花费的时间。
- 此时间不包括对响应实体部分的处理。
requests-2.23.0\requests\sessions.py
# Start time (approximately) of the request
# 记录请求的开始时间
start = preferred_clock()
# Send the request
r = adapter.send(request, **kwargs)
# Total elapsed time of the request (approximately)
# 通过开始时间和结束时间计算时间差
elapsed = preferred_clock() - start
r.elapsed = timedelta(seconds=elapsed)
以访问百度为例:
- test:
name: TestStep-1
request:
url: https://www.baidu.com
method: GET
extract:
# 提取响应时间
- t1: elapsed.microseconds # 单位:微秒 (1秒=1000毫秒=1000000微秒)
- t2: elapsed.total_seconds # 单位:秒(将微秒换算为秒)
- t3: elapsed.seconds # 单位:秒(最小值为1秒)
- t4: elapsed.days # 单位:天(最小值为1天)
validate:
# lt:实际结果小于预期结果即为验证通过
- lt: [$t1, 2000000]
- lt: [$t2, 2]
- lt: [$t3, 1]
- lt: [$t4, 0.01]
执行后测试报告截取如下