3.使用HAR文件生成测试用列(testcase)

什么是HAR文件

HTTP Archive format又称HAR文件,是用来记录浏览器加载网页时所消耗的时间的工具。它可以记录每一个HTTP请求发出直到收到完整的HTTP响应中间所耗费的时间,可以迅速帮助我们知道是哪些HTTP请求没有得到及时的回复,从而进行更一步的排查.

怎么获取HAR文件

  • 使用Google浏览器开发者工具获取
  • 使用抓包工具Charles Proxy导出HAR文件
  • 其他工具导出

1.使用Google浏览器导出HAR

https://postman-echo.com/get?test=123为例,我们使用Google浏览器F12(开发者工具导出HAR)

  1. 使用浏览器打开上面的网址,然后按F12打开浏览器的开发者工具:
    image.png
  2. 点击网络(Network),选择下面的全部(All),就可找到当前的请求信息,如果没法发现,请刷新页面,请求就会出现在列表中
    image.png
  3. 右击目标请求,选择全部另存为HAR
    3.png

2.使用Charles Proxy导出HAR

例如,下面的图片显示了 postman-echo.com 的邮件表单数据。


c1.png

然后我们可以选择捕获的 request & response 并将会话导出到 HTTP 归档(. har)文件。


c2.png

c3.png

使用内建命令 har2case 将其转换为 HttpRunner testcase

使用 har2case -h查看命令用法

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

positional arguments: (关键参数)
  har_source_file       Specify HAR source file(指定HAR源文件,就是我们刚刚导出的HAR文件)

optional arguments:(可选参数)
  -h, --help            show this help message and exit
  -2y, --to-yml, --to-yaml
                        Convert to YAML format, if not specified, convert to
                        pytest format by default.
  -2j, --to-json        Convert to JSON format, if not specified, convert to
                        pytest format by default.
  --filter FILTER       Specify filter keyword, only url include filter string
                        will be converted.
  --exclude EXCLUDE     Specify exclude keyword, url that includes exclude
                        string will be ignored, multiple keywords can be
                        joined with '|'

生成测试用例testcase(pytest)

$ 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

har2case har/postman-echo-post-form.har har/postman-echo-post-form.har 是源文件的绝对路径,windows和linux的稍有不同,请注意**

++====异常情况====++

  • httprunner.exceptions.ParamsError: failed to convert absolute path to relative path based on project_meta.RootDir
$ har2case C:/Users/82419/Desktop/httprunner/yapi-add_cat.har
2021-04-13 14:08:22.843 | INFO     | httprunner.ext.har2case.core:gen_testcase:356 - Start to generate testcase from C:\Users\82419\Desktop\httprunner\yapi-add_cat.har
2021-04-13 14:08:22.846 | INFO     | httprunner.ext.har2case.core:_make_testcase:347 - Extract info from HAR file and prepare for testcase.
2021-04-13 14:08:22.850 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2021-04-13 14:08:22.854 | INFO     | httprunner.loader:load_dot_env_file:127 - Loading environment variables from C:\httprunner\yapi\.env
2021-04-13 14:08:22.856 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: USERNAME
2021-04-13 14:08:22.857 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: PASSWORD
2021-04-13 14:08:22.860 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: C:\Users\82419\Desktop\httprunner\yapi-add_cat.har
  File "c:\programdata\miniconda3\lib\runpy.py", line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\programdata\miniconda3\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\ProgramData\Miniconda3\Scripts\har2case.exe\__main__.py", line 7, in <module>
  File "c:\programdata\miniconda3\lib\site-packages\httprunner\cli.py", line 159, in main_har2case_alias
    main()
  File "c:\programdata\miniconda3\lib\site-packages\httprunner\cli.py", line 121, in main
    main_har2case(args)
  File "c:\programdata\miniconda3\lib\site-packages\httprunner\ext\har2case\__init__.py", line 63, in main_har2case
    HarParser(har_source_file, args.filter, args.exclude).gen_testcase(output_file_type)
  File "c:\programdata\miniconda3\lib\site-packages\httprunner\ext\har2case\core.py", line 374, in gen_testcase
    output_testcase_file = make_testcase(testcase)
  File "c:\programdata\miniconda3\lib\site-packages\httprunner\make.py", line 351, in make_testcase
    testcase_python_abs_path, testcase_cls_name = convert_testcase_path(
  File "c:\programdata\miniconda3\lib\site-packages\httprunner\make.py", line 157, in convert_testcase_path
    testcase_new_path = ensure_file_abs_path_valid(testcase_abs_path)
  File "c:\programdata\miniconda3\lib\site-packages\httprunner\make.py", line 117, in ensure_file_abs_path_valid
    raw_file_relative_name = convert_relative_project_root_dir(raw_abs_file_name)
  File "c:\programdata\miniconda3\lib\site-packages\httprunner\loader.py", line 447, in convert_relative_project_root_dir
    raise exceptions.ParamsError(
httprunner.exceptions.ParamsError: failed to convert absolute path to relative path based on project_meta.RootDir
abs_path: C:\Users\82419\Desktop\httprunner\yapi-add_cat
project_meta.RootDir: C:\httprunner\yapi
Sentry is attempting to send 1 pending error messages
Waiting up to 2 seconds
Press Ctrl-Break to quit

解决方法:

将生成的HAR文件移动到刚刚创建的脚手架项目中的har目录,再次执行命令

生成的 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 =======================================================================

当然,您也可以生成以前的 YAML/JSON testcase 格式,只需将 -2y/-- to-yml 或 -2j/-- to-JSON 参数添加到 har2case 即可。

$ 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 =======================================================================
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容