Skip to content

Commit

Permalink
Configuration added to wait for database.
Browse files Browse the repository at this point in the history
  • Loading branch information
jpaos committed Jul 19, 2024
1 parent 90da814 commit 51f5d10
Show file tree
Hide file tree
Showing 17 changed files with 153 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@v2
- 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"
4 changes: 4 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,15 @@ EXPOSE 8000
ARG DEV=false
RUN python -m venv /py && \
/py/bin/pip install --upgrade pip && \
apk add --update --no-cache postgresql-client && \
apk add --update --no-cache --virtual .tmp-build-deps \
build-base postgresql-dev musl-dev && \
/py/bin/pip install -r /tmp/requirements.txt && \
if [ $DEV = "true" ]; \
then /py/bin/pip install -r /tmp/requirements.dev.txt ; \
fi && \
rm -rf /tmp && \
apk del .tmp-build-deps && \
adduser \
--disabled-password \
--no-create-home \
Expand Down
13 changes: 13 additions & 0 deletions app/app/calc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""
Calculator functions
"""


def add(x, y):
"""Add x and y and return result."""
return x + y


def subtract(x, y):
""" Subtract x from y and return result."""
return y - x
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/3.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
22 changes: 22 additions & 0 deletions app/app/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""
Sample tests
"""
from django.test import SimpleTestCase

from app import calc


class CalcTests(SimpleTestCase):
"""Test the calc module"""

def test_add_numbers(self):
"""Test adding numbers together."""
res = calc.add(5, 6)

self.assertEqual(res, 11)

def test_subtract_numbers(self):
"""Test subtracting numbers."""
res = calc.subtract(10, 15)

self.assertEqual(res, 5)
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 # noqa

# 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 Psycopg2OpError

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


class Command(BaseCommand):
"""Base command to wait for the database."""
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!'))
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 # noqa

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

def test_wait_for_db_ready(self, patched_check):
"""Test waiting for database if database 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 database when getting OperationalError."""

"""
This is the way we throw exceptions instead of returning a
simple value (True of False). Recall that patch is simulating the
behaviour of the connection to the database.
"""
patched_check.side_effect = [Psycopg2Error] * 2 + \
[OperationalError] * 3 + [True]

call_command('wait_for_db')

"""
We expect to call the method 6 times until we get a True.
That's defined in patched_check list.
"""
self.assertEqual(patched_check.call_count, 6)

patched_check.assert_called_with(databases=['default'])
24 changes: 23 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,27 @@ 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
- DB_USER=devuser
- DB_PASS=changeme
depends_on:
- db

db:
image: postgres:13-alpine
volumes:
- dev-db-data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=devdb
- POSTGRES_USER=devuser
- POSTGRES_PASSWORD=changeme



volumes:
dev-db-data:
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
Django>=3.2.4,<3.3
djangorestframework>=3.12.4,<3.13
psycopg2>=2.8.6,<2.9

0 comments on commit 51f5d10

Please sign in to comment.