如何在Python脚本中解析并打印PyMeter的API响应与错误码?
PyMeter解析API响应与错误码的解决方案
问题说明
使用PyMeter对https://reqres.in/api/users?page=2执行性能测试时,已能成功调用API,但需要实现解析并打印API响应内容与错误码的功能。
API响应示例:
{"page":2,"per_page":6,"total":12,"total_pages":2,"data":[{"id":7,"email":"michael.lawson@reqres.in","first_name":"Michael","last_name":"Lawson","avatar":"https://reqres.in/img/faces/7-image.jpg"},{"id":8,"email":"lindsay.ferguson@reqres.in","first_name":"Lindsay","last_name":"Ferguson","avatar":"https://reqres.in/img/faces/8-image.jpg"},{"id":9,"email":"tobias.funke@reqres.in","first_name":"Tobias","last_name":"Funke","avatar":"https://reqres.in/img/faces/9-image.jpg"},{"id":10,"email":"byron.fields@reqres.in","first_name":"Byron","last_name":"Fields","avatar":"https://reqres.in/img/faces/10-image.jpg"},{"id":11,"email":"george.edwards@reqres.in","first_name":"George","last_name":"Edwards","avatar":"https://reqres.in/img/faces/11-image.jpg"},{"id":12,"email":"rachel.howell@reqres.in","first_name":"Rachel","last_name":"Howell","avatar":"https://reqres.in/img/faces/12-image.jpg"}],"support":{"url":"https://reqres.in/#support-heading","text":"To keep ReqRes free, contributions towards server costs are appreciated!"}}
解决方案
1. 修正JSON提取器路径
原脚本中JsonExtractor的路径args.data错误,API响应的data字段直接位于根节点,应改为data(或标准JSONPath表达式$.data)。
2. 获取并打印响应与错误码
测试运行后,通过stats.samples可获取所有采样结果,遍历每个样本即可提取响应状态码和响应体内容。
修改后的完整脚本
from unittest import TestCase from pymeter.api.config import TestPlan, ThreadGroupWithRampUpAndHold from pymeter.api.samplers import HttpSampler from pymeter.api.reporters import HtmlReporter from pymeter.api.postprocessors import JsonExtractor from pymeter.api.assertions import ResponseAssertion class TestTestPlanClass(TestCase): def __init__(self, *args, **kwargs): super(TestTestPlanClass, self).__init__(*args, **kwargs) print("TestTestPlanClass") @classmethod def setUpClass(cls): print("setUpClass") def test_case_1(self): # 修正JSON提取器路径,提取根节点下的data字段 json_extractor = JsonExtractor("user_data", "data") ra = ResponseAssertion().contains_substrings("data") http_sampler = HttpSampler("get_users_request", "https://reqres.in/api/users?page=2", ra, json_extractor) html_reporter = HtmlReporter() # 线程组配置:1线程,1秒启动,持续1秒 thread_group_main = ThreadGroupWithRampUpAndHold(1, 1, 1, http_sampler) test_plan = TestPlan(thread_group_main, html_reporter) # 运行测试并获取结果 stats = test_plan.run() # 遍历所有样本,打印响应码和响应体 for sample in stats.samples: print(f"响应状态码: {sample.response_code}") print(f"响应内容: {sample.response_body}") print("-" * 50) self.assertLess(stats.sample_time_99_percentile_milliseconds, 2000) @classmethod def tearDownClass(cls): print("tearDownClass")
关键说明
stats.samples包含所有采样的详细结果,每个样本对象的response_code属性对应HTTP状态码,response_body属性对应完整的API响应内容。- 若只需提取响应中的特定字段(如用户列表),已通过
JsonExtractor将结果存入user_data变量,可在后续逻辑中直接调用该变量。
内容的提问来源于stack exchange,提问作者Abhishek Kulkarni
相关产品推荐
相关产品推荐

