3.使用HAR文件生成測試用列(testcase)

什么是HAR文件

HTTP Archive format又稱HAR文件叶撒,是用來記錄瀏覽器加載網(wǎng)頁時所消耗的時間的工具。它可以記錄每一個HTTP請求發(fā)出直到收到完整的HTTP響應(yīng)中間所耗費的時間蜜葱,可以迅速幫助我們知道是哪些HTTP請求沒有得到及時的回復(fù),從而進行更一步的排查.

怎么獲取HAR文件

  • 使用Google瀏覽器開發(fā)者工具獲取
  • 使用抓包工具Charles Proxy導(dǎo)出HAR文件
  • 其他工具導(dǎo)出

1.使用Google瀏覽器導(dǎo)出HAR

https://postman-echo.com/get?test=123為例,我們使用Google瀏覽器F12(開發(fā)者工具導(dǎo)出HAR)

  1. 使用瀏覽器打開上面的網(wǎng)址,然后按F12打開瀏覽器的開發(fā)者工具:
    image.png
  2. 點擊網(wǎng)絡(luò)(Network),選擇下面的全部(All),就可找到當前的請求信息,如果沒法發(fā)現(xiàn),請刷新頁面,請求就會出現(xiàn)在列表中
    image.png
  3. 右擊目標請求,選擇全部另存為HAR
    3.png

2.使用Charles Proxy導(dǎo)出HAR

例如耀石,下面的圖片顯示了 postman-echo.com 的郵件表單數(shù)據(jù)牵囤。


c1.png

然后我們可以選擇捕獲的 request & response 并將會話導(dǎo)出到 HTTP 歸檔(. har)文件。


c2.png

c3.png

使用內(nèi)建命令 har2case 將其轉(zhuǎn)換為 HttpRunner testcase

使用 har2case -h查看命令用法

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

positional arguments: (關(guān)鍵參數(shù))
  har_source_file       Specify HAR source file(指定HAR源文件,就是我們剛剛導(dǎo)出的HAR文件)

optional arguments:(可選參數(shù))
  -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文件移動到剛剛創(chuàng)建的腳手架項目中的har目錄,再次執(zhí)行命令

生成的 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 參數(shù)添加到 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 =======================================================================
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市总处,隨后出現(xiàn)的幾起案子狈惫,更是在濱河造成了極大的恐慌,老刑警劉巖鹦马,帶你破解...
    沈念sama閱讀 222,807評論 6 518
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件胧谈,死亡現(xiàn)場離奇詭異,居然都是意外死亡荸频,警方通過查閱死者的電腦和手機菱肖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,284評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來旭从,“玉大人稳强,你說我怎么就攤上這事『驮茫” “怎么了退疫?”我有些...
    開封第一講書人閱讀 169,589評論 0 363
  • 文/不壞的土叔 我叫張陵,是天一觀的道長鸽素。 經(jīng)常有香客問我褒繁,道長,這世上最難降的妖魔是什么馍忽? 我笑而不...
    開封第一講書人閱讀 60,188評論 1 300
  • 正文 為了忘掉前任澜汤,我火速辦了婚禮,結(jié)果婚禮上舵匾,老公的妹妹穿的比我還像新娘俊抵。我一直安慰自己,他們只是感情好坐梯,可當我...
    茶點故事閱讀 69,185評論 6 398
  • 文/花漫 我一把揭開白布徽诲。 她就那樣靜靜地躺著,像睡著了一般吵血。 火紅的嫁衣襯著肌膚如雪谎替。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,785評論 1 314
  • 那天蹋辅,我揣著相機與錄音钱贯,去河邊找鬼。 笑死侦另,一個胖子當著我的面吹牛秩命,可吹牛的內(nèi)容都是我干的尉共。 我是一名探鬼主播,決...
    沈念sama閱讀 41,220評論 3 423
  • 文/蒼蘭香墨 我猛地睜開眼弃锐,長吁一口氣:“原來是場噩夢啊……” “哼袄友!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起霹菊,我...
    開封第一講書人閱讀 40,167評論 0 277
  • 序言:老撾萬榮一對情侶失蹤剧蚣,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后旋廷,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鸠按,經(jīng)...
    沈念sama閱讀 46,698評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,767評論 3 343
  • 正文 我和宋清朗相戀三年饶碘,在試婚紗的時候發(fā)現(xiàn)自己被綠了目尖。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,912評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡熊镣,死狀恐怖卑雁,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情绪囱,我是刑警寧澤测蹲,帶...
    沈念sama閱讀 36,572評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站鬼吵,受9級特大地震影響扣甲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜齿椅,卻給世界環(huán)境...
    茶點故事閱讀 42,254評論 3 336
  • 文/蒙蒙 一琉挖、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧涣脚,春花似錦示辈、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,746評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至芭梯,卻和暖如春险耀,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背玖喘。 一陣腳步聲響...
    開封第一講書人閱讀 33,859評論 1 274
  • 我被黑心中介騙來泰國打工甩牺, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人累奈。 一個月前我還...
    沈念sama閱讀 49,359評論 3 379
  • 正文 我出身青樓贬派,卻偏偏與公主長得像急但,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子赠群,可洞房花燭夜當晚...
    茶點故事閱讀 45,922評論 2 361

推薦閱讀更多精彩內(nèi)容