httprunner 3.x学习17 - 断言字符串包含
Posted 上海-悠悠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
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!")
以上是关于httprunner 3.x学习17 - 断言字符串包含的主要内容,如果未能解决你的问题,请参考以下文章
httprunner 3.x学习16 - 断言使用正则匹配(assert_regex_match)