美文网首页
httprunner学习实践(二)--编写和运行

httprunner学习实践(二)--编写和运行

作者: 陈凌川 | 来源:发表于2019-07-29 16:56 被阅读0次

序言

httprunner的使用和其中的一些概念在官方的文档中已经详细说明,写这个学习记录是为了记录下自己的学习历程,能够在今后快速的深入学习和实践。没有提及的部分,请查看官方文档
版本:2.2.5

参考

HttpRunner V2.x 中文使用文档

录制和转换

录制和转换乘可运行的文件,在官方文档中有详细介绍

编写

首先,获取接口信息,根据实际情况,可以是项目文档,抓包,浏览器F12查看,通过微信开发者工具查看等。
可以使用Yaml/Json文件编写测试,推荐使用Yaml,它在文件中使用注释比较方便
在网上找了一个查询城市天气的接口,编写的yaml如下:

# 测试名称(必须的),String
name: 获取城市的天气
# 变量(可选的), List,被上级(testcases,testsuite)覆盖
variables:
   # 设置变量,城市
   city: 上海
# 默认域名(可选的).String
base_url: https://www.apiopen.top
# 请求参数(必须的), dict, 与request中的参数相同
request:
   method: GET
   url: /weatherApi
   params:
       # 通过 $+参数名称 的形式,应用变量
       city: $city
# 提取器(可选的), dict,提取返回参数
extract:
   code: content.code
# 验证(可选的), list
validate:
   - eq: [$code , 200]
   - eq: [content.msg, "成功!"]
# 前置处理(可选的),list
setup_hooks:
# 后置处理(可选的),list
teardown_hooks:

保存到项目下的 api文件夹,并命名为‘天气.yml’
cmd切换到项目目录,使用hrun运行测试文件

D:\SL\httpAutoTest>hrun api/天气.yml
INFO     Loading environment variables from D:\SL\httpAutoTest\.env
INFO     Start to run testcase: 获取城市的天气
获取城市的天气
INFO     GET https://www.apiopen.top/weatherApi
INFO     status_code: 200, response_time(ms): 1109.06 ms, response_length: 1088
bytes

.

----------------------------------------------------------------------
Ran 1 test in 1.114s

OK
INFO     Start to render Html report ...
INFO     Generated Html report: D:\SL\httpAutoTest\reports\1564387261.html

运行成功后,到reports目录下查看生产的报表


Yaml参数

在编写api/接口名称.yml时,文件中的key如下:

# 测试名称(必须的),String
name:
# 无条件跳过测试(可选的),String,跳过测试的说明
skip:
# 条件为 true 时跳过测试(可选的)
skipIf:
# 条件为 false 时跳过测试(可选的)
skipUnless:
# 变量(可选的), List,被上级(testcases,testsuite)覆盖
variables:
# 默认域名(可选的).String
base_url:
# 请求参数(必须的), dict, 与request中的参数相同
request:
# 提取器(可选的), dict,提取返回参数
extract:
# 验证(可选的), list
validate:
# 验证(可选的), list,与validate相同
validators:
# 前置处理(可选的),list
setup_hooks:
# 后置处理(可选的),list
teardown_hooks:

可以通过查看源码runner.py->Runner->_run_test方法查看具体信息

request参数

request的参数与requests模块中的request参数相同,methodurl是必须参数,如果请求中使用的是json格式的请求的body,建议使用json参数,具体参数如下:

    def request(self, method, url, name=None, **kwargs):
        """
        Constructs and sends a :py:class:`requests.Request`.
        Returns :py:class:`requests.Response` object.

        :param method:
            method for the new :class:`Request` object.
        :param url:
            URL for the new :class:`Request` object.
        :param name: (optional)
            Placeholder, make compatible with Locust's HttpSession
        :param params: (optional)
            Dictionary or bytes to be sent in the query string for the :class:`Request`.
        :param data: (optional)
            Dictionary or bytes to send in the body of the :class:`Request`.
        :param headers: (optional)
            Dictionary of HTTP Headers to send with the :class:`Request`.
        :param cookies: (optional)
            Dict or CookieJar object to send with the :class:`Request`.
        :param files: (optional)
            Dictionary of ``'filename': file-like-objects`` for multipart encoding upload.
        :param auth: (optional)
            Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth.
        :param timeout: (optional)
            How long to wait for the server to send data before giving up, as a float, or \
            a (`connect timeout, read timeout <user/advanced.html#timeouts>`_) tuple.
            :type timeout: float or tuple
        :param allow_redirects: (optional)
            Set to True by default.
        :type allow_redirects: bool
        :param proxies: (optional)
            Dictionary mapping protocol to the URL of the proxy.
        :param stream: (optional)
            whether to immediately download the response content. Defaults to ``False``.
        :param verify: (optional)
            if ``True``, the SSL cert will be verified. A CA_BUNDLE path can also be provided.
        :param cert: (optional)
            if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
        """

注意:httprunnertimeout的默认值为120

def request(self, method, url, name=None, **kwargs):
    .......
    kwargs.setdefault("timeout", 120)
    ......

运行参数

帮助

D:\SL\httpAutoTest>hrun -h
usage: hrun [-h] [-V] [--log-level LOG_LEVEL] [--log-file LOG_FILE]
            [--dot-env-path DOT_ENV_PATH] [--report-template REPORT_TEMPLATE]
            [--report-dir REPORT_DIR] [--failfast] [--save-tests]
            [--startproject STARTPROJECT]
            [--validate [VALIDATE [VALIDATE ...]]]
            [--prettify [PRETTIFY [PRETTIFY ...]]]
            [testcase_paths [testcase_paths ...]]

One-stop solution for HTTP(S) testing.

positional arguments:
  testcase_paths        testcase file path

optional arguments:
  -h, --help            show this help message and exit
  -V, --version         show version
  --log-level LOG_LEVEL
                        Specify logging level, default is INFO.
  --log-file LOG_FILE   Write logs to specified file path.
  --dot-env-path DOT_ENV_PATH
                        Specify .env file path, which is useful for keeping
                        sensitive data.
  --report-template REPORT_TEMPLATE
                        specify report template path.
  --report-dir REPORT_DIR
                        specify report save directory.
  --failfast            Stop the test run on the first error or failure.
  --save-tests          Save loaded tests and parsed tests to JSON file.
  --startproject STARTPROJECT
                        Specify new project name.
  --validate [VALIDATE [VALIDATE ...]]
                        Validate JSON testcase format.
  --prettify [PRETTIFY [PRETTIFY ...]]
                        Prettify JSON testcase format.

查看版本

D:\SL\httpAutoTest>hrun -V
2.2.4

指定测试路径

使用 HttpRunner 指定测试用例路径时,支持多种方式。

使用 hrun 命令外加单个测试用例文件的路径,运行单个测试用例,并生成一个测试报告文件:

hrun filepath/testcase.yml

将多个测试用例文件放置到文件夹中,指定文件夹路径可将文件夹下所有测试用例作为测试用例集进行运行,并生成一个测试报告文件:

hrun testcases_folder_path

指定日志等级

D:\SL\httpAutoTest>hrun api/天气.yml --log-level DEBUG
INFO     Loading environment variables from D:\SL\httpAutoTest\.env
DEBUG    Set OS environment variable: USERNAME
DEBUG    Set OS environment variable: PASSWORD
DEBUG    Set OS environment variable: salesmapi.benlai.com
INFO     Start to run testcase: 获取 城市 的天气
获取 城市 的天气
INFO     GET https://www.apiopen.top/weatherApi
DEBUG    request kwargs(raw): {'params': {'city': '上海'}, 'verify': True}
DEBUG    processed request:
> GET https://www.apiopen.top/weatherApi
> kwargs: {'params': {'city': '上海'}, 'verify': True, 'timeout': 120}
..............

输出日志到文件

指定日志文件输出路径,将在对应目录下生产日志文件

D:\SL\httpAutoTest>hrun api/天气.yml --log-file log.log
获取 城市 的天气
.

----------------------------------------------------------------------
Ran 1 test in 0.942s

OK

保存测试数据

D:\SL\httpAutoTest>hrun api/天气.yml --save-tests
INFO     Loading environment variables from D:\SL\httpAutoTest\.env
dump file: D:\SL\httpAutoTest\logs\天气.loaded.json
dump file: D:\SL\httpAutoTest\logs\天气.parsed.json
INFO     Start to run testcase: 获取 城市 的天气
获取 城市 的天气
INFO     GET https://www.apiopen.top/weatherApi
INFO     status_code: 200, response_time(ms): 958.06 ms, response_length: 1087 b
ytes

.

----------------------------------------------------------------------
Ran 1 test in 0.963s

OK
dump file: D:\SL\httpAutoTest\logs\天气.summary.json
INFO     Start to render Html report ...
INFO     Generated Html report: D:\SL\httpAutoTest\reports\1564465064.html

相关文章

网友评论

      本文标题:httprunner学习实践(二)--编写和运行

      本文链接:https://www.haomeiwen.com/subject/xfyerctx.html