httprunner 3.x学习16 - 断言使用正则匹配(assert_regex_match)

前言

httprunner 3.x可以支持正则匹配断言,使用assert_regex_match方法

assert_regex_match

assert_regex_match 源码如下

    def assert_regex_match(
        self, jmes_path: Text, expected_value: Text, message: Text = ""
    ) -> "StepRequestValidation":
        self.__step_context.validators.append(
            {"regex_match": [jmes_path, expected_value, message]}
        )
        return self

校验方法是 regex_match ,于是找到httprunner/builtin/comparators.py

def regex_match(check_value: Text, expect_value: Any, message: Text = ""):
    assert isinstance(expect_value, str), "expect_value should be Text type"
    assert isinstance(check_value, str), "check_value should be Text type"
    assert re.match(expect_value, check_value), message

断言结果返回的是re.match方法,传2个参数

  • expect_value 正则表达式
  • check_value 检查返回结果的字符串

使用示例

登录接口返回

# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

{
    "code":0,
    "msg":"login success!",
    "username":"test1",
    "token":"2a05f8e450d590f4ea3aba66294a26ec3fe8e0cf"
}

assert_regex_match 方法第一个参数是jmes_path,提取返回的body,比如我要正则匹配token是40位16进制

.assert_regex_match("body.token", "[0-9a-f]{40}")

yaml文件示例

# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

config:
    name: login case
    base_url: http://127.0.0.1:8000
    export:
    - token

teststeps:
-
    name: step login
    variables:
        user: test1
        psw: "123456"
    request:
        url: /api/v1/login
        method: POST
        json:
            username: $user
            password: $psw
    extract:
        token: content.token
    validate:
        - eq: [status_code, 200]
        - regex_match: [body.token, "[0-9a-f]{40}"]

pytest脚本

# NOTE: Generated By HttpRunner v3.1.4
# FROM: testcases\login_var.yml
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase


class TestCaseLoginVar(HttpRunner):

    config = (
        Config("login case")
        .base_url("http://127.0.0.1:8000")
        .export(*["token"])
    )

    teststeps = [
        Step(
            RunRequest("step login")
            .with_variables(**{"user": "test1", "psw": "123456"})
            .post("/api/v1/login")
            .with_json({"username": "$user", "password": "$psw"})
            .extract()
            .with_jmespath("body.token", "token")
            .validate()
            .assert_equal("status_code", 200)
            .assert_regex_match("body.token", "[0-9a-f]{40}")
        ),
    ]


if __name__ == "__main__":
    TestCaseLoginVar().test_start()

需注意的是正则匹配只能匹配字符串类型,不是字符串类型的可以用 jmespath 函数to_string()转字符串

.assert_regex_match("to_string(body.code)", "0")

上海-悠悠 blog地址https://www.cnblogs.com/yoyoketang/

网易云课程地址



点我 ->立即报名

posted @ 2021-06-23 12:40  上海-悠悠  阅读(867)  评论(0编辑  收藏  举报