python assert二次封装
在编写接口自动化case时,感觉自带的assert与unittest内的assert都不太好用在某些场景下,所以对assert进行了二次封装,很多地方可以完善与修改,稍微分享一下~
内部逻辑就不过多叙述了,可以阅读参考一下,逻辑并不复杂,运用到了
jsonpath模块
from common.logger_handler import logger
import jsonpath
class WbAssert:
@staticmethod
def getValue(body, key):
return jsonpath.jsonpath(body, f'$..{key}')
def getKey(self, body, key):
json = self.getValue(body, key)
if not json: logger.debug(f"No key can be obtained. Procedure: {key}")
return json
def assertKey(self, body, key):
"""Whether an assertion exists key"""
res = self.getValue(body, key)
if not res: logger.info(f'Incoming does not exist {key}')
assert res != False
def assertTrue(self, body, key, value):
"""a=b Check whether the value is True
This method applies to a unique parameter"""
assert self.getKey(body, key)[0] == value
def assertFalse(self, body, key, value):
"""a!=b Check whether the value is False
This method applies to a unique parameter"""
assert self.getKey(body, key)[0] != value
def assertScope(self, body, key, left, right):
"""Assert that the value is within the specified range"""
for value in self.getKey(body, key):
assert left < value <= right
def assertJudge(self, body, key, identifier, specifiedValue):
"""Determines whether the value matches the operator range size"""
global s
for value in self.getKey(body, key):
if identifier == '>':
s = int(value) > specifiedValue
elif identifier == '>=':
s = int(value) >= specifiedValue
elif identifier == '<':
s = int(value) < specifiedValue
elif identifier == '<=':
s = int(value) <= specifiedValue
elif identifier == '==':
s = int(value) == specifiedValue
else:
logger.info(f'identifier:{identifier},Input error')
assert s