httprunner(4)錄製生成測試用例

Silent丿丶黑羽發表於2021-02-05

前言

寫用例之前,我們應該熟悉API的詳細資訊。建議使用抓包工具Charles或AnyProxy進行抓包。
 

har2case

我們先來了解一下另一個專案har2case
他的工作原理就是將當前主流的抓包工具和瀏覽器都支援將抓取得到的資料包匯出為標準通用的 HAR 格式(HTTP Archive),然後 HttpRunner 將 HAR 格式的資料包轉換為YAML/JSON格式的測試用例檔案。
這裡使用charles抓取百度首頁進行演示
 

選中百度請求,右鍵點選Export Session,匯出到/hrun_demo/har下,命名為baidu,格式選擇HTTP Archive(.har),點選save

此時,har資料夾下會多出baidu.har檔案
 

har2case生成用例

可以使用命令har2case將Har檔案轉成測試用例,先使用命令har2case -h檢視幫助文件

(httprunner_env) ➜  har har2case -h       
usage: har2case har2case [-h] [-2y] [-2j] [--filter FILTER]
                         [--exclude EXCLUDE]
                         [har_source_file]

positional arguments:
  har_source_file       Specify HAR source file

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 '|'
  • -2y:轉換為yaml格式,如果沒有指定,預設轉換為pytest格式
  • -2j:轉換為json格式,如果沒有指定,預設轉換為pytest格式
  • --filter:指定篩選關鍵字,僅url包含篩選字串將被轉換。
  • --exclude:指定exclude關鍵字,包括exclude的url字串將被忽略,可以選擇多個關鍵字以“|”聯接
     

生成pytest格式的用例

HttpRunner 3.0.7版本開始,har2case將HAR檔案預設轉換成pytest,強烈建議pytest格式而不是以前的YAML / JSON格式編寫和維護測試用例。
這裡也是博主從pytest框架轉換為httprunner框架的原因之一
執行命令將har檔案轉換成測試用例:

(httprunner_env) ➜  har har2case baidu.har
2021-02-05 11:27:32.945 | INFO     | httprunner.ext.har2case.core:gen_testcase:356 - Start to generate testcase from /Users/jkc/hrun/hrun_demo/har/baidu.har
2021-02-05 11:27:32.945 | INFO     | httprunner.ext.har2case.core:_make_testcase:347 - Extract info from HAR file and prepare for testcase.
2021-02-05 11:27:32.948 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2021-02-05 11:27:32.948 | INFO     | httprunner.loader:load_dot_env_file:127 - Loading environment variables from /Users/jkc/hrun/hrun_demo/.env
2021-02-05 11:27:32.949 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: USERNAME
2021-02-05 11:27:32.949 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: PASSWORD
2021-02-05 11:27:32.950 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: /Users/jkc/hrun/hrun_demo/har/baidu.har
2021-02-05 11:27:32.951 | INFO     | httprunner.make:make_testcase:442 - generated testcase: /Users/jkc/hrun/hrun_demo/har/baidu_test.py
2021-02-05 11:27:32.952 | INFO     | httprunner.make:format_pytest_with_black:170 - format pytest cases with black ...
reformatted /Users/songyingkai/hrun/hrun_demo/har/baidu_test.py
All done! ✨ ? ✨
1 file reformatted.
2021-02-05 11:27:33.181 | INFO     | httprunner.ext.har2case.core:gen_testcase:377 - generated testcase: /Users/jkc/hrun/hrun_demo/har/baidu_test.py
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-C to quit

生成的pytest檔案是標準的python檔案,如下所示:

# NOTE: Generated By HttpRunner v3.1.4
# FROM: har/baidu.har


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


class TestCaseBaidu(HttpRunner):

    config = Config("testcase description").verify(False)

    teststeps = [
        Step(
            RunRequest("/")
            .get("https://www.baidu.com/")
            .with_headers(
                **{
                    "Host": "www.baidu.com",
                    "Connection": "keep-alive",
                    "Cache-Control": "max-age=0",
                    "sec-ch-ua": '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
                    "sec-ch-ua-mobile": "?0",
                    "Upgrade-Insecure-Requests": "1",
                    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36",
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                    "Sec-Fetch-Site": "none",
                    "Sec-Fetch-Mode": "navigate",
                    "Sec-Fetch-User": "?1",
                    "Sec-Fetch-Dest": "document",
                    "Accept-Encoding": "gzip, deflate, br",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Cookie": "PSTM=1610459846; BAIDUID=A40AD6AD806FBBED1033903732FFA453:FG=1; BD_UPN=123253; BIDUPSID=898B917A8EF92E036B0F06DC792638A1; __yjs_duid=1_c391922164c20246fd49e4ad821d46c41610613507042; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=33423_33513_33403_33273_33594_33585_26350_33568; delPer=0; BD_CK_SAM=1; PSINO=5; BAIDUID_BFESS=A40AD6AD806FBBED1033903732FFA453:FG=1; COOKIE_SESSION=86630_1_9_6_41_5_0_0_8_2_1_0_0_0_71_0_1612340974_1611912344_1612427533%7C9%23262013_235_1611912339%7C9; BD_HOME=1; ZD_ENTRY=baidu; BA_HECTOR=20ag2180aga18k21mm1g1pegu0r",
                }
            )
            .with_cookies(
                **{
                    "PSTM": "1610459846",
                    "BAIDUID": "A40AD6AD806FBBED1033903732FFA453:FG=1",
                    "BD_UPN": "123253",
                    "BIDUPSID": "898B917A8EF92E036B0F06DC792638A1",
                    "__yjs_duid": "1_c391922164c20246fd49e4ad821d46c41610613507042",
                    "BDORZ": "B490B5EBF6F3CD402E515D22BCDA1598",
                    "H_PS_PSSID": "33423_33513_33403_33273_33594_33585_26350_33568",
                    "delPer": "0",
                    "BD_CK_SAM": "1",
                    "PSINO": "5",
                    "BAIDUID_BFESS": "A40AD6AD806FBBED1033903732FFA453:FG=1",
                    "COOKIE_SESSION": "86630_1_9_6_41_5_0_0_8_2_1_0_0_0_71_0_1612340974_1611912344_1612427533%7C9%23262013_235_1611912339%7C9",
                    "BD_HOME": "1",
                    "ZD_ENTRY": "baidu",
                    "BA_HECTOR": "20ag2180aga18k21mm1g1pegu0r",
                }
            )
            .validate()
            .assert_equal("status_code", 200)
            .assert_equal('headers."Content-Type"', "text/html;charset=utf-8")
        ),
    ]


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

可以使用命令hrunpytest執行,實際上,hrun是pytest的封裝,效果基本相同。

(httprunner_env) ➜  har hrun baidu_test.py 
2021-02-05 14:03:39.279 | INFO     | httprunner.make:__make:512 - make path: /Users/jkc/hrun/hrun_demo/har/baidu_test.py
2021-02-05 14:03:39.279 | INFO     | httprunner.make:format_pytest_with_black:170 - format pytest cases with black ...
No Path provided. Nothing to do ?
2021-02-05 14:03:39.457 | INFO     | httprunner.cli:main_run:56 - start to run tests with pytest. HttpRunner version: 3.1.4
============================================= test session starts =============================================
platform darwin -- Python 3.7.6, pytest-5.4.3, py-1.10.0, pluggy-0.13.1
rootdir: /Users/songyingkai/hrun/hrun_demo/har
plugins: metadata-1.11.0, html-2.1.1
collected 1 item                                                                                              

baidu_test.py .                                                                                         [100%]

============================================== 1 passed in 0.25s ==============================================
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-C to quit
(httprunner_env) ➜  har pytest baidu_test.py 
============================================= test session starts =============================================
platform darwin -- Python 3.7.6, pytest-5.4.3, py-1.10.0, pluggy-0.13.1
rootdir: /Users/songyingkai/hrun/hrun_demo/har
plugins: metadata-1.11.0, html-2.1.1
collected 1 item                                                                                              

baidu_test.py .                                                                                         [100%]

============================================== warnings summary ===============================================
baidu_test.py::TestCaseBaidu::test_start
  /Users/songyingkai/.virtualenvs/httprunner_env/lib/python3.7/site-packages/urllib3/connectionpool.py:1020: InsecureRequestWarning: Unverified HTTPS request is being made to host 'www.baidu.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
    InsecureRequestWarning,

-- Docs: https://docs.pytest.org/en/latest/warnings.html
======================================== 1 passed, 1 warning in 0.47s =========================================

 

生成測試用例(YAML/JSON)

當然,你也可以生成YAML/JSON測試用例。 只需要在har2case命令後 新增-2y/--to-yml-2j/--to-json
 

生成YAML格式:

har har2case baidu.har -2y
(httprunner_env) ➜  har har2case baidu.har -2y
2021-02-05 14:23:48.484 | INFO     | httprunner.ext.har2case.core:gen_testcase:356 - Start to generate testcase from /Users/jkc/hrun/hrun_demo/har/baidu.har
2021-02-05 14:23:48.484 | INFO     | httprunner.ext.har2case.core:_make_testcase:347 - Extract info from HAR file and prepare for testcase.
2021-02-05 14:23:48.488 | INFO     | httprunner.ext.har2case.utils:dump_yaml:108 - dump testcase to YAML format.
2021-02-05 14:23:48.492 | INFO     | httprunner.ext.har2case.utils:dump_yaml:115 - Generate YAML testcase successfully: /Users/jkc/hrun/hrun_demo/har/baidu.yml
2021-02-05 14:23:48.493 | INFO     | httprunner.ext.har2case.core:gen_testcase:377 - generated testcase: /Users/jkc/hrun/hrun_demo/har/baidu.yml
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-C to quit

檢視生成的yaml檔案

config:
    name: testcase description
    variables: {}
    verify: false
teststeps:
-   name: /
    request:
        cookies:
            BAIDUID: A40AD6AD806FBBED1033903732FFA453:FG=1
            BAIDUID_BFESS: A40AD6AD806FBBED1033903732FFA453:FG=1
            BA_HECTOR: 20ag2180aga18k21mm1g1pegu0r
            BDORZ: B490B5EBF6F3CD402E515D22BCDA1598
            BD_CK_SAM: '1'
            BD_HOME: '1'
            BD_UPN: '123253'
            BIDUPSID: 898B917A8EF92E036B0F06DC792638A1
            COOKIE_SESSION: 86630_1_9_6_41_5_0_0_8_2_1_0_0_0_71_0_1612340974_1611912344_1612427533%7C9%23262013_235_1611912339%7C9
            H_PS_PSSID: '33423_33513_33403_33273_33594_33585_26350_33568'
            PSINO: '5'
            PSTM: '1610459846'
            ZD_ENTRY: baidu
            __yjs_duid: 1_c391922164c20246fd49e4ad821d46c41610613507042
            delPer: '0'
        headers:
            Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
            Accept-Encoding: gzip, deflate, br
            Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7
            Cache-Control: max-age=0
            Connection: keep-alive
            Cookie: PSTM=1610459846; BAIDUID=A40AD6AD806FBBED1033903732FFA453:FG=1;
                BD_UPN=123253; BIDUPSID=898B917A8EF92E036B0F06DC792638A1; __yjs_duid=1_c391922164c20246fd49e4ad821d46c41610613507042;
                BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=33423_33513_33403_33273_33594_33585_26350_33568;
                delPer=0; BD_CK_SAM=1; PSINO=5; BAIDUID_BFESS=A40AD6AD806FBBED1033903732FFA453:FG=1;
                COOKIE_SESSION=86630_1_9_6_41_5_0_0_8_2_1_0_0_0_71_0_1612340974_1611912344_1612427533%7C9%23262013_235_1611912339%7C9;
                BD_HOME=1; ZD_ENTRY=baidu; BA_HECTOR=20ag2180aga18k21mm1g1pegu0r
            Host: www.baidu.com
            Sec-Fetch-Dest: document
            Sec-Fetch-Mode: navigate
            Sec-Fetch-Site: none
            Sec-Fetch-User: ?1
            Upgrade-Insecure-Requests: '1'
            User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36
                (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36
            sec-ch-ua: '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"'
            sec-ch-ua-mobile: ?0
        method: GET
        url: https://www.baidu.com/
    validate:
    -   eq:
        - status_code
        - 200
    -   eq:
        - headers.Content-Type
        - text/html;charset=utf-8

 

生成JSON格式:

har2case baidu.har -2j
(httprunner_env) ➜  har har2case baidu.har -2j
2021-02-05 14:25:35.729 | INFO     | httprunner.ext.har2case.core:gen_testcase:356 - Start to generate testcase from /Users/jkc/hrun/hrun_demo/har/baidu.har
2021-02-05 14:25:35.730 | INFO     | httprunner.ext.har2case.core:_make_testcase:347 - Extract info from HAR file and prepare for testcase.
2021-02-05 14:25:35.732 | INFO     | httprunner.ext.har2case.utils:dump_json:121 - dump testcase to JSON format.
2021-02-05 14:25:35.733 | INFO     | httprunner.ext.har2case.utils:dump_json:130 - Generate JSON testcase successfully: /Users/jkc/hrun/hrun_demo/har/baidu.json
2021-02-05 14:25:35.733 | INFO     | httprunner.ext.har2case.core:gen_testcase:377 - generated testcase: /Users/jkc/hrun/hrun_demo/har/baidu.json
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-C to quit

檢視生成的json格式

{
    "config": {
        "name": "testcase description",
        "variables": {},
        "verify": false
    },
    "teststeps": [
        {
            "name": "/",
            "request": {
                "url": "https://www.baidu.com/",
                "method": "GET",
                "cookies": {
                    "PSTM": "1610459846",
                    "BAIDUID": "A40AD6AD806FBBED1033903732FFA453:FG=1",
                    "BD_UPN": "123253",
                    "BIDUPSID": "898B917A8EF92E036B0F06DC792638A1",
                    "__yjs_duid": "1_c391922164c20246fd49e4ad821d46c41610613507042",
                    "BDORZ": "B490B5EBF6F3CD402E515D22BCDA1598",
                    "H_PS_PSSID": "33423_33513_33403_33273_33594_33585_26350_33568",
                    "delPer": "0",
                    "BD_CK_SAM": "1",
                    "PSINO": "5",
                    "BAIDUID_BFESS": "A40AD6AD806FBBED1033903732FFA453:FG=1",
                    "COOKIE_SESSION": "86630_1_9_6_41_5_0_0_8_2_1_0_0_0_71_0_1612340974_1611912344_1612427533%7C9%23262013_235_1611912339%7C9",
                    "BD_HOME": "1",
                    "ZD_ENTRY": "baidu",
                    "BA_HECTOR": "20ag2180aga18k21mm1g1pegu0r"
                },
                "headers": {
                    "Host": "www.baidu.com",
                    "Connection": "keep-alive",
                    "Cache-Control": "max-age=0",
                    "sec-ch-ua": "\"Chromium\";v=\"88\", \"Google Chrome\";v=\"88\", \";Not A Brand\";v=\"99\"",
                    "sec-ch-ua-mobile": "?0",
                    "Upgrade-Insecure-Requests": "1",
                    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.146 Safari/537.36",
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                    "Sec-Fetch-Site": "none",
                    "Sec-Fetch-Mode": "navigate",
                    "Sec-Fetch-User": "?1",
                    "Sec-Fetch-Dest": "document",
                    "Accept-Encoding": "gzip, deflate, br",
                    "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
                    "Cookie": "PSTM=1610459846; BAIDUID=A40AD6AD806FBBED1033903732FFA453:FG=1; BD_UPN=123253; BIDUPSID=898B917A8EF92E036B0F06DC792638A1; __yjs_duid=1_c391922164c20246fd49e4ad821d46c41610613507042; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; H_PS_PSSID=33423_33513_33403_33273_33594_33585_26350_33568; delPer=0; BD_CK_SAM=1; PSINO=5; BAIDUID_BFESS=A40AD6AD806FBBED1033903732FFA453:FG=1; COOKIE_SESSION=86630_1_9_6_41_5_0_0_8_2_1_0_0_0_71_0_1612340974_1611912344_1612427533%7C9%23262013_235_1611912339%7C9; BD_HOME=1; ZD_ENTRY=baidu; BA_HECTOR=20ag2180aga18k21mm1g1pegu0r"
                }
            },
            "validate": [
                {
                    "eq": [
                        "status_code",
                        200
                    ]
                },
                {
                    "eq": [
                        "headers.Content-Type",
                        "text/html;charset=utf-8"
                    ]
                }
            ]
        }
    ]
}

YAML/JSON用例和pytest用例檔案含有相同的資訊,也可以使用hrun執行。

(httprunner_env) ➜  har hrun baidu.yml    
2021-02-05 14:28:05.573 | INFO     | httprunner.make:__make:512 - make path: /Users/jkc/hrun/hrun_demo/har/baidu.yml
2021-02-05 14:28:05.582 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2021-02-05 14:28:05.582 | INFO     | httprunner.loader:load_dot_env_file:127 - Loading environment variables from /Users/jkc/hrun/hrun_demo/.env
2021-02-05 14:28:05.582 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: USERNAME
2021-02-05 14:28:05.582 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: PASSWORD
2021-02-05 14:28:05.583 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: /Users/jkc/hrun/hrun_demo/har/baidu.yml
2021-02-05 14:28:05.583 | INFO     | httprunner.make:make_testcase:442 - generated testcase: /Users/jkc/hrun/hrun_demo/har/baidu_test.py
2021-02-05 14:28:05.584 | INFO     | httprunner.make:format_pytest_with_black:170 - format pytest cases with black ...
reformatted /Users/songyingkai/hrun/hrun_demo/har/baidu_test.py
All done! ✨ ? ✨
1 file reformatted.
2021-02-05 14:28:05.769 | INFO     | httprunner.cli:main_run:56 - start to run tests with pytest. HttpRunner version: 3.1.4
============================================= test session starts =============================================
platform darwin -- Python 3.7.6, pytest-5.4.3, py-1.10.0, pluggy-0.13.1
rootdir: /Users/songyingkai/hrun/hrun_demo/har
plugins: metadata-1.11.0, html-2.1.1
collected 1 item                                                                                              

baidu_test.py .                                                                                         [100%]

============================================== 1 passed in 0.26s ==============================================
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-C to quit
(httprunner_env) ➜  har hrun baidu.json 
2021-02-05 14:28:25.793 | INFO     | httprunner.make:__make:512 - make path: /Users/jkc/hrun/hrun_demo/har/baidu.json
2021-02-05 14:28:25.794 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2021-02-05 14:28:25.794 | INFO     | httprunner.loader:load_dot_env_file:127 - Loading environment variables from /Users/jkc/hrun/hrun_demo/.env
2021-02-05 14:28:25.794 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: USERNAME
2021-02-05 14:28:25.794 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: PASSWORD
2021-02-05 14:28:25.795 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: /Users/jkc/hrun/hrun_demo/har/baidu.json
2021-02-05 14:28:25.795 | INFO     | httprunner.make:make_testcase:442 - generated testcase: /Users/jkc/hrun/hrun_demo/har/baidu_test.py
2021-02-05 14:28:25.795 | INFO     | httprunner.make:format_pytest_with_black:170 - format pytest cases with black ...
reformatted /Users/songyingkai/hrun/hrun_demo/har/baidu_test.py
All done! ✨ ? ✨
1 file reformatted.
2021-02-05 14:28:25.975 | INFO     | httprunner.cli:main_run:56 - start to run tests with pytest. HttpRunner version: 3.1.4
============================================= test session starts =============================================
platform darwin -- Python 3.7.6, pytest-5.4.3, py-1.10.0, pluggy-0.13.1
rootdir: /Users/songyingkai/hrun/hrun_demo/har
plugins: metadata-1.11.0, html-2.1.1
collected 1 item                                                                                              

baidu_test.py .                                                                                         [100%]

============================================== 1 passed in 0.31s ==============================================
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-C to quit

相關文章