Skip to content

Commit

Permalink
Implemented wait_for_db command and tests for it.
Browse files Browse the repository at this point in the history
  • Loading branch information
ArtemVasylchuck committed Jul 25, 2023
1 parent 900cc54 commit 3497a99
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 5 deletions.
2 changes: 1 addition & 1 deletion app/core/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from django.contrib import admin
from django.contrib import admin # noqa

# Register your models here.
18 changes: 17 additions & 1 deletion app/core/management/commands/wait_for_db.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,27 @@
"""
Django command to wait for the database to be available.
"""
import time

from psycopg2 import OperationalError as Psycopg2Error

from django.db.utils import OperationalError
from django.core.management.base import BaseCommand


class Command(BaseCommand):
"""Django command to wait the database."""

def handle(self, *args, **options):
pass
"""Entrypoint for command."""
self.stdout.write('Waiting for database...')
db_up = False
while db_up is False:
try:
self.check(databases=['default'])
db_up = True
except (Psycopg2Error, OperationalError):
self.stdout.write('Database unavailable, waiting 1 second...')
time.sleep(1)

self.stdout.write(self.style.SUCCESS('Database available!'))
2 changes: 1 addition & 1 deletion app/core/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from django.db import models
from django.db import models # noqa

# Create your models here.
4 changes: 2 additions & 2 deletions app/core/tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ 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(database=['default'])
patched_check.assert_called_once_with(databases=['default'])

@patch('time.sleep')
def test_wait_for_db_delay(self, patched_sleep, patched_check):
Expand All @@ -30,4 +30,4 @@ def test_wait_for_db_delay(self, patched_sleep, patched_check):
call_command('wait_for_db')

self.assertEqual(patched_check.call_count, 6)
patched_check.assert_called_with(database=['default'])
patched_check.assert_called_with(databases=['default'])

0 comments on commit 3497a99

Please sign in to comment.