[Python] Getting Attribute error in django BaseCommand- Check

Discussão em 'Python' iniciado por Stack, Maio 30, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on a tutorial project. The same code works for the instructor but doesn't work for me.

    I have a file for custom commands:

    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!'))


    And I am writing test case for the same in a file called test_command.py which is below:

    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):
    """test waiting for db if db ready"""
    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):
    """test waiting for db when getting operational error"""
    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'])


    When I run the tests, I get an error message- AttributeError: <class 'core.management.commands.wait_for_db.Command'> does not have the attribute 'Check'

    I am unable to resolve the error.

    The structure of the files are added below:

    ![Project Structure Here] (https://ibb.co/R44Swzs0)

    Continue reading...

Compartilhe esta Página