Python函数验证失败未抛异常,Robot测试用例未失败的求助
解决Robot Framework中Python验证失败不触发用例失败的问题
当前你的Python关键字函数遇到验证错误时仅打印提示信息,函数会正常执行完毕并返回None,Robot Framework会默认判定用例执行成功,无法达到"验证失败则用例失败"的预期。解决核心是在Python函数中抛出异常,Robot Framework会将Python抛出的异常识别为用例失败。
修改后的Python函数代码
import json from robot.api.deco import keyword # 定义用到的常量(根据实际业务值替换) CURRENTDATETIME = "currentDateTime" SYSTEMS = "systems" SERIALNUM = "serialNumber" PUBKEYS = "pubKeys" @keyword def ParseJSONUserData(jsonstring): systems = set() # 初始化存储序列号的集合,避免未定义错误 if len(jsonstring) == 0: error_msg = "String is empty. No processing is possible." print(error_msg) raise AssertionError(error_msg) json_dict = json.loads(jsonstring) if len(json_dict) == 0: error_msg = "No data found in file." print(error_msg) raise AssertionError(error_msg) currentdt = json_dict[CURRENTDATETIME] if len(currentdt) == 0: error_msg = "The Current datetime property is empty" print(error_msg) raise AssertionError(error_msg) system_count = len(json_dict[SYSTEMS]) print(f"Systems found: {system_count}") if system_count == 0 : error_msg = "No systems found!" print(error_msg) raise AssertionError(error_msg) for system_result in json_dict[SYSTEMS]: serial_num = system_result[SERIALNUM] if serial_num in systems: error_msg = f"Duplicate systemserialnumber value: {serial_num}" print(error_msg) raise AssertionError(error_msg) systems.add(serial_num) pubkey = system_result[PUBKEYS][0]["pubkey"] if len(pubkey) == 0 : error_msg = f"No pubkey found for system: {serial_num}" print(error_msg) raise AssertionError(error_msg) pubkey_system = system_result[PUBKEYS][0]["system"] if len(pubkey_system) == 0 : error_msg = f"No pubkey system designator (typically intraop) found for system: {serial_num}" print(error_msg) raise AssertionError(error_msg)
关键修改说明
- 抛出断言异常:将所有验证失败的
print语句替换为raise AssertionError(error_msg),Robot Framework会捕获该异常,直接标记用例为失败,并在日志中展示错误信息。 - 初始化集合:新增
systems = set()解决原代码中变量未定义的潜在报错。 - 常量定义:显式定义业务常量,避免魔法字符串,提升代码可读性和维护性。
- 关键字装饰器:
@keyword装饰器让函数符合Robot Framework关键字规范,可直接在测试用例中调用。
对应的Robot Framework代码
无需大幅调整,保持原有调用逻辑即可:
${response}= GET ${host}/data ${data} headers=${header} ParseJSONUserData ${response.json()} # 若函数抛出异常,后续代码不会执行,用例会直接标记为失败
额外优化建议
如果希望错误信息在Robot日志中以错误级别高亮显示,可替换print为Robot官方日志API:
from robot.api import logger # 将print(error_msg)替换为 logger.error(error_msg)
这样错误信息会在Robot测试报告的日志模块中突出显示,更便于问题排查。
内容的提问来源于stack exchange,提问作者user3354840
相关产品推荐
相关产品推荐

