You need to enable JavaScript to run this app. Python使用mockito测试时Mock类触发AttributeError问题求解
优惠活动
大模型
产品
解决方案
定价
更多

Python使用mockito测试时Mock类触发AttributeError问题求解

问题排查与解决

报错根因分析

  • 第一个AttributeError: 'NoneType' object has no attribute 'last_modified'报错原因:
    你没有对mock_bucket.Object()方法做返回值桩,mockito对未声明桩的方法默认返回None。业务代码中last_modified是self.bucket.Object(cache_file)返回的S3对象的属性,而非bucket本身的属性,你之前将last_modified赋值给mock_bucket属于赋值对象错误,因此访问None对象的属性触发报错。
  • 第二个AttributeError: 'StubbedInvocation' object has no attribute 'thenReturn'报错原因:
    mockito-python中直接给mock对象的属性赋值即可生效,不需要用when(xxx).属性.thenReturn的写法。该写法仅适用于方法桩的声明,用于属性桩时会返回非法的StubbedInvocation对象,触发属性不存在报错。

修复后的测试代码

以下代码覆盖了缓存过期、缓存未过期两种测试场景:

from mockito import mock, when, verify
import datetime
import boto3

import mock_cache

class TestMockCache:
    def test_cache_outdated(self):
        # 模拟缓存过期场景:last_modified早于当前时间,触发下载
        mock_client = mock()
        when(boto3).resource('s3').thenReturn(mock_client)

        mock_bucket = mock()
        when(mock_client).Bucket('name').thenReturn(mock_bucket)

        # 构造mock S3对象,设置过期的last_modified
        mock_cache_obj = mock()
        mock_cache_obj.last_modified = datetime.datetime.now() - datetime.timedelta(hours=1)
        # 给bucket.Object方法打桩,传入默认cache.csv参数时返回构造的mock对象
        when(mock_bucket).Object('cache.csv').thenReturn(mock_cache_obj)
        # 给download_file打桩,避免真实调用S3接口
        when(mock_bucket).download_file('cache', 'cache.csv').thenReturn(None)

        mock_cache.main()
        # 验证下载方法被调用1次
        verify(mock_bucket, times=1).download_file('cache', 'cache.csv')

    def test_cache_updated(self):
        # 模拟缓存未过期场景:last_modified晚于当前时间,不触发下载
        mock_client = mock()
        when(boto3).resource('s3').thenReturn(mock_client)

        mock_bucket = mock()
        when(mock_client).Bucket('name').thenReturn(mock_bucket)

        # 构造mock S3对象,设置未过期的last_modified
        mock_cache_obj = mock()
        mock_cache_obj.last_modified = datetime.datetime.now() + datetime.timedelta(hours=1)
        when(mock_bucket).Object('cache.csv').thenReturn(mock_cache_obj)

        mock_cache.main()
        # 验证下载方法未被调用
        verify(mock_bucket, times=0).download_file('cache', 'cache.csv')

额外注意点

如果需要更严格的时间控制,避免测试时的毫秒级时间差导致的用例不稳定,可以将datetime.datetime.now()也打桩固定返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:39:03