!pip install jsonpath
Requirement already satisfied: jsonpath in /root/venv/lib/python3.7/site-packages (0.82)
import unittest
from jsonpath import jsonpath
class APICase(unittest.TestCase):
def assert_response(self, response, validate_expression):
"""
validate_expression example:
[["assertEqual", "$..code", 0], ["assertEqual", "$..msg", "OK"]]
"""
for validation in validate_expression:
method_name, jsonpath_expr, expected_value = validation
actual = jsonpath(resp, jsonpath_expr)[0]
assert_method = getattr(self, method_name)
assert_method(expected_value, actual)
resp = {"msg": "OK", "code": 0, "data": ""}
validate_expression = [["assertEqual", "$..code", 0], ["assertEqual", "$..msg", "OK"]]
APICase().assert_response(resp, validate_expression)
print("OK")
0 0
OK OK
OK
from jsonpath import jsonpath
class APICase(unittest.TestCase):
@classmethod
def extract(cls, response, extractors):
for name,jsonpath_expression in extractors.items():
value, *_ = jsonpath(resp, jsonpath_expression)
setattr(cls, name, value)
extractors = {"token": "$..token", "loan_id": "$..id"}
resp = {"id": "123", "token": "xxx xxx"}
APICase.extract(resp, extractors)
print(APICase.token)
xxx xxx
import unittest
import re
class APICase(unittest.TestCase):
@classmethod
def replace_data(cls, string, pattern='#(.*?)#'):
"""数据动态替换"""
# pattern = '#(.*?)#'
results = re.finditer(pattern=pattern, string=string)
for result in results:
old = result.group()
key = result.group(1)
new = str(getattr(cls, key, ''))
string = string.replace(old, new)
return string
APICase.investor_phone = 'investor phone'
APICase.investor_pwd = 'investor phone'
APICase.loan_phone = 'loan phone'
APICase.loan_pwd = 'loan pwd'
APICase.admin_phone = 'admin phone'
APICase.admin_pwd = 'admin pwd'
original_data = """{"phone": "#investor_phone#", \
"pwd": "#investor_pwd#", \
"admin": "#admin_phone#"}"""
new_data = APICase.replace_data(original_data)
print(new_data)
{"phone": "investor phone", "pwd": "investor phone", "admin": "admin phone"}