httprunner3.x全網最詳細教程


一、所需環境

  • wiindows10以上
  • python3.6以上
  • httprunner3.1.6(最新版本)
  • pycharm社區版

二、安裝httprunner

1、卸載舊版本

卸載之前版本的命令為:pip3 uninstall httprunner

2、安裝新版本

默認安裝方式

pip3 install httprunner

以這種方式是默認安裝最新版本的,並且是從國外服務器下載,但是偶爾會出現報錯或者超時的情況,因此一般采用國內鏡像安裝,這里采用國內豆瓣源鏡像安裝。
一般安裝命令:

pip3 install httprunner==3.1.6 -i https://pypi.douban.com/simple

此種方式是指定安裝版本和安裝源
安裝完成后如下顯示,表示安裝成功

點擊查看代碼
C:\Users\fsy>pip3 install httprunner==3.1.6 -i https://pypi.douban.com/simple
Looking in indexes: https://pypi.douban.com/simple
Collecting httprunner==3.1.6
  Downloading https://pypi.doubanio.com/packages/e4/2f/25011310f2f13f55de18845435f62b0ae16fbb69500885c268705ef42ee2/httprunner-3.1.6-py3-none-any.whl (60 kB)
     |████████████████████████████████| 60 kB 549 kB/s
Collecting requests<3.0.0,>=2.22.0
  Downloading https://pypi.doubanio.com/packages/2d/61/08076519c80041bc0ffa1a8af0cbd3bf3e2b62af10435d269a9d0f40564d/requests-2.27.1-py2.py3-none-any.whl (63 kB)
     |████████████████████████████████| 63 kB 584 kB/s
Collecting jmespath<0.10.0,>=0.9.5
  Downloading https://pypi.doubanio.com/packages/a3/43/1e939e1fcd87b827fe192d0c9fc25b48c5b3368902bfb913de7754b0dc03/jmespath-0.9.5-py2.py3-none-any.whl (24 kB)
Collecting pytest<6.0.0,>=5.4.2
  Downloading https://pypi.doubanio.com/packages/9f/f3/0a83558da436a081344aa6c8b85ea5b5f05071214106036ce341b7769b0b/pytest-5.4.3-py3-none-any.whl (248 kB)
     |████████████████████████████████| 248 kB 819 kB/s
Collecting sentry-sdk<0.15.0,>=0.14.4
  Downloading https://pypi.doubanio.com/packages/1b/95/9a20eebcedab2c1c63fad59fe19a0469edfc2a25b8576497e8084629c2ff/sentry_sdk-0.14.4-py2.py3-none-any.whl (104 kB)
     |████████████████████████████████| 104 kB 1.3 MB/s
Collecting black<20.0,>=19.10b0
  Downloading https://pypi.doubanio.com/packages/fd/bb/ad34bbc93d1bea3de086d7c59e528d4a503ac8fe318bd1fa48605584c3d2/black-19.10b0-py36-none-any.whl (97 kB)
     |████████████████████████████████| 97 kB 951 kB/s
Collecting pytest-html<3.0.0,>=2.1.1
  Downloading https://pypi.doubanio.com/packages/00/a7/34f195c514d39b4453619b3eb284989e5adb09a2a68ac09ce3779f9b9478/pytest_html-2.1.1-py2.py3-none-any.whl (16 kB)
Collecting pyyaml<6.0.0,>=5.1.2
  Downloading https://pypi.doubanio.com/packages/97/d3/24097209f6af04fcdbb40500480a0feaa62164e60bca4c9532f0e9354e47/PyYAML-5.4.1-cp38-cp38-win_amd64.whl (213 kB)
     |████████████████████████████████| 213 kB 3.3 MB/s
Collecting loguru<0.5.0,>=0.4.1
  Downloading https://pypi.doubanio.com/packages/b2/f4/2c8b94025c6e30bdb331c7ee628dc152771845aedff35f0365c2a4dacd42/loguru-0.4.1-py3-none-any.whl (54 kB)
     |████████████████████████████████| 54 kB 331 kB/s
Collecting jinja2<3.0.0,>=2.10.3
  Downloading https://pypi.doubanio.com/packages/7e/c2/1eece8c95ddbc9b1aeb64f5783a9e07a286de42191b7204d67b7496ddf35/Jinja2-2.11.3-py2.py3-none-any.whl (125 kB)
     |████████████████████████████████| 125 kB 819 kB/s
Collecting pydantic<2.0,>=1.4
  Downloading https://pypi.doubanio.com/packages/5f/ca/ec4b2597b7ace79a05300a2e7eff8713b55745312b2acc89f74bf73f8dfc/pydantic-1.9.0-cp38-cp38-win_amd64.whl (2.1 MB)
     |████████████████████████████████| 2.1 MB 1.3 MB/s
Collecting Brotli<2.0.0,>=1.0.9
  Downloading https://pypi.doubanio.com/packages/63/29/1b104b5915e61d9f7443889657d93937b7e0b33b331609b82693547934a0/Brotli-1.0.9-cp38-cp38-win_amd64.whl (365 kB)
     |████████████████████████████████| 365 kB 6.8 MB/s
Collecting attrs>=18.1.0
  Downloading https://pypi.doubanio.com/packages/be/be/7abce643bfdf8ca01c48afa2ddf8308c2308b0c3b239a44e57d020afa0ef/attrs-21.4.0-py2.py3-none-any.whl (60 kB)
     |████████████████████████████████| 60 kB 952 kB/s
Collecting typed-ast>=1.4.0
  Downloading https://pypi.doubanio.com/packages/93/6a/1b01a1864854fd6ed63e0e0649a9c1e4ef1425e417c43e7b09c0e4e7fdac/typed_ast-1.5.1-cp38-cp38-win_amd64.whl (164 kB)
     |████████████████████████████████| 164 kB 819 kB/s
Collecting click>=6.5
  Downloading https://pypi.doubanio.com/packages/48/58/c8aa6a8e62cc75f39fee1092c45d6b6ba684122697d7ce7d53f64f98a129/click-8.0.3-py3-none-any.whl (97 kB)
     |████████████████████████████████| 97 kB 3.2 MB/s
Collecting appdirs
  Downloading https://pypi.doubanio.com/packages/3b/00/2344469e2084fb287c2e0b57b72910309874c3245463acd6cf5e3db69324/appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB)
Collecting regex
  Downloading https://pypi.doubanio.com/packages/e2/b1/b1d30513d3638e1e48cdfa5857a0e9c92ec7d19c0641836d0b49c4d00cac/regex-2021.11.10-cp38-cp38-win_amd64.whl (273 kB)
     |████████████████████████████████| 273 kB 731 kB/s
Collecting toml>=0.9.4
  Downloading https://pypi.doubanio.com/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl (16 kB)
Collecting pathspec<1,>=0.6
  Downloading https://pypi.doubanio.com/packages/42/ba/a9d64c7bcbc7e3e8e5f93a52721b377e994c22d16196e2b0f1236774353a/pathspec-0.9.0-py2.py3-none-any.whl (31 kB)
Collecting colorama
  Downloading https://pypi.doubanio.com/packages/44/98/5b86278fbbf250d239ae0ecb724f8572af1c91f4a11edf4d36a206189440/colorama-0.4.4-py2.py3-none-any.whl (16 kB)
Collecting MarkupSafe>=0.23
  Downloading https://pypi.doubanio.com/packages/30/9e/4b7116f464a0151b86ce42b5185941eb74c207b38fe033f71f5e5d150356/MarkupSafe-2.0.1-cp38-cp38-win_amd64.whl (14 kB)
Collecting win32-setctime>=1.0.0
  Downloading https://pypi.doubanio.com/packages/37/6a/a498698d31626f32eae2c3bd1f1c303c6b3d54589b2993e9e05a4cd513dd/win32_setctime-1.0.4-py3-none-any.whl (3.5 kB)
Collecting typing-extensions>=3.7.4.3
  Downloading https://pypi.doubanio.com/packages/05/e4/baf0031e39cf545f0c9edd5b1a2ea12609b7fcba2d58e118b11753d68cf0/typing_extensions-4.0.1-py3-none-any.whl (22 kB)
Collecting wcwidth
  Downloading https://pypi.doubanio.com/packages/59/7c/e39aca596badaf1b78e8f547c807b04dae603a433d3e7a7e04d67f2ef3e5/wcwidth-0.2.5-py2.py3-none-any.whl (30 kB)
Collecting pluggy<1.0,>=0.12
  Downloading https://pypi.doubanio.com/packages/a0/28/85c7aa31b80d150b772fbe4a229487bc6644da9ccb7e427dd8cc60cb8a62/pluggy-0.13.1-py2.py3-none-any.whl (18 kB)
Collecting atomicwrites>=1.0
  Downloading https://pypi.doubanio.com/packages/2c/a0/da5f49008ec6e9a658dbf5d7310a4debd397bce0b4db03cf8a410066bb87/atomicwrites-1.4.0-py2.py3-none-any.whl (6.8 kB)
Collecting packaging
  Downloading https://pypi.doubanio.com/packages/05/8e/8de486cbd03baba4deef4142bd643a3e7bbe954a784dc1bb17142572d127/packaging-21.3-py3-none-any.whl (40 kB)
     |████████████████████████████████| 40 kB 2.7 MB/s
Collecting more-itertools>=4.0.0
  Downloading https://pypi.doubanio.com/packages/e5/c3/48e2c81038f57e8caab9a6e6fb6c2fc23536c59b092abefc447e6b5d1903/more_itertools-8.12.0-py3-none-any.whl (54 kB)
     |████████████████████████████████| 54 kB 1.9 MB/s
Collecting py>=1.5.0
  Downloading https://pypi.doubanio.com/packages/f6/f0/10642828a8dfb741e5f3fbaac830550a518a775c7fff6f04a007259b0548/py-1.11.0-py2.py3-none-any.whl (98 kB)
     |████████████████████████████████| 98 kB 2.6 MB/s
Collecting pytest-metadata
  Using cached https://pypi.doubanio.com/packages/e5/12/bfb677aad996cc994efb9c61289a4994d60079587e85155738859fd3b68e/pytest_metadata-1.11.0-py2.py3-none-any.whl (10 kB)
Collecting idna<4,>=2.5
  Downloading https://pypi.doubanio.com/packages/04/a2/d918dcd22354d8958fe113e1a3630137e0fc8b44859ade3063982eacd2a4/idna-3.3-py3-none-any.whl (61 kB)
     |████████████████████████████████| 61 kB 2.0 MB/s
Collecting urllib3<1.27,>=1.21.1
  Downloading https://pypi.doubanio.com/packages/4e/b8/f5a25b22e803f0578e668daa33ba3701bb37858ec80e08a150bd7d2cf1b1/urllib3-1.26.8-py2.py3-none-any.whl (138 kB)
     |████████████████████████████████| 138 kB 6.8 MB/s
Collecting charset-normalizer~=2.0.0
  Downloading https://pypi.doubanio.com/packages/84/3e/1037abe6498e65d645ce7a22d3402605d49a3b2c7f20c3abb027760da4f0/charset_normalizer-2.0.10-py3-none-any.whl (39 kB)
Collecting certifi>=2017.4.17
  Downloading https://pypi.doubanio.com/packages/37/45/946c02767aabb873146011e665728b680884cd8fe70dde973c640e45b775/certifi-2021.10.8-py2.py3-none-any.whl (149 kB)
     |████████████████████████████████| 149 kB 3.2 MB/s
Collecting pyparsing!=3.0.5,>=2.0.2
  Downloading https://pypi.doubanio.com/packages/a0/34/895006117f6fce0b4de045c87e154ee4a20c68ec0a4c9a36d900888fb6bc/pyparsing-3.0.6-py3-none-any.whl (97 kB)
     |████████████████████████████████| 97 kB 1.7 MB/s
Installing collected packages: pyparsing, wcwidth, py, pluggy, packaging, more-itertools, colorama, attrs, atomicwrites, pytest, win32-setctime, urllib3, typing-extensions, typed-ast, toml, regex, pytest-metadata, pathspec, MarkupSafe, idna, click, charset-normalizer, certifi, appdirs, sentry-sdk, requests, pyyaml, pytest-html, pydantic, loguru, jmespath, jinja2, Brotli, black, httprunner
Successfully installed Brotli-1.0.9 MarkupSafe-2.0.1 appdirs-1.4.4 atomicwrites-1.4.0 attrs-21.4.0 black-19.10b0 certifi-2021.10.8 charset-normalizer-2.0.10 click-8.0.3 colorama-0.4.4 httprunner-3.1.6 idna-3.3 jinja2-2.11.3 jmespath-0.9.5 loguru-0.4.1 more-itertools-8.12.0 packaging-21.3 pathspec-0.9.0 pluggy-0.13.1 py-1.11.0 pydantic-1.9.0 pyparsing-3.0.6 pytest-5.4.3 pytest-html-2.1.1 pytest-metadata-1.11.0 pyyaml-5.4.1 regex-2021.11.10 requests-2.27.1 sentry-sdk-0.14.4 toml-0.10.2 typed-ast-1.5.1 typing-extensions-4.0.1 urllib3-1.26.8 wcwidth-0.2.5 win32-setctime-1.0.4

3、查看版本號

hrun命令查看安裝的httprunner版本號,或者用命令httprunner,效果是一樣的

C:\Users\fsy>hrun -V
3.1.6
C:\Users\fsy>httprunner -V
3.1.6

至此,httprunner已經安裝成功,安裝成功后,httprunner會自動生成幾個重要的命令,通過-h查看命令

C:\Users\fsy>httprunner -h
usage: httprunner [-h] [-V] {run,startproject,har2case,make} ...

One-stop solution for HTTP(S) testing.

positional arguments:
  {run,startproject,har2case,make}
                        sub-command help
    run                 Make HttpRunner testcases and run with pytest.
    startproject        Create a new project with template structure.
    har2case            Convert HAR(HTTP Archive) to YAML/JSON testcases for HttpRunner.
    make                Convert YAML/JSON testcases to pytest cases.

optional arguments:
  -h, --help            show this help message and exit
  -V, --version         show version

可以看到生成了4個命令,分別是

  • run:運行測試用例的命令
  • startproject:創建測試模板項目的命令
  • har2case:將fiddler或者charles導出的文件轉化成py文件的命令
  • make:將yaml文件的測試用例或者json文件的測試用例轉化成pytest測試用例

三、創建項目

1、用命令startproject創建一個模板項目,進入到對應的目錄下面,執行命令

D:\httprunnerStudy>httprunner startproject httprunner_demo
2022-01-09 13:25:30.189 | INFO     | httprunner.scaffold:create_scaffold:43 - Create new project: httprunner_demo
Project Root Dir: D:\httprunnerStudy\httprunner_demo

created folder: httprunner_demo
created folder: httprunner_demo\har
created folder: httprunner_demo\testcases
created folder: httprunner_demo\reports
created file: httprunner_demo\testcases\demo_testcase_request.yml
created file: httprunner_demo\testcases\demo_testcase_ref.yml
created file: httprunner_demo\debugtalk.py
created file: httprunner_demo\.env
created file: httprunner_demo\.gitignore

$ tree httprunner_demo -a
2022-01-09 13:25:30.205 | WARNING  | httprunner.scaffold:show_tree:29 - tree command not exists, ignore.
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-Break to quit

從日志信息可以看到已經成功創建了一個項目,通過pycahrm打開創建的項目,看到項目結構如下

其中包含兩個yml文件,這兩個yml文件是官方給的示例,實際使用的時候可以刪除掉,執行其中一個yml測試用例

 D:\httprunnerStudy> hrun D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_ref.yml
2022-01-09 13:31:48.546 | INFO     | httprunner.make:__make:512 - make path: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_ref.yml
2022-01-09 13:31:48.556 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2022-01-09 13:31:48.561 | INFO     | httprunner.loader:load_dot_env_file:127 - Loading environment variables from D:\httprunnerStudy\httprunner_demo\.env
2022-01-09 13:31:48.566 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: USERNAME
2022-01-09 13:31:48.566 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: PASSWORD
2022-01-09 13:31:48.566 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_ref.yml
2022-01-09 13:31:48.586 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2022-01-09 13:31:48.586 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_request.yml
2022-01-09 13:31:48.586 | INFO     | httprunner.make:make_testcase:442 - generated testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_request_test.py
2022-01-09 13:31:48.596 | INFO     | httprunner.make:make_testcase:442 - generated testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcas2022-01-09 13:31:48.596 | INFO     | httprunner.make:format_pytest_with_black:170 - format pytest cases with black ...
reformatted D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_ref_test.py
reformatted D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_request_test.py
All done! ✨ 🍰 ✨
2 files reformatted.
2022-01-09 13:31:50.116 | INFO     | httprunner.cli:main_run:56 - start to run tests with pytest. HttpRunner version: 3.1.6
================================================================ test session starts ================================================================ 
platform win32 -- Python 3.8.10, pytest-5.4.3, py-1.11.0, pluggy-0.13.1
rootdir: D:\httprunnerStudy
plugins: html-2.1.1, metadata-1.11.0
collected 1 item

httprunner_demo\testcases\demo_testcase_ref_test.py .                                                                                          [100%]

================================================================= 1 passed in 2.46s ================================================================= 

從日志最后可以看到該用例執行成功,如果想要2個用例一起執行,則執行命令hrun run testcases,如下看到已經執行成功

D:\httprunnerStudy\httprunner_demo> httprunner run testcases
2022-01-09 13:36:28.756 | INFO     | httprunner.make:__make:512 - make path: D:\httprunnerStudy\httprunner_demo\testcases
2022-01-09 13:36:28.772 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2022-01-09 13:36:28.772 | INFO     | httprunner.loader:load_dot_env_file:127 - Loading environment variables from D:\httprunnerStudy\httprunner_demo\.env
2022-01-09 13:36:28.772 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: USERNAME
2022-01-09 13:36:28.772 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: PASSWORD
2022-01-09 13:36:28.772 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_ref.yml
2022-01-09 13:36:28.788 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2022-01-09 13:36:28.788 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_request.yml
2022-01-09 13:36:28.788 | INFO     | httprunner.make:make_testcase:442 - generated testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_request_test.py
2022-01-09 13:36:28.803 | INFO     | httprunner.make:make_testcase:442 - generated testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_ref_test.py
2022-01-09 13:36:28.803 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2022-01-09 13:36:28.803 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_request.yml
2022-01-09 13:36:28.819 | INFO     | httprunner.make:format_pytest_with_black:170 - format pytest cases with black ...
reformatted D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_ref_test.py
reformatted D:\httprunnerStudy\httprunner_demo\testcases\demo_testcase_request_test.py
All done! ✨ 🍰 ✨
2 files reformatted.
2022-01-09 13:36:30.000 | INFO     | httprunner.cli:main_run:56 - start to run tests with pytest. HttpRunner version: 3.1.6
================================================================ test session starts ================================================================
platform win32 -- Python 3.8.10, pytest-5.4.3, py-1.11.0, pluggy-0.13.1
rootdir: D:\httprunnerStudy\httprunner_demo
plugins: html-2.1.1, metadata-1.11.0
collected 2 items                                                                                                                                    

testcases\demo_testcase_request_test.py .                                                                                                      [ 50%]
testcases\demo_testcase_ref_test.py .                                                                                                          [100%]

================================================================= 2 passed in 4.00s ================================================================= 

這里我這里的項目根目錄,和上面有所不同,如果目錄和上面一樣,需要在testcases目錄前面加上httprunnerStudy,否則執行的時候找不到測試用例

四、測試用例

在httprunner項目結構中,測試用例直接寫在testcases包下面,無論是單個請求,還是多個有依賴的請求,都寫在這個包下面的yml文件中,一個yml文件代表一條測試用例

1、測試用例的屬性

在yml文件中,也就是我們的測試用例,必須具有2個類屬性,分別是configteststeps,其中config包含以下屬性

屬性名稱 是否必填 作用
name 必填 指定測試用例名稱,測試用例名稱將顯示在執行日志和測試報告中
base_url 選填 如果base_url指定,則teststep中的url可以設置成相對路徑
verify 選填 https請求時是否檢驗證書,默認為true,如果設置成False,則表示忽略證書
variables 選填 指定測試用例的公共變量,每個測試步驟都可以引用該變量
export 選填 導出的測試用例會話變量,把變量暴露出來,設置成全局變量

teststeps中包含以下屬性

屬性名稱 是否必填 作用
name 必填 指定測試步驟名稱
request 必填 發送請求的參數,參數引用變量“$變量名”
variables 選填 指定測試步驟變量,參數引用變量“$變量名”
extract 選填 提取返回結果
export 選填 導出測試用例變量,設置成全局變量
validate 選填 校驗返回結果

2、實際應用

以登錄接口為例:登錄地址:http://49.235.92.12:8201/api/v1/login,用戶名:test,密碼123456

  1. 在testcases包下面新建login.yml文件
  2. 在yml文件中填寫以下信息
config:
  name: 登錄用例
teststeps:
  - name: 登錄
    request:
      url: http://49.235.92.12:8201/api/v1/login
      method: POST  # POST必須大寫,這是約定
      json:
        username: test
        password: "123456"  # 123456如果不加引號,則表示的是int類型,但是實際需要的是str類型
    validate:
      - eq: [status_code,200]
      - eq: [body.msg,login success!]
  1. 在pycharm的terminal控制台中執行命令:hrun testcases/login.yml,看到控制台信息:
 D:\httprunnerStudy\httprunner_demo> hrun testcases/login.yml
2022-01-09 16:16:58.932 | INFO     | httprunner.make:__make:512 - make path: D:\httprunnerStudy\httprunner_demo\testcases\login.yml
2022-01-09 16:16:58.937 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2022-01-09 16:16:58.939 | INFO     | httprunner.loader:load_dot_env_file:127 - Loading environment variables from D:\httprunnerStudy\httprunner_demo\.env
2022-01-09 16:16:58.941 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: USERNAME
2022-01-09 16:16:58.942 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: PASSWORD
2022-01-09 16:16:58.945 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: D:\httprunnerStudy\httprunner_demo\testcases\login.yml
2022-01-09 16:16:58.948 | INFO     | httprunner.make:make_testcase:442 - generated testcase: D:\httprunnerStudy\httprunner_demo\testcases\login_test.p
================================================================= 1 passed in 0.52s ================================================================= 

上面日志表示該接口執行成功

3、request請求

request請求在python中最常用的就是post方式和get方式,在post請求中,如果請求頭是Content-Type:application/json格式的話,post請求參數傳json,如果請求頭是application/x-www-from-urlencoded,post請求參數傳data,詳細參考request請求庫

4、base_url

  1. 為什么會有base_uel?因為在我們測試中,會有多套測試環境,每套環境中除了服務器的地址不一樣以外,其他都是一樣的,服務器的地址就是我們的base_url,因此需要把服務器地址提取出來單獨管理,這樣以來,測試環境切換的時候,只需要修改base_url的值,接口中涉及引用到base_url的地方就全改過來了
  2. base_url寫在yml文件中的哪里呢?實際上在yml文件中,base_url應該寫在config屬性下面,和name屬於同一級,例如:
config:
  name: 獲取商品
  base_url: http://49.235.92.12:8201
teststeps:
  - name: goods
    request:
      url: /api/v1/goods
      method: GET
      params:
        page: 1
        size: 2
    validate:
      - eq: [status_code,200]
      - eq: [body.code,0]
  1. 在config中寫了base_url后,在teststeps中的url只需要寫接口的路徑地址接口,httprunner會將base_url和url拼接起來作為完整的地址發送出去
  2. 如果在base_url配置后,在測試步驟中的url寫接口的絕對路徑,是否會報錯了?答案是否定的,因為httprunner在請求的時候,會遵從就近原則取url的地址,如果測試步驟中的地址是正確的地址,httprunner就會直接請求

5、變量的聲明與應用

在yml文件中的兩個屬性中都有變量variables,其中在config中的變量對整個yml文件都有效,而teststeps中的變量只對當前step有效,可以理解為一個是全局變量,一個是局部變量,優先級是局部變量大於全局變量

6、validate校驗

在httprunner的validate中,列表內部實際上能傳3個參數, 第一個參數是jmespath表達式,也就是實際結果,第二個參數是期望結果,第三個參數是message,表示斷言的錯誤原因,其中第一個參數和第二個參數是必傳的,第三個參數可以不傳

httprunner發送請求后,會返回四個對象,分別是:

  • status_code:狀態碼
  • headers:頭部信息
  • cookies:cookie信息
  • body:返回的body內容
    如果要校驗返回頭部的信息,則可以用headers.xxx等獲取,如果要校驗返回響應體的內容,則用body.xxx,如body.msg

7、參數關聯

什么是參數關聯?上一個接口返回的參數在下一個接口中需要用到,這就是參數關聯,而且該參數是動態變化的。參數關聯涉及兩個點,一是提取變量,用extract,而是引用變量,引用變量和其他引用方式一樣,$變量名。

點擊查看代碼
config:
  name: 登錄用例
  base_url: http://49.235.92.12:8201
  variables:
    user: test
teststeps:
  - name: 登錄
    request:
      url: /api/v1/login
      method: POST  # POST必須大寫
      json:
        username: $user
        password: "123456"  # 123456如果不加引號,則表示的是int類型,但是實際需要的是str類型
    extract:
      token: body.token
    validate:
      - eq: [status_code,200]
      - eq: [body.msg,login success!]
  - name: 獲取用戶信息
    request:
      url: /api/v1/userinfo
      method: POST
      headers:
        Authorization: Token $token
      json:
        name: $user
        sex: M
        age: 18
        mail: 592485@qq.com
    validate:
    - eq: [status_code,200]
    - eq: [body.code,0]

上述代碼關聯是在一個yml文件中,而一個yml文件對應一個用例,如果需要在不同的yml文件中關聯怎么處理呢?只需要將關聯的值導出來即可,在config屬性下面添加export,並設置導出后的變量

具體做法:有2個yml文件,一個是login.yml,另一個是userinfo.yml,很顯然后一個文件需要依賴登錄返回的token,需要在login.yml文件的config中寫上上圖信息,在userinfo.yml文件中的teststeps中有2個測試步驟,第一個測試步驟是登錄,而登錄在另一個文件中,所以需要在第一步中引用login.yml,一個yml文件引用另一個yml文件用到關鍵字testcase,然后第二步才是userinfo
login.yml代碼:

點擊查看代碼
config:
  name: 登錄用例
  base_url: http://49.235.92.12:8201
  variables:
    user: test
  export:
    - token
teststeps:
  - name: 登錄
    request:
      url: /api/v1/login
      method: POST  # POST必須大寫
      json:
        username: $user
        password: "123456"  # 123456如果不加引號,則表示的是int類型,但是實際需要的是str類型
    extract:
      token: body.token
    validate:
      - eq: [status_code,200]
      - eq: [body.msg,login success!]
userinfo.yml代碼:
點擊查看代碼
config:
  name: 獲取商品
  base_url: http://49.235.92.12:8201
teststeps:
  - name: 步驟1:登錄
    testcase: testcases/login.yml
  - name: 獲取用戶信息
    request:
      url: /api/v1/userinfo
      method: POST
      headers:
        Authorization: Token $token
      json:
        name: test
        sex: M
        age: 18
        mail: 592485@qq.com
    validate:
    - eq: [status_code,200]
    - eq: [body.code,0]

8、環境變量

在項目的根目錄中,有一個.env文件,該文件就是存放項目的環境變量,在該文件中變量的存放形式是k=v,一般存放的賬號,密碼,環境地址等等

那么如何環境變量呢?在yml文件中引用環境變量${ENV(變量名)}即可

9、參數化

在httprunner3版本中,實現參數化是在config中,參數化實現的方式有3中
方式一: (適用數據量比較少的情況)
在config屬性下面添加關鍵字parameters實現參數化,然后指定user變量,具體變量寫在[]

這是單個變量參數化的,如果多個參數參數化了,比如賬號密碼都要參數化,該怎么做呢?實際上多個參數化也是用parameters關鍵字。變量名用-鏈接起來,參數的所有組合方式展示在列表中即可,一行代表一種情況

parameters:
  user-password:
    - [test1,"123456"]
    - [test2,"123456"]
    - [test3,"123456"]
    - [test4,"123456"]

還可以用如下形式表示,笛卡爾積形式

parameters:
  user: [test1,test2,test3,test4]
  password: ["13578","246810","123456","456789"]

方式二:(適用數據量大的情況)
引用CSV文件進行參數化,在項目根目錄下新建目錄data,在data目錄下新建一個csv文件,在csv文件里存放需要的參數化數據,csv文件的參數化數據用逗號分隔,csv第一行寫參數名稱

那么csv文件如何引用呢,只需要在paramaters關鍵字下面用P函數寫上csv文件路徑即可,路徑一定是從項目的根目錄查找

parameters:
  user-password:${P(data/para.csv)}

方式三:(適用比較靈活的參數)
該種方式是在項目根目錄下的debugtalk.py文件中寫python函數來實現的,單個參數的實現:

def get_user():
    return ["test1", "test2", "test3", "test4"]

如何引用呢?只需要在parameters關鍵字下面的user后面寫上${get_user()}即可
多個參數的情況,python腳本為:

def get_user_pwd(m):
    account = []
    for i in range(1, m):
        account.append({"user": "test%s" % i, "pwd": 123456})
    return account

引用形式為:

parameters:
  user-password:${get_user_pwd(9)}

在debugtalk.py中參數化多於2個的時候返回值需要用字典的形式,變量名作為key,變量值作為value

10、hook機制

hook機制就是執行用例的前置步驟和后置步驟,在pytest中一般用setup和teardown來表示,在httprunner中,需要把前置函數和后置函數寫在debugtalk.py中,然后在測試步驟teststeps中用關鍵字setup_hooksteardown_hooks來引用

11、文件上傳

文件上傳在httprunner中使用的是關鍵字upload來實現,upload下面有幾個參數根據實際情況來處理,這里只有2個,代碼如下:

config:
  name: 文件上傳
  base_url: http://49.235.92.12:8201
teststeps:
  - name: 上傳文件
    request:
      url: /api/v1/upfile/
      method: POST
      upload:
        file: data/QQ20220109214618.png
        title: faith

但是我在運行的時候報錯

根據提示執行命令:pip3 install requests_toolbelt filetype,之后再次運行該用例,執行成功

五、數據庫鏈接

1、數據庫鏈接

鏈接數據庫需要驅動,首先得安裝驅動,在cmd命令行中執行命令:pip3 install PyMySQL,默認安裝最新的

C:\Users\fsy>pip3 install PyMySQL
Collecting PyMySQL
  Downloading PyMySQL-1.0.2-py3-none-any.whl (43 kB)
     |████████████████████████████████| 43 kB 28 kB/s
Installing collected packages: PyMySQL
Successfully installed PyMySQL-1.0.2

安裝成功后,在項目根目錄下新建目錄utils,新建一個python文件,用於鏈接數據庫操作

import pymysql

class MysqlHelper:
    # 初始化數據庫信息
    def __init__(self, host, username, password, db, charset='utf8', port=3306):
        self.host = host
        self.username = username
        self.password = password
        self.db = db
        self.charset = charset
        self.port = port

    # 數據庫連接
    def connect(self):
        self.conn = pymysql.connect(host=self.host, port=self.port, user=self.username, password=self.password,
                                    db=self.db, charset=self.charset, cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    # 查詢單條數據
    def get_one(self, sql, params=()):
        result = None
        try:
            self.connect()
            self.cursor.execute(sql, params)
            result = self.cursor.fetchone()
            self.close()
        except Exception as e:
            print(e)
        return result

    # 查詢多條數據
    def get_all(self, sql, params=()):
        list_data = ()
        try:
            self.connect()
            self.cursor.execute(sql, params)
            list_data = self.cursor.fetchall()
            self.close()
        except Exception as e:
            print(e)
        return list_data

    def execute(self, sql, params=()):
        # SQL刪除、提交、修改語句
        try:
            self.cursor.execute(sql, params)  # 執行SQL語句
            self.db.commit()  # 提交修改
        except Exception as e:
            # 發生錯誤時回滾
            print(e)
            self.db.rollback()

    # 關閉連接
    def close(self):
        self.cursor.close()
        self.conn.close()

2、數據庫校驗結果

在debugtalk.py文件中寫入函數調用數據庫查詢,查詢出來數據后,取出要校驗的字段,然后返回出去,最后在校驗字段的時候引用改函數來判斷

六、jmespath

jmespath是用來提取json表達式的值,官網地址:https://jmespath.org/tutorial.html
分為以下幾種情況

  • 最簡單的json格式,如`{"a": "foo", "b": "bar", "c": "baz"},這種方式取值直接輸入key值即可

  • json嵌套形式的取值,如{"a": {"b": {"c": {"d": "value"}}}},這種方式取值按照python字典取值的方式即可

  • 列表取值,如["a", "b", "c", "d", "e", "f"],按照python列表的取值方式即可

  • 字典和列表相互嵌套的時候取值,就是將字典取值和列表取值結合起來

  • 切片取值和python里面的切片取值一樣的

  • *取值

  • 按條件取值

  • |管道符過濾取值

七、編寫pytest用例

1、為什么要寫pytest用例

因為httprunner底層用的就是pytest,所以httprunner支持pytest編寫的用例,編寫pytest用例需要滿足以下條件:

  • 文件名必須以test_.py文件或者_test.py文件
  • 測試用例函數必須以test_開頭
  • 類是以Test開頭的,不能帶有__init__方法
  • 所有的包必須有__init__.py文件

2、pytest用例的屬性

一個pytest用例就是一個python類,這個類中有兩個屬性,分別是configteststeps,只是把yml文件中的用例轉換成立python語言而已,主要是teststeps中的一些方法
RunRequest測試步驟:RunRequest一般用在發送請求的時候,里面包含函數信息,請求方法,請求頭,請求數據,斷言信息等,具體如下

屬性名稱 是否必填 作用
name 必填 指定測試步驟名稱
method(url) 必填 如果在config中設置了base_url,那method中只能設置相對路徑
with_params 選填 對應params參數,一般用get方法的時候使用
with_headers 選填 對應headers參數
with_cookies 選填 cookies參數
with_data 選填 對應於data參數
with_json 選填 對應json參數
with_variables 選填 測試步驟中的變量,每個步驟的變量獨立,變量引用形式:$變量名,如果是函數引用則為:${函數名()}
with_jmespath 選填 提取變量值,保存后給下個接口使用,和extract結合使用,先有extract,再有with_jmespath
validate 選填 校驗結果,和assert函數結合使用,先有validate,再有assert函數

RunTestCase:RunTestCase一般用作一個測試用例需要依賴另一個用例的時候,RunTestCase有以下參數

參數 作用
name 指定測試步驟名稱,該名稱將顯示在執行日志和測試報告中
with_variables 定義變量
call 引用的測試用例類,需要提前導入這個類
export 從引用的測試用例導出的會話變量名稱,導出的變量方便后續測試步驟引用

八、測試報告

1、pytest自帶測試報告

由於httprunner底層用的是pytest測試框架,而pytest測試框架自帶測試報告,因此httprunner也可以執行pytest的測試報告,執行命令:pytest testcases --html=./reports/result.html --self-contained-html

2、allure插件安裝

allure測試報告是一個java開發的插件,需要java環境,首先按照allure-pytest插件

點擊查看代碼
C:\Users\siyong.fan>pip install allure-pytest -i https://pypi.douban.com/simple
Looking in indexes: https://pypi.douban.com/simple
Requirement already satisfied: allure-pytest in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (2.9.43)
Requirement already satisfied: six>=1.9.0 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from allure-pytest) (1.16.0)
Requirement already satisfied: allure-python-commons==2.9.43 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from allure-pytest) (2.9.43)
Requirement already satisfied: pytest>=4.5.0 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from allure-pytest) (5.4.3)
Requirement already satisfied: pluggy>=0.4.0 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from allure-python-commons==2.9.43->allure-pytest) (0.13.1)
Requirement already satisfied: attrs>=16.0.0 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from allure-python-commons==2.9.43->allure-pytest) (21.2.0)
Requirement already satisfied: colorama in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from pytest>=4.5.0->allure-pytest) (0.4.4)
Requirement already satisfied: py>=1.5.0 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from pytest>=4.5.0->allure-pytest) (1.10.0)
Requirement already satisfied: more-itertools>=4.0.0 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from pytest>=4.5.0->allure-pytest) (8.12.0)
Requirement already satisfied: packaging in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from pytest>=4.5.0->allure-pytest) (21.0)
Requirement already satisfied: atomicwrites>=1.0 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from pytest>=4.5.0->allure-pytest) (1.4.0)
Requirement already satisfied: wcwidth in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from pytest>=4.5.0->allure-pytest) (0.2.5)
Requirement already satisfied: pyparsing>=2.0.2 in c:\users\siyong.fan\appdata\local\programs\python\python38\lib\site-packages (from packaging->pytest>=4.5.0->allure-pytest) (2.4.7)

這里已經安裝成功
運行用例時,如果報錯,是因為pytest-allure-adaptorallure-pytest不能共存,下載掉即可:pip uninstall pytest-allure-adaptor,接着安裝allure命令行工具:

  1. 下載allure-commandline安裝包,github官網:https://github.com/allure-framework/allure2/releases/tag/2.17.2

  2. 解壓下載的文件,進入到bin目錄,一個是linux啟動文件,一個是windows啟動文件

  3. 將allure所在的bin目錄添加到環境變量,注意只需要到bin目錄即可,添加完成后,在新打開的cmd中輸入allure --version,可以看到顯示版本表明allure安裝成功

3、生成allure測試報告

  1. allure生成測試報告分成2個步驟,分別是運行用例和生成報告,運行用例有2中方式
  • hrun testcases --alluredir ./allure_report
  • pytest 測試用例文件 --alluredir ./reports/allure_report,測試用例文件可以寫某個具體的文件,也可以不寫,不寫的話,allure會在當前目錄下自動查找符合pytest用例風格的用例,執行命令后會在allure_report目錄下生成json文件,json文件就是報告執行的結果
  1. 將json文件轉換成html報告
    在命令行執行:allure serve ./reports/allure_report生成html報告

八、持續集成

1、在linux服務器上安裝python3.9版本,先安裝相關依賴

yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel mysql-devel

2、下載linux需要的python包,下載地址:https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz

3、在linux中新建一個目錄存放下載的python安裝包,使用命令:mkdir python39,進入到python39目錄,用wget命令下載3.9.0的python包

點擊查看代碼
[edenapp@eden-dev-test ~]$ cd python39/
[edenapp@eden-dev-test python39]$ wget https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz
--2022-01-10 17:03:28--  https://www.python.org/ftp/python/3.9.0/Python-3.9.0.tgz
Resolving www.python.org (www.python.org)... 151.101.72.223, 2a04:4e42:11::223
Connecting to www.python.org (www.python.org)|151.101.72.223|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 26724009 (25M) [application/octet-stream]
Saving to: ‘Python-3.9.0.tgz’

100%[=========================================================================================================================================================================>] 26,724,009  13.2MB/s   in 1.9s

2022-01-10 17:03:31 (13.2 MB/s) - ‘Python-3.9.0.tgz’ saved [26724009/26724009]

4、解壓下載的python包

解壓命令:tar -xvf Python-3.9.0.tgz

5、指定安裝目錄

執行命令:./configure --prefix=/usr/local/python39,如果執行命令報錯:configure: error: no acceptable C compiler found in $PATH,則先執行sudo yum install gcc-c++,再執行上條命令就可以安裝成功了

6、編譯

在當前目錄輸入sudo make,執行完成后再執行sudo make install

7、添加軟連接,查看安裝的版本,軟連接的目錄一定要是之前指定的目錄

[edenapp@eden-dev-test bin]$ sudo ln -s  /usr/local/python39/bin/python3.9 /usr/bin/python3
 [edenapp@eden-dev-test bin]$ python3
Python 3.9.0 (default, Jan 10 2022, 17:26:42)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux
Type "help", "copyright", "credits" or "license" for more information.

8、給pip添加軟連接,查看是否成功

[edenapp@eden-dev-test bin]$ sudo ln -s  /usr/local/python39/bin/pip3 /usr/bin/pip3
 [edenapp@eden-dev-test bin]$ pip3 -V
 pip 20.2.3 from /usr/local/python39/lib/python3.9/site-packages/pip (python 3.9)

9、安裝httprunner

使用命令pip3 install httprunner安裝,安裝完成后,使用httprunner -V查看安裝的版本,但是會出現如下信息,這是因為命令沒有加環境變量或者軟連接

為了解決問題,這里添加軟連接,先查找httprunner命令,查找命令find / -name httprunner

[root@localhost Python-3.9.0]# find / -name httprunner
/usr/local/python39/bin/httprunner
/usr/local/python39/lib/python3.9/site-packages/httprunner
[root@localhost Python-3.9.0]# 

找到bin目錄下的httprunner,給他添加軟連接

[root@localhost Python-3.9.0]# ln -s /usr/local/python39/bin/httprunner /usr/bin/httprunner
[root@localhost Python-3.9.0]# httprunner -V
3.1.6
[root@localhost Python-3.9.0]# 

可以看到添加成功並可以正確使用,同樣的方法給pytest添加軟連接

10、執行測試用例

將在windows中寫的測試代碼打包,然后通過rz命令上傳到linux服務器的指定目錄下,然后在解壓,解壓后進入到項目的根目錄下,查看需要安裝的依賴庫,把所需要的的依賴庫全部安裝完成,然后在根目錄下輸入pytest執行用例

11、集成到jenkins

jenkins安裝直接使用docker安裝,方便快捷,安裝完成后創建一個自由風格的項目,指定項目的根目錄

輸入shell的命令pytest

最后一步就是jenkins生成allure測試報告,打開 jenkins 首頁-系統管理-管理插件-可選插件

插件安裝完成后,在配置里面找到allure的插件

回到全局工具配置頁面,找到Allure Commandline安裝

最后在構建頁面按照如下信息輸入

12、發送郵件

發送郵件需要插件,參考博客:https://www.cnblogs.com/yoyoketang/p/12174056.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM