在搜索stackoverflow一段时间后,我找到了很多方法来检查在连接之前停靠的数据库服务是否准备就绪。所以我把他们都包括在这里。
第一个是用bash脚本编写的,我在
here
if [ "$DATABASE" = "postgres" ]
then
echo "Waiting for postgres..."
while ! nc -z $SQL_HOST $SQL_PORT; do
sleep 0.1
done
echo "PostgreSQL started"
fi
python manage.py flush --no-input
python manage.py migrate
exec "$@"
here
:
class Command(BaseCommand):
"""Django command that waits for database to be available"""
def handle(self, *args, **options):
"""Handle the command"""
self.stdout.write('Waiting for database...')
db_conn = None
while not db_conn:
try:
connection.ensure_connection()
db_conn = True
except OperationalError:
self.stdout.write('Database unavailable, waiting 1 second...')
time.sleep(1)
self.stdout.write(self.style.SUCCESS('Database available!'))
我用这个docker命令
ENTRYPOINT ["/usr/src/app/entrypoint.sh"]
跑第一个。
from unittest.mock import patch
# Use patch to to simulate db for being available or not
from django.core.management import call_command
from django.test import TestCase
class CommandTests(TestCase):
def test_wait_for_db_ready(self):
"""Test waiting for db when db is available"""
with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:
gi.return_value = True
call_command('wait_for_db')
self.assertEqual(gi.call_count, 1)
但是有谁能帮我找到为第一个(bash脚本)编写测试的方法吗?
谢谢