RobotFramework/Selenium:失败时如何将截图名设为测试用例名
动态命名失败测试用例的截图方案
当然可以实现这个需求!而且用Robot Framework的内置功能就能轻松搞定,完全适配你当前的Python 2.7、wxPython 2.8和geckodriver环境。下面给你具体的实现思路和代码示例:
核心思路
利用Robot Framework的内置变量获取当前测试用例名称和执行状态,结合SeleniumLibrary的截图关键字,实现仅在测试用例失败时,用测试用例名称(可替换空格为下划线)命名截图。
具体实现
你不需要自定义Get Testcase Name关键字,Robot Framework已经提供了内置变量${TEST NAME}可以直接获取当前执行的测试用例名称。再配合Run Keyword If Test Failed关键字,就能精准触发失败时的截图操作。
方案一:全局测试用例Teardown(推荐)
在测试套件的Settings部分配置全局的Test Teardown,这样所有测试用例执行完成后,都会自动判断是否失败并执行截图:
*** Settings *** Library SeleniumLibrary # 每个测试用例执行完后,若失败则运行截图关键字 Test Teardown Run Keyword If Test Failed Capture Named Failure Screenshot *** Keywords *** Capture Named Failure Screenshot # 获取当前测试用例名称 ${test_case_name}= Get Variable Value ${TEST NAME} # 将名称中的空格替换为下划线(如果需要保留空格,可跳过这一步) ${formatted_name}= Replace String ${test_case_name} ${SPACE} _ # 执行截图,用格式化后的名称作为文件名 Capture Page Screenshot ${formatted_name}.png
方案二:单个测试用例内配置
如果只想给特定测试用例配置这个逻辑,可以在测试用例里直接添加:
*** Test Cases *** Testcase Easter [Documentation] 测试用例1 # 你的测试步骤... [Teardown] Run Keyword If Test Failed Capture Named Failure Screenshot Testcase Christmas [Documentation] 测试用例2 # 你的测试步骤... [Teardown] Run Keyword If Test Failed Capture Named Failure Screenshot Testcase Foo [Documentation] 测试用例3 # 你的测试步骤... [Teardown] Run Keyword If Test Failed Capture Named Failure Screenshot *** Keywords *** Capture Named Failure Screenshot ${test_case_name}= Get Variable Value ${TEST NAME} ${formatted_name}= Replace String ${test_case_name} ${SPACE} _ Capture Page Screenshot ${formatted_name}.png
关键细节说明
- 内置变量说明:
${TEST NAME}:返回当前执行的测试用例的完整名称(比如Testcase Christmas)${TEST STATUS}:返回当前测试用例的执行状态(PASS或FAIL),不过Run Keyword If Test Failed已经帮我们做了状态判断,无需手动校验
- 文件名格式:
- 如果想要保留空格作为文件名(比如
Testcase Christmas.png),直接去掉Replace String步骤,用Capture Page Screenshot ${TEST NAME}.png即可
- 如果想要保留空格作为文件名(比如
- 环境兼容性:
你的Python 2.7、wxPython 2.8和geckodriver环境完全支持这些关键字,因为都是Robot Framework和SeleniumLibrary的标准功能,没有版本冲突问题。
内容的提问来源于stack exchange,提问作者Martin Herzuba
相关产品推荐
相关产品推荐

