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

为什么我的unittest运行时报错:'str'对象没有属性'cursor'

问题核心原因
  • 你调用get_address_query时传入的第二个参数是字符串'connection',字符串不存在cursor方法,直接触发属性错误
  • 你的mock目标错误:connection是函数的入参,不是函数内部通过pymysql创建的连接对象,所以@mock.patch('lambda_function.pymysql')完全没有作用,mock到的对象根本没有传入业务函数
正确的单元测试实现
def test_get_address_query(self):
    # 构造模拟的connection对象
    mock_record = (('test',),('first',),('last',))
    mock_connection = mock.MagicMock()
    # 按调用链配置mock:connection.cursor().fetchall() 返回模拟数据
    mock_connection.cursor.return_value.fetchall.return_value = mock_record

    # 把mock的connection对象传入业务函数,不要传字符串
    result = lambda_function.get_address_query('test', mock_connection)
    
    # 结果校验
    self.assertEqual(result, mock_record)
    # 可选补充:校验SQL执行逻辑符合预期
    mock_connection.cursor.return_value.execute.assert_called_once_with(
        "SELECT * FROM address where id = '%s' AND type = 'registered'",
        'test'
    )
额外注意事项

你的业务代码里存在逻辑错误:cursor.fetchall()永远不会返回None,如果没有匹配数据会返回空元组(),所以if address_query is None的判断永远不会触发异常,建议修改为:

if not address_query:
    raise Exception("address details do not exist")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:48:02