httprunner 2.x学习11-命令行参数详解

前言

httprunner 2.x 命令行参数讲解

命令行参数CLI

使用 -h 查看相关命令行参数

hrun -h

参数名称 参数值 参数说明
-h, --help 不带参数 查看帮助信息
-V, --version 不带参数 查看版本号
--log-level LOG_LEVEL 日志等级,默认 info 级别 如:debug/info/warn/error/critical
--log-file LOG_FILE 指定日志文本保存路径
--dot-env-path DOT_ENV_PATH 指定环境变量.env的详细路径
--report-template REPORT_TEMPLATE 指定报告模板路径
--report-dir REPORT_DIR 指定报告保存目录
--report-file REPORT_FILE 指定报告文件路径,优先级高于报告保存目录REPORT_DIR
--save-tests 不带参数 将加载/解析/变量输出/摘要json数据保存到json文件
--failfast 不带参数 在出现第一个错误或失败时停止测试运行
--startproject STARTPROJECT 创建一个 hrun 项目
--validate [VALIDATE [VALIDATE ...]] 校验json格式
--prettify [PRETTIFY [PRETTIFY ...]] 美化json文件

--startproject

创建一个 httprunner2.x 的项目,可以看到整个项目的基本结构,执行命令:hrun --startproject projectname

D:demo>hrun --startproject hrun_yoyo
Start to create new project: hrun_yoyo
CWD: D:demo

created folder: hrun_yoyo
created folder: hrun_yoyoapi
created folder: hrun_yoyo	estcases
created folder: hrun_yoyo	estsuites
created folder: hrun_yoyo
eports
created file: hrun_yoyoapidemo_api.yml
created file: hrun_yoyo	estcasesdemo_testcase.yml
created file: hrun_yoyo	estsuitesdemo_testsuite.yml
created file: hrun_yoyodebugtalk.py
created file: hrun_yoyo.env
created file: hrun_yoyo.gitignore

创建完成后整个目录结构

--save-tests

--save-tests 作用是将加载/解析/变量输出/摘要json数据保存到json文件,这个功能对于调试还是很有帮助的,方便了解整个用例和报告的数据结构
使用语法:hrun demo_login.yml --save-tests

D:demohrun_yoyoapi>hrun demo_login.yml --save-tests
INFO     HttpRunner version: 2.5.7
dump file: D:demohrun_yoyoapilogsdemo_login.loaded.json
dump file: D:demohrun_yoyoapilogsdemo_login.parsed.json
INFO     Start to run testcase: demo login api
demo login api
INFO     POST http://127.0.0.1:8000/api/v1/login
INFO     status_code: 200, response_time(ms): 130.0 ms, response_length: 109 bytes

.

----------------------------------------------------------------------
Ran 1 test in 0.135s

OK
dump file: D:demohrun_yoyoapilogsdemo_login.summary.json
dump file: D:demohrun_yoyoapilogsdemo_login.io.json
INFO     Start to render Html report ...
INFO     Generated Html report: D:demohrun_yoyoapi
eports20210406T154415.947966.html
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-Break to quit

运行完成后,会生成一个 logs 的目录

  • demo_login.io.json : io读写文件相关的数据
  • demo_login.loaded.json: 加载到的测试用例生成的json数据文件
  • demo_login.parsed.json: 解析yaml文件生成json数据
  • demo_login.summary.json:运行用例后生成的报告总结

--log-level

打印日志等级,使用--log-level参数,日志有五个等级:debug < info < warn < error < critical

各等级的含义:

  • debug: 级别最低,用户开发过程中的调试
  • info:打印程序运行是的正常的信息,用于替代print输出
  • warn: 打印警告信息,不影响程序的运行
  • error: 程序运行出错,可以修复,常用在except异常捕获之后
  • critical: 非常严重,无法修复,程序继续运行的话后果非常严重

设置了日志等级后,调用比等级低的日志记录函数则不会输出。

httprunner默认使用info等级,不带 --log-level info 参数结果也是一样的

hrun demo_login.yml --log-level info

设置debug等级,打印最详细的内容

hrun demo_login.yml --log-level debug

D:demohrun_yoyoapi>hrun demo_login.yml --log-level debug
INFO     HttpRunner version: 2.5.7
INFO     Start to run testcase: demo login api
demo login api
INFO     POST http://127.0.0.1:8000/api/v1/login
DEBUG    request kwargs(raw): {'headers': {'Content-Type': 'application/json'}, 'json': {'username': 'test', 'password': '123456'}, 'verify': True}
DEBUG    processed request:
> POST http://49.235.92.12:7005/api/v1/login
> kwargs: {'headers': {'Content-Type': 'application/json'}, 'json': {'username': 'test', 'password': '123456'}, 'verify': True, 'timeout': 120}
DEBUG
================== request details ==================
url              : 'http://127.0.0.1:8000/api/v1/login'
method           : 'POST'
headers          : {'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Content-Length': '42'}
body             : b'{"username": "test", "password": "123456"}'

DEBUG
================== response details ==================
ok               : True
url              : 'http://49.235.x.x:7001/api/v1/login'
status_code      : 200
reason           : 'OK'
cookies          : {}
encoding         : None
headers          : {'Date': 'Wed, 07 Apr 2021 03:37:49 GMT', 'Server': 'WSGIServer/0.2 CPython/3.6.8', 'Content-Type': 'application/json', 'Vary': 'Accept, Cookie', 'Allow': 'POST, OPTIONS', 'X-Frame-Options': 'SAMEORIGIN', 'Content-Length': '109'}
content_type     : 'application/json'
body             : {'code': 0, 'msg': 'login success!', 'username': 'test', 'token': 'd58b5e43c7fb5cb906f1cd12889ab705cc764154'}

INFO     status_code: 200, response_time(ms): 162.7 ms, response_length: 109 bytes

DEBUG    start to validate.
DEBUG    extract: status_code   => 200
DEBUG
validate: status_code equals 200(int)   ==> pass
.

----------------------------------------------------------------------
Ran 1 test in 0.169s

OK
DEBUG    No html report template specified, use default.
INFO     Start to render Html report ...
INFO     Generated Html report: D:demohrun_yoyoapi
eports20210407T033750.778655.html
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-Break to quit

另外三个等级warn/error/critical,只有有警告或者报错时候,才有日志输出,所以用的很少

D:demohrun_yoyoapi>hrun demo_login.yml --log-level warn
demo login api
.

----------------------------------------------------------------------
Ran 1 test in 0.165s

OK
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-Break to quit

D:demohrun_yoyoapi>hrun demo_login.yml --log-level error
demo login api
.

----------------------------------------------------------------------
Ran 1 test in 0.196s

OK
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-Break to quit

D:demohrun_yoyoapi>hrun demo_login.yml --log-level critical
demo login api
.

----------------------------------------------------------------------
Ran 1 test in 0.185s

OK
Sentry is attempting to send 0 pending error messages
Waiting up to 2 seconds
Press Ctrl-Break to quit

--log-file

--log-file 参数保存日志文件到指定的目录,保存日志文件到yoyo.txt

hrun demo_login.yml --log-file ./yoyo.txt

在当前运行的目录,会生成一个yoyo.txt文件

INFO     HttpRunner version: 2.5.7
INFO     Start to run testcase: demo login api
INFO     POST http://127.0.0.1:8000/api/v1/login
INFO     status_code: 200, response_time(ms): 208.95 ms, response_length: 109 bytes

INFO     Start to render Html report ...
INFO     Generated Html report: D:demohrun_yoyoapi
eports20210407T034138.037326.html

由于日志的输出有加颜色,所以保存的时候会有一些乱码,我稍微改了下httprunner/logger.py文件的日志内容,但还是有一点乱码

def setup_logger(log_level, log_file=None):
    """setup root logger with ColoredFormatter."""
    level = getattr(logging, log_level.upper(), None)
    if not level:
        color_print("Invalid log level: %s" % log_level, "RED")
        sys.exit(1)

    # hide traceback when log level is INFO/WARNING/ERROR/CRITICAL
    if level >= logging.INFO:
        sys.tracebacklimit = 0
    formatter = ColoredFormatter(
        u"%(log_color)s%(bg_white)s%(levelname)-8s%(reset)s %(message)s",
        datefmt=None,
        reset=True,
        log_colors=log_colors_config
      )
    if log_file:
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')  # 加了这句
        handler = logging.FileHandler(log_file, encoding='utf-8')
    else:
        handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logging.root.addHandler(handler)
    logging.root.setLevel(level)

其它

--dot-env-path 用于指定.env文件的目录

hrun test_demo.yml --dot-env-path d:path o.env

--failfast 遇到失败停止测试

hrun test_demo.yml --failfast

--validate 校验json格式,格式正确返回OK,若 JSON 文件格式存在异常,则打印详细的报错信息,精确到错误在文件中出现的行和列。

hrun --validate test_login2.json

--prettify 用于格式化json文件内容,美化 json 格式

hrun --prettify test_login2.json

D:softuntitled>hrun --validate test_login2.json
Start to validate JSON file: test_login2.json
OK

D:softuntitled>hrun --prettify test_login2.json
Start to prettify JSON file: test_login2.json
success: test_login2.pretty.json


httprunner 2.x实战教程点我 ->立即报名

原文地址:https://www.cnblogs.com/yoyoketang/p/14624680.html