0

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:

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

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:

enter image description here

3
  • 1
    shouldnt this wait_for_db.Command.Check be wait_for_db.Command.check Commented May 30 at 6:49
  • 1
    Unless .Check is created by yourself, it should be .check (github.com/django/django/blob/main/django/core/management/… Commented May 30 at 7:10
  • I am an idiot and that was a stupid mistake. Thank you guys @Exprator and @shaik moeed. It works fine when I use check Commented May 30 at 11:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.