httprunner 3.x學習16 - 斷言使用正則匹配(assert_regex_match)
阿新 • • 發佈:2021-06-23
前言
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
variables:
user: test
psw: "123456"
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")
.variables(**{"user": "test", "psw": "123456"})
.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/](blog地址 https://www.cnblogs.com/yoyoketang/)