Robot Framework POST请求400场景测试:无法获取状态码求助
Robot Framework POST请求400错误无法获取状态码的解决方法
问题原因
RequestsLibrary的POST On Session关键字默认会将4xx、5xx类错误状态码的响应视为异常抛出,导致后续代码无法执行,无法从响应对象中获取status_code属性完成断言。
解决方案1:添加ignore_status=True参数(推荐)
在调用POST On Session时添加ignore_status=True参数,关键字将不会因错误状态码抛出异常,直接返回完整响应对象,后续可正常获取状态码。
修改后的关键字代码:
**Post API Request** [Documentation] Post Request call [Arguments] ${base_url} ${endpoint_uri} ${jsonBody}=${None} ${tokenGenerated}=${None} Create Session mysession ${base_url} disable_warnings=1 ${headers} Create Dictionary Content-Type=application/json Authorization=Bearer ${tokenGenerated} # 加入ignore_status=True,禁止错误状态码触发异常 ${postResponse}= POST On Session mysession ${endpoint_uri} json=${jsonBody} headers=${headers} ignore_status=True ${statusCode} = Convert to string ${postResponse.status_code} log to console ${statusCode} Should Be Equal As Strings ${postResponse.status_code} 400
解决方案2:捕获异常提取状态码
若你的robotframework-requests版本不支持ignore_status参数,可使用Run Keyword And Expect Error捕获异常,再从异常信息中提取状态码。
示例代码:
**Post API Request** [Documentation] Post Request call [Arguments] ${base_url} ${endpoint_uri} ${jsonBody}=${None} ${tokenGenerated}=${None} Create Session mysession ${base_url} disable_warnings=1 ${headers} Create Dictionary Content-Type=application/json Authorization=Bearer ${tokenGenerated} # 捕获400错误对应的异常 ${error_msg}= Run Keyword And Expect Error 400 Client Error:* ... POST On Session mysession ${endpoint_uri} json=${jsonBody} headers=${headers} # 从异常字符串中截取状态码 ${statusCode}= Get Substring ${error_msg} 0 3 log to console ${statusCode} Should Be Equal As Strings ${statusCode} 400
解决方案3:直接调用requests原生方法
如果前两种方案都不适用,可直接调用Python的requests库原生方法,手动处理响应避免框架自动抛出异常。
示例代码:
**Post API Request** [Documentation] Post Request call [Arguments] ${base_url} ${endpoint_uri} ${jsonBody}=${None} ${tokenGenerated}=${None} # 导入requests库 ${requests}= Import Library requests ${full_url}= Catenate ${base_url} ${endpoint_uri} ${headers} Create Dictionary Content-Type=application/json Authorization=Bearer ${tokenGenerated} # 发送POST请求,按需设置allow_redirects和verify参数 ${postResponse}= Call Method ${requests} post ${full_url} json=${jsonBody} headers=${headers} allow_redirects=False verify=False ${statusCode} = Convert to string ${postResponse.status_code} log to console ${statusCode} Should Be Equal As Strings ${postResponse.status_code} 400
内容的提问来源于stack exchange,提问作者rajesh
相关产品推荐
相关产品推荐

