使用 httprunner 2.x版本,validate校验的时候引用变量,在测试报告会显示LazyString($msg)。
httprunner 版本是2.5.7 demo.yml文件用例先定义变量,在validate引用变量
config:
name: demo case
base_url: http://192.168.1.0:8000
variables:
msg: 成功success!
teststeps:
- name: demo
request:
url: /api/test/demo
method: GET
validate:
- eq: [body.code, 0]
- eq: [body.msg, $msg]
执行后生成测试报告
可以在github上找到解决办法https://github.com/httprunner/httprunner/issues/693
在模板搜索{{validator.expect | e}}
,将其修改为{{validator.expect_value | e}}
就可以了
这个问题很多用户都有提到https://github.com/httprunner/httprunner/issues/892,但是作者给的答复是让升级到3.x,言外之意是不想解决这个问题了。
先找到validator.py中validator_dict部分
comparator 是校验方式
check 是检查点
check_value 是实际结果
expect 期望值
expect_value 期望的实际值
不用命令行执行,用httprunner提供的API执行用例
运行结果找到validators
因为expect_value是实际得到的结果值,所以在模板里面{{validator.expect | e}}
,将其修改为{{validator.expect_value | e}}
就可以,这种方法只能解决测试报告的显示问题。
如果我们不需要html的测试报告,只需得到summary结果,summary结果在转json的时候,会出现异常:Object of type ‘LazyString’ is not JSON serializable
from httprunner.api import HttpRunner
runner = HttpRunner()
summary = runner.run('demo.yml')
print(summary)
import json
print(json.dumps(summary))
因为LazyString 是自定义的一个类,无法解析json,关于自定义类解析json的问题在前面一篇有讲解https://www.cnblogs.com/yoyoketang/p/15588036.html
出现这个问题的最根本问题在于 LazyString 类,找到parser.py中的 LazyString 类
class LazyString(object):
def __repr__(self):
return "LazyString({})".format(self.raw_string)
__repr__
方法返回的内容就是我们所看到的LazyString($msg)
, 是这个类的实例化对象打印内容。
于是可以用猴子补丁解决
from httprunner.api import HttpRunner
from httprunner.parser import LazyString
from httprunner.report import gen_html_report
import json
def new__repr__(self):
return "{}".format(self.raw_string)
LazyString.__repr__ = new__repr__
runner = HttpRunner()
summary = runner.run('demo.yml')
gen_html_report(summary=summary)
生成报告后显示效果
summary转json,需定义解析LazyString类的方法
from httprunner.api import HttpRunner
from httprunner.parser import LazyString
from httprunner.report import gen_html_report
import json
from json import JSONEncoder
def new__repr__(self):
return "{}".format(self.raw_string)
LazyString.__repr__ = new__repr__
runner = HttpRunner()
summary = runner.run('demo.yml')
# gen_html_report(summary=summary)
def new_default(self, obj):
if isinstance(obj, LazyString):
return str(obj)
else:
return json.JSONEncoder.default(self, obj)
JSONEncoder.default = new_default
print(json.dumps(summary, indent=4))