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

Robot Framework监听器报错TypeError: 'TestCase' object is not subscriptable及测试结果入库失败问题求助

Robot Framework监听器报错TypeError: 'TestCase' object is not subscriptable及测试结果入库失败问题求助

这个问题的核心原因是你混淆了Robot Framework监听器API v3版本的参数类型——end_test方法接收的是对象,不是字典,所以不能用[]下标来访问属性,得用.点语法来获取属性值。下面给你详细的解决方案:

错误根源分析

Robot Framework监听器API v3中,end_test方法的正确参数定义是:

def end_test(self, test, result):

其中:

  • test是TestCase类的实例对象
  • result是TestResult类的实例对象

这两个都是对象,不是字典,所以你用result['status']这种字典下标方式访问属性,就会抛出TypeError: 'TestCase' object is not subscriptable错误。

修正后的监听器代码

我帮你修正了代码中的参数访问方式、拼写错误以及潜在的问题,你可以直接使用:

from robot.libraries.BuiltIn import BuiltIn
import psycopg2
import datetime

class CustomListener:
    ROBOT_LISTENER_API_VERSION = 3

    def __init__(self):
        # 增加数据库连接异常捕获,方便排查连接问题
        try:
            self.conn = psycopg2.connect(
                host= "....",
                port= "...",
                database = "...s",
                user = "j....",
                password = "......"
            )
        except psycopg2.Error as e:
            print(f"PostgreSQL连接失败:{str(e)}")
            raise  # 抛出异常终止监听器初始化,避免后续无意义执行

    def end_test(self, test, result):
        # 用点语法访问对象属性
        execution_result = 'PASSED' if result.status == "PASS" else 'FAILED'
        # 修正了原代码中FALLIED的拼写错误
        
        test_name = test.name
        execution_start = result.start_time
        execution_end = result.end_time
        execution_duration = result.elapsed_time
        # 注意Robot Framework的属性名是elapsed_time,不是elapsedtime
        
        cursor = self.conn.cursor()
        try:
            # 修正了SQL中excecution_star的拼写错误,改为execution_start
            # 移除了重复传入的execution_duration参数,只保留需要的秒数
            cursor.execute(
                "INSERT INTO test_results (test_name, execution_start, execution_end, execution_duration, execution_result) VALUES (%s, %s, %s, %s, %s)",
                (test_name, execution_start, execution_end, execution_duration.total_seconds(), execution_result)
            )
            self.conn.commit()
        except psycopg2.Error as e:
            print(f"数据插入失败:{str(e)}")
            self.conn.rollback()  # 插入失败回滚事务,避免脏数据
        finally:
            cursor.close()  # 确保游标无论成功失败都关闭

关键修正点说明

  1. 参数与属性访问:把result['status']改成result.status,result['name']改成test.name(用例名称在test对象里),所有属性都用.点语法访问
  2. 拼写错误修正:FALLIED改为FAILED,SQL字段名excecution_star改为execution_start,属性名elapsedtime改为elapsed_time(Robot Framework官方定义的属性名是带下划线的)
  3. 异常处理增强:增加数据库连接和数据插入的异常捕获,方便排查问题,同时插入失败时回滚事务,避免脏数据
  4. 参数合理性:原代码中插入SQL时同时传了execution_duration.total_seconds()和execution_duration,这里只保留了耗时的秒数(如果需要datetime对象可以调整,但要确保数据库字段类型匹配)

额外注意事项

  • 确保监听器文件路径正确:如果测试用例和监听器不在同一目录,运行时要指定完整路径,比如--listener C:\Users\voztelecom\Documents\CustomListener.py
  • 数据库字段类型匹配:execution_start和execution_end是datetime对象,你的PostgreSQL表对应的字段要设置为timestamp类型,如果需要字符串格式,可以转成字符串后插入,比如execution_start.strftime('%Y-%m-%d %H:%M:%S')
  • 调试技巧:可以先在end_test方法里加print语句输出属性值,确认数据正确后再执行插入操作,方便快速定位问题

这样修改后,应该就能解决你的错误,成功把测试结果存入PostgreSQL了。


备注:内容来源于stack exchange,提问作者María Luján Tissera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.21 10:39:29