httprunner 3.x学习17 - 断言字符串包含
前言
校验接口返回结果,我们习惯校验实际结果和期望结果相等,如果只是部分相等可以用contains包含校验
校验包含
先看下httprunner/builtin/comparators.py 关于 contains 和 contained_by 函数定义
- check_value 是需要校验的返回结果
- expect_value 是期望结果,可以是这几种类型:list, tuple, dict, basestring
def contains(check_value: Any, expect_value: Any, message: Text = ""):
assert isinstance(
check_value, (list, tuple, dict, str, bytes)
), "expect_value should be list/tuple/dict/str/bytes type"
assert expect_value in check_value, message
def contained_by(check_value: Any, expect_value: Any, message: Text = ""):
assert isinstance(
check_value, (list, tuple, dict, str, bytes)
), "expect_value should be list/tuple/dict/str/bytes type"
assert check_value in expect_value, message
使用示例
登录结果返回
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
{
"code":0,
"msg":"login success!",
"username":"test1",
"token":"2a05f8e450d590f4ea3aba66294a26ec3fe8e0cf"
}
校验 msg 包含 success! 字符串
validate:
- eq: [status_code, 200]
- contains: [body.msg, success!]
如果code返回的结果有多种情况,可能为0,也可以为200,这2种情况但是可以的,于是可以用 contained_by 被包含在[0, 200]
validate:
- eq: [status_code, 200]
- contains: [body.msg, success!]
- contained_by: [body.code, [0, 200]]
对应pytest代码
.validate()
.assert_equal("status_code", 200)
.assert_contains("body.msg", "success!")
.assert_contained_by("body.code", [0, 200])
但是会抛出异常:
E httprunner.exceptions.ValidationFailure: assert body.code contained_by [0, 200](list) ==> fail
E check_item: body.code
E check_value: 0(int)
E assert_method: contained_by
E expect_value: [0, 200](list)
E message: expect_value should be list/tuple/dict/str/bytes type
报错说 expect_value 必须是 list/tuple/dict/str/bytes 类型,但确实是给的list 类型[0, 200]
这是因为httprunner3.1.4版本的一个bug,把上面源码里面的contained_by函数check_value改成expect_value,这个bug就可以修复
def contained_by(check_value: Any, expect_value: Any, message: Text = ""):
assert isinstance(
expect_value, (list, tuple, dict, str, bytes)
), "expect_value should be list/tuple/dict/str/bytes type"
assert check_value in expect_value, message
(备注:此问题在httprunner 3.1.5版本已修复,更新时间2021年6月27号)
startswith 和 endswith
校验字符串以什么和以什么结果
- startswith 字符串以expect_value开头
- endswith 字符串以expect_value结尾
def startswith(check_value: Any, expect_value: Any, message: Text = ""):
assert str(check_value).startswith(str(expect_value)), message
def endswith(check_value: Text, expect_value: Any, message: Text = ""):
assert str(check_value).endswith(str(expect_value)), message
使用示例
validate:
- eq: [status_code, 200]
- startswith: [body.msg, login]
- endswith: [body.msg, success!]
pytest 示例
.validate()
.assert_equal("status_code", 200)
.assert_startswith("body.msg", "login")
.assert_endswith("body.msg", "success!")
网易云课程地址