Python Robot Framework验证JSON响应 解决dict无count属性报错
报错原因说明
你遇到的AttributeError: 'dict' object has no attribute 'count'来自两个直接的问题:
- 字典对象没有
.count方法:requests.Response.json()返回的是Python原生dict,.count()是list类型的内置方法(用于统计元素出现次数),不能直接在dict上调用。想要拿接口返回的count字段值,需要用response["count"]的字典取值语法。 - 你定义的JSON Schema和接口真实结构不匹配:SWAPI的people接口返回的根节点是object,不是你写的array;且
height、mass字段是字符串类型,不是number类型,就算修正了count的取值方式,后续Schema校验也会抛出结构不匹配的错误。
可选的JSON响应校验方案
1. 逐字段取值断言
适合固定预期值的校验场景,无额外依赖。
修正你的validate_json_response关键字逻辑:
@keyword def validate_json_response(self, response): # 校验必填字段存在 assert all(key in response for key in ["count", "next", "previous", "results"]), "响应缺少必填顶层字段" # 校验count值:接口返回的count是整数,不能和字符串类型的'82'做比较 assert response["count"] == 82, f"count值校验失败,实际为{response['count']}" # 校验results结构 assert isinstance(response["results"], list), "results字段不是列表类型"
2. JSON Schema结构校验
适合需要通用校验响应结构(字段类型、必填项、数组规则)的场景,你已经在代码中引入了jsonschema库,只需要修正错误的Schema定义即可:
# keywords.py 顶部导入 from robot.api.deco import keyword from jsonschema import validate class keywords: ROBOT_LIBRARY_SCOPE = 'TESTS' # 匹配接口真实返回结构的Schema schemaAllUsers = { "type": "object", "required": ["count", "next", "previous", "results"], "properties": { "count": {"type": "integer"}, "next": {"type": ["string", "null"]}, "previous": {"type": ["string", "null"]}, "results": { "type": "array", "items": { "type": "object", "required": ["name", "height", "mass"], "properties": { "name": {"type": "string"}, "height": {"type": "string"}, "mass": {"type": "string"} } } } } } @keyword def validate_json_response(self, response): # 先做全量结构校验,不匹配时会抛出带具体错误位置的异常 validate(instance=response, schema=self.schemaAllUsers) # 再做关键值校验 assert response["count"] == 82
3. 依托Robot内置库简化断言
如果不想写大量Python自定义关键字,可以直接用Robot内置的Collections库完成字典取值和校验,提升用例可读性。
修改后的测试用例示例:
*** Settings *** Library keywords.py Library Collections *** Test Cases *** TC - Verify GET request for all users ${json_resp} Get Json Response ${people_endpoint} # 提取count字段做整数比较 ${count} Get From Dictionary ${json_resp} count Should Be Equal As Integers ${count} 82 # 提取results字段做结构校验 ${results} Get From Dictionary ${json_resp} results Should Be True ${\isinstance($results, list)} *** Variables *** ${people_endpoint} https://swapi.dev/api/people
现有代码的其他问题修正
你当前代码还有两处会导致运行失败的问题,需要同步调整:
- 自定义方法中调用的
restAPI_library未定义:需要在keywords.py顶部导入你之前编写的请求工具模块,比如把from 请求工具文件名 import get_method放在文件头部,方法内直接调用导入的get_method(URL)即可,不要使用未定义的模块前缀。 - 避免重复请求:现有测试用例对同一个endpoint先后发了两次GET请求(一次拿response对象做状态码校验,一次转JSON),可以把转JSON的逻辑改成接收已有的response对象,减少不必要的接口调用,比如新增关键字:
测试用例里直接复用第一次拿到的response对象转JSON即可。@keyword def convert_response_to_json(self, response): return response.json()
内容的提问来源于stack exchange,提问作者oksa23
相关产品推荐
相关产品推荐

