Skip to content

Commit

Permalink
db test 2 failure
Browse files Browse the repository at this point in the history
  • Loading branch information
felix1110xx committed Jul 15, 2024
1 parent 64f66d7 commit 48cf624
Show file tree
Hide file tree
Showing 8 changed files with 52 additions and 6 deletions.
1 change: 1 addition & 0 deletions app/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core'
]

MIDDLEWARE = [
Expand Down
Empty file added app/core/management/__init__.py
Empty file.
Empty file.
23 changes: 23 additions & 0 deletions app/core/management/commands/wait_for_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
Django command to wait for the db to be available.
"""
import time
from django.core.management.base import BaseCommand
from psycopg2 import OperationalError as Psycopg2OpError
from django.db.utils import OperationalError


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!'))
3 changes: 0 additions & 3 deletions app/core/tests.py

This file was deleted.

Empty file added app/core/tests/__init__.py
Empty file.
28 changes: 28 additions & 0 deletions app/core/tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
"""
Test Django management commands.
"""
from unittest.mock import patch

from psycopg2 import OperationalError as Psycopg2Error

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 when db is available"""
patched_check.return_value = True
call_command('wait_for_db')
patched_check.assert_called_once_with(database=['default'])

@patch('time.sleep')
def test_wait_for_db_delay(self, patched_sleep, patched_check):
"""Test waiting for db when getting OperationalError"""
patched_check.side_effect = [Psycopg2Error] * 2 + \
[OperationalError] * 3 + [True]
call_command('wait_for_db')
self.assertEqual(patched_check.call_count, 6)
patched_check.assert_called_with(database=['default'])
3 changes: 0 additions & 3 deletions app/core/views.py

This file was deleted.

0 comments on commit 48cf624

Please sign in to comment.