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

使用@patch mock time.sleep时Django测试报TypeError如何解决

报错原因

@patch装饰器执行时会自动将生成的Mock实例作为位置参数传入被装饰的测试方法,当前test_wait_for_db方法仅定义了self一个入参,无法接收这个额外传入的参数,因此触发参数数量不匹配的TypeError。

修复方案

你可以任选以下一种方式修复:

  • 方案1:给测试方法新增参数接收Mock对象
    哪怕你不需要操作这个mock的sleep对象,也必须声明对应参数接收,通常将该参数命名为mock_sleep即可,修改后代码如下:
from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase

class CommandsTest(TestCase):
    @patch('time.sleep', return_value=None)
    def test_wait_for_db(self, mock_sleep):
        """Test waiting for db"""
        with patch('django.utils.connection.BaseConnectionHandler.__getitem__') as gi:
            gi.side_effect = [OperationalError] * 5 + [True]
            call_command('wait_for_db')
            self.assertEqual(gi.call_count, 6)
  • 方案2:改用上下文管理器写法mock sleep
    和你mock数据库连接的写法保持一致,用with语句包裹mock逻辑,这种方式不会给测试方法传递额外参数,不需要修改方法定义:
from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase

class CommandsTest(TestCase):
    def test_wait_for_db(self):
        """Test waiting for db"""
        with patch('time.sleep', return_value=None):
            with patch('django.utils.connection.BaseConnectionHandler.__getitem__') as gi:
                gi.side_effect = [OperationalError] * 5 + [True]
                call_command('wait_for_db')
                self.assertEqual(gi.call_count, 6)

补充说明:如果修复参数问题后发现mock sleep不生效、测试仍存在等待耗时,需要检查wait_for_db命令代码中导入sleep的方式:@patch的路径必须和被测试代码中sleep的引用路径完全一致。如果命令中是用from time import sleep导入的,需要将patch路径改为对应命令模块下的sleep路径,例如core.management.commands.wait_for_db.sleep。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 22:12:28