Django BaseCommand属性错误:自定义命令测试报AttributeError
解决Django自定义命令测试中的AttributeError问题
我跟着教程开发Django项目,教程代码能正常运行,但我的代码出问题了。我编写了一个等待数据库就绪的自定义命令,同时写了对应的测试用例,运行测试时触发了AttributeError。
自定义命令代码(wait_for_db.py)
import time from psycopg2 import OperationalError as Psycopg2OpError from django.db.utils import OperationalError from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write('waiting for database...') db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except(Psycopg2OpError, OperationalError): self.stdout.write("Database unavailable, waiting 1 second...") time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!'))
测试用例代码(test_command.py)
from unittest.mock import patch from psycopg2 import OperationalError as Psycopg2OpError from django.core.management import call_command from django.db.utils import OperationalError from django.test import SimpleTestCase @patch('core.management.commands.wait_for_db.Command.Check') class CommandTests(SimpleTestCase): def test_wait_for_db_ready(self, patched_check): """测试数据库就绪时的等待逻辑""" patched_check.return_value = True call_command('wait_for_db') patched_check.assert_called_once_with(databases=['default']) @patch('time.sleep') def test_wait_for_db_delay(self, patched_sleep, patched_check): """测试数据库不可用时的等待重试逻辑""" patched_check.side_effect = [Psycopg2OpError] * 2 + \ [OperationalError] * 3 + [True] call_command('wait_for_db') self.assertEqual(patched_check.call_count, 6) patched_check.assert_called_with(databases=['default'])
报错信息
AttributeError: <class 'core.management.commands.wait_for_db.Command'> does not have the attribute 'Check'
文件结构

修复方案
问题根源是测试用例的patch路径错误:
- 代码中调用的是实例方法
self.check(小写c),但你在patch时写的是Command.Check(大写C),该类本身没有名为Check的属性。
修改测试用例的patch装饰器,将路径改为正确的实例方法路径:
@patch('core.management.commands.wait_for_db.Command.check')
修改后重新运行测试,该错误即可解决。
内容的提问来源于stack exchange,提问作者The Bat
相关产品推荐
相关产品推荐

