HTTPRunner 3 用户手册 (2) 录制用例

在编写测试用例之前,我们应该了解 API 的详细信息。使用 Web 调试代理工具(如Charles,Fiddler)捕获 HTTP 是一个不错的选择。

httprunner 提供一个命令行工具har2case,用于将抓包工具导出的 har 文件转化为 httprunner 格式的用例,并加上了一些简单的断言。

通过这种方式可以实现录制界面操作并生成测试用例。

录制

这是一个简单的示例,你可以访问 postman-echo.com 中的示例请求来尝试这个案例。

1. 抓包

image

2. 导出 har

选择捕获的请求和响应,并 HTTP请求信息.har文件。

image
image

3. Fiddler 保存 har

image
image

4. 通过har2case命令生成用例

获取.har文件后,可以使用内置命令har2case将其转换为 HttpRunner 测试用例。

har2case 命令帮助:

$ har2case -h
usage: har2case har2case [-h] [-2y] [-2j] [--filter FILTER]
                         [--exclude EXCLUDE]
                         [har_source_file]

positional arguments:
  har_source_file       指定 .har 源文件

optional arguments:
  -h, --help            显示此帮助信息并退出
  -2y, --to-yml, --to-yaml
                        转换为 YAML 格式的用例,
                        如果你没有特殊指定,默认转化为 pytest 格式的用例
                        
  -2j, --to-json        转换为 JSON 格式的用例,
                        如果你没有特殊指定,默认转化为 pytest 格式的用例
                        
  --filter FILTER       指定过滤关键字,只有包含过滤字符串的 url 的 API 才会被转换
  
  --exclude EXCLUDE     指定忽略关键字,如果 url 包含该关键字,则会被忽略,
                        如果需要过滤多个关键字,使用`|`(竖线)分隔

生成用例

1. pytest 格式用例

从 HttpRunner 3.0.7 开始,默认情况下har2case会将 HAR 文件转换为 pytest 格式的用例。

强烈建议以pytest 格式而不是以前的 YAML/JSON 格式编写和维护测试用例。

$ har2case har/postman-echo-post-form.har
2020-06-15 15:08:01.187 | INFO     | httprunner.ext.har2case.core:gen_testcase:332 - Start to generate testcase from har/postman-echo-post-form.har
2020-06-15 15:08:01.187 | INFO     | httprunner.ext.har2case.core:_make_testcase:323 - Extract info from HAR file and prepare for testcase.
2020-06-15 15:08:01.191 | INFO     | httprunner.loader:load_dot_env_file:130 - Loading environment variables from /Users/debugtalk/Desktop/demo/.env
2020-06-15 15:08:01.191 | DEBUG    | httprunner.utils:set_os_environ:32 - Set OS environment variable: USERNAME
2020-06-15 15:08:01.191 | DEBUG    | httprunner.utils:set_os_environ:32 - Set OS environment variable: PASSWORD
2020-06-15 15:08:01.193 | INFO     | httprunner.make:make_testcase:310 - start to make testcase: /Users/debugtalk/Desktop/demo/har/postman-echo-post-form.har
2020-06-15 15:08:01.193 | INFO     | httprunner.make:make_testcase:383 - generated testcase: /Users/debugtalk/Desktop/demo/har/postman_echo_post_form_test.py
2020-06-15 15:08:01.194 | INFO     | httprunner.make:format_pytest_with_black:147 - format pytest cases with black ...
reformatted /Users/debugtalk/Desktop/demo/har/postman_echo_post_form_test.py
All done! ✨ 🍰 ✨
1 file reformatted.
2020-06-15 15:08:01.469 | INFO     | httprunner.ext.har2case.core:gen_testcase:353 - generated testcase: /Users/debugtalk/Desktop/demo/har/postman_echo_post_form_test.py

生成的 pytest 文件为如下所示的标准 Python 文件:

# NOTE: Generated By HttpRunner v3.0.12
# FROM: har/postman-echo-post-form.har

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


class TestCasePostmanEchoPostForm(HttpRunner):
    config = Config("testcase description").verify(False)

    teststeps = [
        Step(
            RunRequest("/get")
            .get("https://postman-echo.com/get")
            .with_params(**{"foo1": "bar1", "foo2": "bar2"})
            .with_headers(
                **{
                    "User-Agent": "PostmanRuntime/7.24.1",
                    "Accept": "*/*",
                    "Cache-Control": "no-cache",
                    "Postman-Token": "6606343b-10e5-4165-a89f-6c301b762ce0",
                    "Host": "postman-echo.com",
                    "Accept-Encoding": "gzip, deflate, br",
                    "Connection": "keep-alive",
                    "Cookie": "sails.sid=s%3AQG_EVeNRw8k1xxZ6v_SG401VTpmJDSRu.fTAGx3JnZUT7S0c2%2FrD9cxUhQemIsm78nifYZYHpPCU",
                }
            )
            .with_cookies(
                **{
                    "sails.sid": "s%3AQG_EVeNRw8k1xxZ6v_SG401VTpmJDSRu.fTAGx3JnZUT7S0c2%2FrD9cxUhQemIsm78nifYZYHpPCU"
                }
            )
            .validate()
            .assert_equal("status_code", 200)
            .assert_equal('headers."Content-Type"', "application/json; charset=utf-8")
            .assert_equal(
                "body.url", "https://postman-echo.com/get?foo1=bar1&foo2=bar2"
            )
        ),
        Step(
            RunRequest("/post")
            .post("https://postman-echo.com/post")
            .with_headers(
                **{
                    "User-Agent": "PostmanRuntime/7.24.1",
                    "Accept": "*/*",
                    "Cache-Control": "no-cache",
                    "Postman-Token": "3e408e9d-25ca-4b31-b04b-7f4898a8cd49",
                    "Host": "postman-echo.com",
                    "Accept-Encoding": "gzip, deflate, br",
                    "Connection": "keep-alive",
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Content-Length": "19",
                    "Cookie": "sails.sid=s%3AQG_EVeNRw8k1xxZ6v_SG401VTpmJDSRu.fTAGx3JnZUT7S0c2%2FrD9cxUhQemIsm78nifYZYHpPCU",
                }
            )
            .with_cookies(
                **{
                    "sails.sid": "s%3AQG_EVeNRw8k1xxZ6v_SG401VTpmJDSRu.fTAGx3JnZUT7S0c2%2FrD9cxUhQemIsm78nifYZYHpPCU"
                }
            )
            .with_data({"foo1": "bar1", "foo2": "bar2"})
            .validate()
            .assert_equal("status_code", 200)
            .assert_equal('headers."Content-Type"', "application/json; charset=utf-8")
            .assert_equal("body.data", "")
            .assert_equal("body.url", "https://postman-echo.com/post")
        ),
    ]


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

然后可以使用hrun命令或pytest命令运行。实际上,hrun只是pytest的包装,因此效果基本相同。

$ hrun har/postman_echo_post_form_test.py  
2020-06-15 15:23:03.502 | INFO     | httprunner.loader:load_dot_env_file:130 - Loading environment variables from /Users/debugtalk/Desktop/demo/.env
2020-06-15 15:23:03.502 | DEBUG    | httprunner.utils:set_os_environ:32 - Set OS environment variable: USERNAME
2020-06-15 15:23:03.502 | DEBUG    | httprunner.utils:set_os_environ:32 - Set OS environment variable: PASSWORD
2020-06-15 15:23:03.503 | INFO     | httprunner.make:format_pytest_with_black:147 - format pytest cases with black ...
All done! ✨ 🍰 ✨
1 file left unchanged.
2020-06-15 15:23:03.662 | INFO     | httprunner.cli:main_run:56 - start to run tests with pytest. HttpRunner version: 3.0.12
========================== test session starts ==========================
platform darwin -- Python 3.7.5, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: /Users/debugtalk/Desktop/demo
plugins: metadata-1.9.0, allure-pytest-2.8.16, html-2.1.1
collected 1 item                                                                                                                                                

har/postman_echo_post_form_test.py .                                                                                                                      [100%]

=========================== 1 passed in 2.60s =============================
$ pytest har/postman_echo_post_form_test.py 
=========================== test session starts ===========================
platform darwin -- Python 3.7.5, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: /Users/debugtalk/Desktop/demo
plugins: metadata-1.9.0, allure-pytest-2.8.16, html-2.1.1
collected 1 item                                                                                                                                                

har/postman_echo_post_form_test.py .                                                                                                                      [100%]

============================= 1 passed, 1 warning in 4.11s =============================

2. YAML/JSON 格式用例

当然,也可以生成以前的 YAML/JSON 测试用例格式。只需在har2case中添加-2y/-to-yml-2j/-to-json参数即可。

$ har2case har/postman-echo-post-form.har -2j
2020-06-15 15:32:02.955 | INFO     | httprunner.ext.har2case.core:gen_testcase:332 - Start to generate testcase from har/postman-echo-post-form.har
2020-06-15 15:32:02.955 | INFO     | httprunner.ext.har2case.core:_make_testcase:323 - Extract info from HAR file and prepare for testcase.
2020-06-15 15:32:02.958 | INFO     | httprunner.ext.har2case.utils:dump_json:122 - dump testcase to JSON format.
2020-06-15 15:32:02.959 | INFO     | httprunner.ext.har2case.utils:dump_json:131 - Generate JSON testcase successfully: har/postman-echo-post-form.json
2020-06-15 15:32:02.959 | INFO     | httprunner.ext.har2case.core:gen_testcase:353 - generated testcase: har/postman-echo-post-form.json
{
    "config": {
        "name": "testcase description",
        "variables": {},
        "verify": false
    },
    "teststeps": [
        {
            "name": "/get",
            "request": {
                "url": "https://postman-echo.com/get",
                "params": {
                    "foo1": "bar1",
                    "foo2": "bar2"
                },
                "method": "GET",
                "cookies": {
                    "sails.sid": "s%3AQG_EVeNRw8k1xxZ6v_SG401VTpmJDSRu.fTAGx3JnZUT7S0c2%2FrD9cxUhQemIsm78nifYZYHpPCU"
                },
                "headers": {
                    "User-Agent": "PostmanRuntime/7.24.1",
                    "Accept": "*/*",
                    "Cache-Control": "no-cache",
                    "Postman-Token": "6606343b-10e5-4165-a89f-6c301b762ce0",
                    "Host": "postman-echo.com",
                    "Accept-Encoding": "gzip, deflate, br",
                    "Connection": "keep-alive",
                    "Cookie": "sails.sid=s%3AQG_EVeNRw8k1xxZ6v_SG401VTpmJDSRu.fTAGx3JnZUT7S0c2%2FrD9cxUhQemIsm78nifYZYHpPCU"
                }
            },
            "validate": [
                {
                    "eq": [
                        "status_code",
                        200
                    ]
                },
                {
                    "eq": [
                        "headers.Content-Type",
                        "application/json; charset=utf-8"
                    ]
                },
                {
                    "eq": [
                        "body.url",
                        "https://postman-echo.com/get?foo1=bar1&foo2=bar2"
                    ]
                }
            ]
        },
        {
            "name": "/post",
            "request": {
                "url": "https://postman-echo.com/post",
                "method": "POST",
                "cookies": {
                    "sails.sid": "s%3AQG_EVeNRw8k1xxZ6v_SG401VTpmJDSRu.fTAGx3JnZUT7S0c2%2FrD9cxUhQemIsm78nifYZYHpPCU"
                },
                "headers": {
                    "User-Agent": "PostmanRuntime/7.24.1",
                    "Accept": "*/*",
                    "Cache-Control": "no-cache",
                    "Postman-Token": "3e408e9d-25ca-4b31-b04b-7f4898a8cd49",
                    "Host": "postman-echo.com",
                    "Accept-Encoding": "gzip, deflate, br",
                    "Connection": "keep-alive",
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Content-Length": "19",
                    "Cookie": "sails.sid=s%3AQG_EVeNRw8k1xxZ6v_SG401VTpmJDSRu.fTAGx3JnZUT7S0c2%2FrD9cxUhQemIsm78nifYZYHpPCU"
                },
                "data": {
                    "foo1": "bar1",
                    "foo2": "bar2"
                }
            },
            "validate": [
                {
                    "eq": [
                        "status_code",
                        200
                    ]
                },
                {
                    "eq": [
                        "headers.Content-Type",
                        "application/json; charset=utf-8"
                    ]
                },
                {
                    "eq": [
                        "body.data",
                        ""
                    ]
                },
                {
                    "eq": [
                        "body.url",
                        "https://postman-echo.com/post"
                    ]
                }
            ]
        }
    ]
}

YAML/JSON 测试用例与 pytest 测试用例具有相同的信息,并且可以使用hrun命令运行 YAML/JSON 测试用例。

$ hrun har/postman-echo-post-form.json 
2020-06-15 15:37:15.621 | INFO     | httprunner.loader:load_dot_env_file:130 - Loading environment variables from /Users/debugtalk/Desktop/demo/.env
2020-06-15 15:37:15.622 | DEBUG    | httprunner.utils:set_os_environ:32 - Set OS environment variable: USERNAME
2020-06-15 15:37:15.622 | DEBUG    | httprunner.utils:set_os_environ:32 - Set OS environment variable: PASSWORD
2020-06-15 15:37:15.623 | INFO     | httprunner.make:make_testcase:310 - start to make testcase: /Users/debugtalk/Desktop/demo/har/postman-echo-post-form.json
2020-06-15 15:37:15.625 | INFO     | httprunner.make:make_testcase:383 - generated testcase: /Users/debugtalk/Desktop/demo/har/postman_echo_post_form_test.py
2020-06-15 15:37:15.625 | INFO     | httprunner.make:format_pytest_with_black:147 - format pytest cases with black ...
reformatted /Users/debugtalk/Desktop/demo/har/postman_echo_post_form_test.py
All done! ✨ 🍰 ✨
1 file reformatted, 1 file left unchanged.
2020-06-15 15:37:15.962 | INFO     | httprunner.cli:main_run:56 - start to run tests with pytest. HttpRunner version: 3.0.12
================================= test session starts ===============================
platform darwin -- Python 3.7.5, pytest-5.4.2, py-1.8.1, pluggy-0.13.1
rootdir: /Users/debugtalk/Desktop/demo
plugins: metadata-1.9.0, allure-pytest-2.8.16, html-2.1.1
collected 1 item                                                                                                                                                

har/postman_echo_post_form_test.py .                                                                                                                      [100%]

=============================== 1 passed in 2.03s ===================================
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,723评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,485评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,998评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,323评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,355评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,079评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,389评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,019评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,519评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,971评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,100评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,738评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,293评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,289评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,517评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,547评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,834评论 2 345