You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

获取Robot Framework关键字失败原因及实现执行信息收集监听器

Alright, let’s break down how to solve both your Robot Framework requirements clearly. I’ve put together a complete, working listener implementation that covers everything you need, plus details on capturing failure reasons:

1. 获取Robot Framework关键字的失败原因

When a keyword fails, Robot Framework exposes the failure details directly through its listener API. Specifically, in the end_keyword method, you can access the error attribute of the keyword object—this holds the full error message or stack trace that caused the failure. We’ll leverage this in the listener below to log failure info whenever a keyword doesn’t pass.

2. 完整的监听器实现(收集耗时、状态、失败信息)

Here’s a polished version of your listener that tracks all required data and writes it to a temp file. I’ve filled in the missing end_keyword method and added extra context like keyword name and parent test case for better visibility:

import os.path
import tempfile
from datetime import datetime

class PythonListener:
    ROBOT_LISTENER_API_VERSION = 2
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'

    def __init__(self, filename='keyword_execution_logs.txt'):
        # Set up output file in system temp directory
        outpath = os.path.join(tempfile.gettempdir(), filename)
        self.outfile = open(outpath, 'w')
        # Write header for log file
        self.outfile.write(f"Keyword Execution Log Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        self.outfile.write("-" * 80 + "\n")

    def end_keyword(self, keyword):
        # Convert execution time from milliseconds to seconds for readability
        execution_time = round(keyword.elapsedtime / 1000, 2)
        # Pull core keyword and test case info
        keyword_name = keyword.name
        test_case_name = keyword.parent.name
        status = keyword.status

        # Build base log entry
        log_entry = f"Test Case: '{test_case_name}' | Keyword: '{keyword_name}' | Status: {status} | Time: {execution_time}s"
        
        # Append failure reason if keyword failed
        if status == 'FAIL':
            failure_reason = keyword.error.strip()
            log_entry += f"\nFailure Reason:\n{failure_reason}"
        
        # Write entry to file with separator
        self.outfile.write(log_entry + "\n" + "-" * 80 + "\n")

    def close(self):
        # Clean up: close file and add end timestamp
        self.outfile.write(f"Log Ended at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        self.outfile.close()

How to Activate the Listener

You have two simple ways to use this listener:

  • Option 1: Import as a library in your test suite
    Add this line at the top of your .robot file:
    Library    /path/to/your/listener/file.py    custom_log_filename.txt
    
  • Option 2: Use via command line
    Run your tests with the --listener flag:
    robot --listener /path/to/your/listener/file.py:custom_log_filename.txt your_test_suite.robot
    

Key Details Explained

  • Execution Time: keyword.elapsedtime returns time in milliseconds—we convert it to seconds for easier interpretation.
  • Failure Capture: We check if keyword.status equals 'FAIL' to trigger pulling the failure details from keyword.error.
  • Cleanup: The close method ensures the log file is properly closed and adds a timestamp for log completeness.

内容的提问来源于stack exchange,提问作者Sreejith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:35:32