Skip to content

Commit

Permalink
Update docker-compose and checks to wait for db to start up
Browse files Browse the repository at this point in the history
  • Loading branch information
marcintomiczek committed Dec 20, 2023
1 parent 3a83349 commit 255e618
Show file tree
Hide file tree
Showing 13 changed files with 79 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Test
run: docker-compose run --rm app sh -c "python manage.py test"
run: docker-compose run --rm app sh -c "python manage.py wait_for_db && python manage.py test"
- name: Lint
run: docker-compose run --rm app sh -c "flake8"
9 changes: 7 additions & 2 deletions app/app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
Expand Down Expand Up @@ -37,6 +38,7 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core',
]

MIDDLEWARE = [
Expand Down Expand Up @@ -75,8 +77,11 @@

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
'ENGINE': 'django.db.backends.postgresql',
'HOST': os.environ.get('DB_HOST'),
'NAME': os.environ.get('DB_NAME'),
'USER': os.environ.get('DB_USER'),
'PASSWORD': os.environ.get('DB_PASS'),
}
}

Expand Down
Empty file added app/core/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions app/core/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
6 changes: 6 additions & 0 deletions app/core/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class CoreConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'core'
Empty file added app/core/management/__init__.py
Empty file.
Empty file.
24 changes: 24 additions & 0 deletions app/core/management/commands/wait_for_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""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 for database."""

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

self.stdout.write(self.style.SUCCESS("Database available!"))
Empty file added app/core/migrations/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions app/core/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.db import models

# Create your models here.
Empty file added app/core/tests/__init__.py
Empty file.
32 changes: 32 additions & 0 deletions app/core/tests/test_commands.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Test custom 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):
"""Test commands."""

def test_wait_for_db_ready(self, check):
"""Test waiting for database if database ready."""
check.return_value = True

call_command("wait_for_db")

check.assert_called_once_with(databases=['default'])

def test_wait_for_db_delay(self, check):
"""Test waiting for database when getting OperationalError."""
check.side_effect = (
[Psycopg2Error] * 2 + [OperationalError] * 3 + [True]
)

with patch("time.sleep"):
call_command("wait_for_db")

self.assertEquals(check.call_count, 6)
check.assert_called_with(databases=['default'])
4 changes: 3 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ services:
volumes:
- ./app:/app
command: >
sh -c "python manage.py runserver 0.0.0.0:8000"
sh -c "python manage.py wait_for_db &&
python manage.py migrate &&
python manage.py runserver 0.0.0.0:8000"
environment:
- DB_HOST=db
- DB_NAME=devdb
Expand Down

0 comments on commit 255e618

Please sign in to comment.