一、所需環境
- 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個類屬性,分別是config和teststeps,其中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
- 在testcases包下面新建login.yml檔案
- 在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!]
- 在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
- 為什么會有base_uel?因為在我們測驗中,會有多套測驗環境,每套環境中除了服務器的地址不一樣以外,其他都是一樣的,服務器的地址就是我們的base_url,因此需要把服務器地址提取出來單獨管理,這樣以來,測驗環境切換的時候,只需要修改base_url的值,介面中涉及參考到base_url的地方就全改過來了
- 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]
- 在config中寫了base_url后,在teststeps中的url只需要寫介面的路徑地址介面,httprunner會將base_url和url拼接起來作為完整的地址發送出去
- 如果在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: [email protected]
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!]
點擊查看代碼
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: [email protected]
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_hooks和teardown_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 = https://www.cnblogs.com/faith007/p/()
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類,這個類中有兩個屬性,分別是config和teststeps,只是把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-adaptor與allure-pytest不能共存,下載掉即可:pip uninstall pytest-allure-adaptor,接著安裝allure命令列工具:
-
下載allure-commandline安裝包,github官網:https://github.com/allure-framework/allure2/releases/tag/2.17.2
-
解壓下載的檔案,進入到bin目錄,一個是linux啟動檔案,一個是windows啟動檔案

-
將allure所在的bin目錄添加到環境變數,注意只需要到bin目錄即可,添加完成后,在新打開的cmd中輸入
allure --version,可以看到顯示版本表明allure安裝成功
3、生成allure測驗報告
- allure生成測驗報告分成2個步驟,分別是運行用例和生成報告,運行用例有2中方式
hrun testcases --alluredir ./allure_reportpytest 測驗用例檔案 --alluredir ./reports/allure_report,測驗用例檔案可以寫某個具體的檔案,也可以不寫,不寫的話,allure會在當前目錄下自動查找符合pytest用例風格的用例,執行命令后會在allure_report目錄下生成json檔案,json檔案就是報告執行的結果
- 將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
我亦無他,唯手熟爾轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/412930.html
標籤:其他
