httprunner 3.x学习2 - 测试用例结构(testcase)

前言

httprunner 3.x 支持3种格式的用例:YAML/JSON/pytest 代码,3.x版本主推的是pytest测试用例。

测试用例结构

httprunner 3.x 版本弱化了api层的概念,直接在 testcase 中写request 请求,如果是单个请求,也可以直接写成一个 testcase 。
每个 testcase 必须具有两个类属性:config 和 teststeps。

每个测试用例都应该有一个config部分,您可以在其中配置测试用例级别的设置,有以下属性

属性名称是否必填作用
name必填指定测试用例名称。这将显示在执行日志和测试报告中。
base_url可选如果base_url指定,则 teststep 中的 url 可以设置相对路径部分
verify可选https请求时,是否校验证书,默认True,忽略证书校验可以设置为False
variables可选指定测试用例的公共变量。每个测试步骤都可以引用未在步骤变量中设置的配置变量。换句话说,步骤变量比配置变量具有更高的优先级。
export可选(早期版本用的output)指定导出的测试用例会话变量,把变量暴露出来,设置为全局变量

teststeps 可以有多个步骤,每个步骤对应一个接口的请求,也就是 RunRequest (测试步骤)

属性名称是否必填作用
name必填指定测试步骤名称
method(url)必填。如果在Config中设置了baseurl,method中只能设置相对路径,可选参数为get/post/put/delete/等
with_params可选对应于的params参数requests.request
with_headers可选对应于的headers参数requests.request
with_cookies可选cookies参数requests.request
with_data可选cookies参数requests.request
with_cookies可选cookies参数requests.request
with_data可选对应于的data参数requests.request
with_json可选对应于的json参数requests.request
with_variables可选指定测试步骤变量。每个步骤的变量都是独立的,参数引用使用" 变 量 名 " , 如 果 是 函 数 引 用 使 用 " 变量名",如果是函数引用使用" "使"{函数名()}"

extract 数据提取

with_jmespath(jmes_path:文字,var_name:文字)

  • mes_path:jmespath表达式,有关更多详细信息,请参考JMESPath教程https://jmespath.org/tutorial.html
  • var_name:存储提取值的变量名,可以在后续测试步骤中引用它

validate 校验结果

使用jmespath提取 JSON 响应正文并使用预期值进行验证。

assert_XXX(jmes_path: Text, expected_value: Any, message: Text = "")
  • jmes_path:jmespath 表达式,更多细节参考JMESPath 教程
  • 预期值:这里也可以使用指定的预期值、变量或函数引用
  • 消息(可选):用于指示断言错误原因

下图显示了 HttpRunner 内置验证器。

yaml 结构 testcase

yaml 结构 testcase 和之前2.x版本没什么区别,以登录接口为例test_login.yml

# 作者-上海悠悠 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]
        - eq: [content.code, 0]
        - eq: [content.msg, login success!]
        - len_eq: [content.token, 40]

hrun 运行结果

pytest 脚本

hrun 运行后在当前目录会自动生成对应的 pytest 脚本test_login_test.py

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


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


class TestCaseTestLogin(HttpRunner):

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

    teststeps = [
        Step(
            RunRequest("steplogin")
            .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_equal("body.code", 0)
            .assert_equal("body.msg", "login success!")
            .assert_length_equal("body.token", 40)
        ),
    ]


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

命令行使用pytest -s运行结果

D:\demo\hrun3x\testcases>pytest test_login_test.py -s
===================== test session starts ================================
platform win32 -- Python 3.6.6, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: D:\demo\hrun3x\testcases
plugins: allure-pytest-2.8.6, Faker-8.6.0, assume-2.3.3, base-url-1.4.2
collected 1 item                                                                                                                                                                   

test_login_test.py 2021-06-15 20:43:49.328 | INFO     | httprunner.runner:test_start:451 - Start to run testcase: logincase, TestCase ID: ec9695e0-6e05-4bbf-8276-216b4b09a380
2021-06-15 20:43:49.330 | INFO     | httprunner.runner:__run_step:292 - run step begin: steplogin >>>>>>
2021-06-15 20:43:49.476 | DEBUG    | httprunner.client:request:186 - client IP: 192.168.1.125, Port: 20657
2021-06-15 20:43:49.477 | DEBUG    | httprunner.client:request:194 - server IP: 49.235.92.12, Port: 8201
2021-06-15 20:43:49.478 | DEBUG    | httprunner.client:log_print:40 -
================== request details ==================
method   : POST
url      : http://127.0.0.1:8000/api/v1/login
headers  : {
    "User-Agent": "python-requests/2.22.0",
    "Accept-Encoding": "gzip, deflate",
    "Accept": "*/*",
    "Connection": "keep-alive",
    "HRUN-Request-ID": "HRUN-ec9695e0-6e05-4bbf-8276-216b4b09a380-029331",
    "Content-Length": "43",
    "Content-Type": "application/json"
}
cookies  : {}
body     : {
    "username": "test1",
    "password": "123456"
}

2021-06-15 20:43:49.480 | DEBUG    | httprunner.client:log_print:40 -
================== response details ==================
status_code : 200
headers  : {
    "Date": "Tue, 15 Jun 2021 12:43:49 GMT",
    "Server": "WSGIServer/0.2 CPython/3.6.8",
    "Content-Type": "application/json",
    "Vary": "Accept, Cookie",
    "Allow": "POST, OPTIONS",
    "X-Frame-Options": "SAMEORIGIN",
    "Content-Length": "110"
}
cookies  : {}
encoding : None
content_type : application/json
body     : {
    "code": 0,
    "msg": "login success!",
    "username": "test1",
    "token": "99c06543e23d90f26b3d02e2474120fa6dbb7cc3"
}

2021-06-15 20:43:49.483 | INFO     | httprunner.client:request:218 - status_code: 200, response_time(ms): 144.13 ms, response_length: 0 bytes
2021-06-15 20:43:49.484 | INFO     | httprunner.response:extract:176 - extract mapping: {'token': '99c06543e23d90f26b3d02e2474120fa6dbb7cc3'}
2021-06-15 20:43:49.485 | INFO     | httprunner.response:validate:246 - assert status_code equal 200(int)       ==> pass
2021-06-15 20:43:49.486 | INFO     | httprunner.response:validate:246 - assert body.code equal 0(int)   ==> pass
2021-06-15 20:43:49.487 | INFO     | httprunner.response:validate:246 - assert body.msg equal login success!(str)       ==> pass
2021-06-15 20:43:49.488 | INFO     | httprunner.response:validate:246 - assert body.token length_equal 40(int)  ==> pass
2021-06-15 20:43:49.489 | INFO     | httprunner.runner:__run_step:304 - run step end: steplogin <<<<<<

2021-06-15 20:43:49.489 | INFO     | httprunner.runner:test_start:460 - generate testcase log: D:\demo\hrun3x\testcases\logs\ec9695e0-6e05-4bbf-8276-216b4b09a380.run.log
.

============================== 1 passed in 0.96s ===================================

jmespath相关语法可以查看这篇https://www.cnblogs.com/yoyoketang/p/14310898.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值