欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpRunner3.X开源接口测试框架学习(二)

程序员文章站 2024-03-21 23:14:34
...

HttpRunner3.X开源接口测试框架学习(二)

debugtalk.py

每个项目应该并且只能有一个debugtalk.py文件。该文件具有多种功能。

  • 作为项目的根路径锚,测试用例中的相对路径(例如引用测试用例或CSV文件)都基于此根路径

  • 存储自定义python函数,在测试用例中调用的函数均在此文件中定义

HttpRunner框架中的变量

全局变量

全局变量在.env文件中定义,编写测试用例脚本时使用中${ENV(KEY)} 获取变量

pytest格式

HttpRunner3.X开源接口测试框架学习(二)

 

用例级变量

在使用pytest格式编写测试用例时,variables用来定义变量,请注意如果全局环境变量与测试用例脚本中存在相同变量名,则优先使用用例级变量。即:测试用例变量>导出变量>测试套件配置变量>引用的测试用例配置变量

HttpRunner3.X开源接口测试框架学习(二)

 

创建HttpRunner项目

httprunner框架提供了自动生成手脚架项目的功能,可以快速创建新项目。

#使用httprunner命令创建项目
 httprunner startproject demo    创建名为demo的httprunner项目
#自动生成的文件目录如下:       
created folder: demo/har                    #har接口录制导出文件,用于生成测试脚本
created folder: demo/reports                #测试报告存放目录                   
created folder: demo/testcases              #测试用例存放目录
created file: demo/testcases/demo_testcase_request.yml   #测试用例模板示例
created file: demo/testcases/demo_testcase_ref.yml       #测试用例模板示例
created file: demo/debugtalk.py             #debugtalk.py文件  #用于编写自定义函数
created file: demo/.env                     #全局环境变量定义文件
created file: demo/.gitignore           
  

示例创建baidutest项目:

C:\github>httprunner startproject baidutest
2020-08-11 14:32:19.860 | INFO     | httprunner.scaffold:create_scaffold:43 - Create new project: baidutest
Project Root Dir: C:\github\baidutest
​
created folder: baidutest
created folder: baidutest\har
created folder: baidutest\testcases
c:\programs\python\python38\lib\site-packages\urllib3\request.py:171: InvalidProxyConfigurationWarning: Your proxy configuration specified an HTTPS scheme for the proxy. Are you sure you want to use HTTPS to contact the proxy? This most likely indicates an error in your configuration. Read this issue for more info: https://github.com/urllib3/urllib3/issues/1850
  return self.urlopen(method, url, **extra_kw)
created folder: baidutest\reports
created file: baidutest\testcases\demo_testcase_request.yml
created file: baidutest\testcases\demo_testcase_ref.yml
created file: baidutest\debugtalk.py
created file: baidutest\.env
created file: baidutest\.gitignore
​
$ tree baidutest -a
2020-08-11 14:32:19.921 | 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

编写httprunner框架接口测试用例

httprunner提供了自动生成测试脚本的功能,利用har2case xxx.har命令可以将抓包工具导出的har文件转换为pytest格式测试用例(默认格式),也可以转换成yaml、json格式。

使用抓包工具录制业务:

如图使用charles工具录制导出har文件

HttpRunner3.X开源接口测试框架学习(二)

har2case命令详解:

$ 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 '|'

执行har2case doctest.har 命令后会在当前文件夹生成doctest_test.py测试用例文件

C:\github\baidutest\har>har2case doctest.har
2020-08-11 14:51:57.340c:\programs\python\python38\lib\site-packages\urllib3\request.py:171: InvalidProxyConfigurationWarning: Your proxy configuration specified an HTTPS scheme for the proxy. Are you sure you want to use HTTPS to contact the proxy? This most likely indicates an error in your configuration. Read this issue for more info: https://github.com/urllib3/urllib3/issues/1850
  return self.urlopen(method, url, **extra_kw)
 | INFO     | httprunner.ext.har2case.core:gen_testcase:356 - Start to generate testcase from C:\github\baidutest\har\doctest.har
2020-08-11 14:51:57.354 | INFO     | httprunner.ext.har2case.core:_make_testcase:347 - Extract info from HAR file and prepare for testcase.
2020-08-11 14:51:57.358 | INFO     | httprunner.compat:ensure_testcase_v3:219 - ensure compatibility with testcase format v2
2020-08-11 14:51:57.438 | INFO     | httprunner.loader:load_dot_env_file:127 - Loading environment variables from C:\github\baidutest\.env
2020-08-11 14:51:57.456 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: USERNAME
2020-08-11 14:51:57.462 | DEBUG    | httprunner.utils:set_os_environ:33 - Set OS environment variable: PASSWORD
2020-08-11 14:51:57.471 | INFO     | httprunner.make:make_testcase:349 - start to make testcase: C:\github\baidutest\har\doctest.har
2020-08-11 14:51:57.480 | INFO     | httprunner.make:make_testcase:442 - generated testcase: C:\github\baidutest\har\doctest_test.py
2020-08-11 14:51:57.484 | INFO     | httprunner.make:format_pytest_with_black:170 - format pytest cases with black ...
reformatted C:\github\baidutest\har\doctest_test.py
All done! ✨ ???? ✨
1 file reformatted.
2020-08-11 14:51:58.705 | INFO     | httprunner.ext.har2case.core:gen_testcase:377 - generated testcase: C:\github\baidutest\har\doctest_test.py

HttpRunner3.X开源接口测试框架学习(二)

doctest_test用例文件:

# NOTE: Generated By HttpRunner v3.1.4
# FROM: har\doctest.har
​
​
from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase
​
​
class TestCaseDoctest(HttpRunner):
​
    config = Config("testcase description").verify(False)
​
    teststeps = [
        Step(
            RunRequest("/controller/login/login.html")
            .get("http://www.doclever.cn/controller/login/login.html")
            .with_headers(
                **{
                    "Host": "www.doclever.cn",
                    "Upgrade-Insecure-Requests": "1",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
                    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
                    "Referer": "http://www.doclever.cn/controller/index/index.html",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                    "Cookie": "pgv_pvid=7266193040",
                    "Connection": "keep-alive",
                }
            )
            .with_cookies(**{"pgv_pvid": "7266193040"})
            .validate()
            .assert_equal("status_code", 200)
            .assert_equal('headers."Content-Type"', "text/html")
        ),
        Step(
            RunRequest("/user/login")
            .post("http://www.doclever.cn:8090/user/login")
            .with_headers(
                **{
                    "Host": "www.doclever.cn:8090",
                    "Content-Length": "28",
                    "Accept": "application/json, text/plain, */*",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
                    "content-type": "application/x-www-form-urlencoded",
                    "Origin": "http://www.doclever.cn",
                    "Referer": "http://www.doclever.cn/controller/login/login.html",
                    "Accept-Encoding": "gzip, deflate",
                    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
                    "Cookie": "pgv_pvid=7266193040; __qc_wId=29",
                    "Connection": "keep-alive",
                }
            )
            .with_cookies(**{"pgv_pvid": "7266193040", "__qc_wId": "29"})
            .with_data({"name": "lanTest", "password": "123456"})
            .validate()
            .assert_equal("status_code", 200)
            .assert_equal('headers."Content-Type"', "application/json; charset=utf-8")
            .assert_equal("body.code", 200)
            .assert_equal("body.msg", "ok")
        ),
    ]
​
​
if __name__ == "__main__":
    TestCaseDoctest().test_start()
 

执行httprunner测试用例

使用hrun doctest_test.py 或者 pytest doctest_test.py 均可执行测试用例。

HttpRunner3.X开源接口测试框架学习(二)

C:\github\baidutest\har>hrun doctest_test.py
2020-08-11 15:01:13.457c:\programs\python\python38\lib\site-packages\urllib3\request.py:171: InvalidProxyConfigurationWarning: Your proxy configuration specified an HTTPS scheme for the proxy. Are you sure you want to use HTTPS to contact the proxy? This most likely indicates an error in your configuration. Read this issue for more info: https://github.com/urllib3/urllib3/issues/1850
  return self.urlopen(method, url, **extra_kw)
 | INFO     | httprunner.make:__make:512 - make path: C:\github\baidutest\har\doctest_test.py
2020-08-11 15:01:13.495 | INFO     | httprunner.make:format_pytest_with_black:170 - format pytest cases with black ...
No Path provided. Nothing to do ????
2020-08-11 15:01:13.814 | INFO     | httprunner.cli:main_run:56 - start to run tests with pytest. HttpRunner version: 3.1.4
================================================= test session starts =================================================
platform win32 -- Python 3.8.5, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: C:\github\baidutest\har
plugins: forked-1.3.0, metadata-1.10.0, rerunfailures-9.0, allure-pytest-2.8.17, assume-2.2.1, html-2.1.1, xdist-1.34.0
collected 1 item
​
doctest_test.py .                                                                                                [100%]
​
================================================== 1 passed in 0.93s ==================================================
​
C:\github\baidutest\har>pytest doctest_test.py
================================================= test session starts =================================================
platform win32 -- Python 3.8.5, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: C:\github\baidutest\har
plugins: forked-1.3.0, metadata-1.10.0, rerunfailures-9.0, allure-pytest-2.8.17, assume-2.2.1, html-2.1.1, xdist-1.34.0
collected 1 item
​
doctest_test.py .                                                                                                [100%]
​
================================================== 1 passed in 0.84s ==================================================
​

生成接口测试报告

安装httprunner模块自动安装了pytest_html模块,可使用pytest doctest_test.py --html=reports.html 命令执行用例并生成报告

HttpRunner3.X开源接口测试框架学习(二)

 

 


C:\github\baidutest\har>pytest doctest_test.py  --html=reports.html
================================================= test session starts =================================================
platform win32 -- Python 3.8.5, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: C:\github\baidutest\har
plugins: forked-1.3.0, metadata-1.10.0, rerunfailures-9.0, allure-pytest-2.8.17, assume-2.2.1, html-2.1.1, xdist-1.34.0
collected 1 item
​
doctest_test.py .                                                                                                [100%]
​
-------------------------- generated html file: file://C:\github\baidutest\har\reports.html ---------------------------
================================================== 1 passed in 0.93s ==================================================

reports测试报告:

HttpRunner3.X开源接口测试框架学习(二)

未完待续,下一节用例参数化与关联!!!!

欢迎大家关注我的订阅号,会定期分享一些关于测试相关的文章,有问题也欢迎一起讨论学习!订阅号每一条留言都会回复!

HttpRunner3.X开源接口测试框架学习(二)