我正在上关于Django的在线课程。在这门课程中,我将我的项目与Postgresql数据库连接起来。如果我的Django应用程序在Postgresql数据库启动之前启动,我们写一个命令延迟应用程序的启动,直到Postgresql启动。下面是命令代码:
from psycopg2 import OperationalError as Psycopg2OpError
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
""" 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(Psycopg2OpError, OperationalError):
self.stdout.write('Database unavailable, waiting for 1 second...')
time.sleep(1)
self.stdout.write(self.style.SUCCESS('Database available!'))
但是我不理解测试这个命令是否有效的测试代码。你能解释一下这些代码的逻辑吗?
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 is 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"""
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(databases=['default'])
test utils的背景
所以你正在创建一个你想要执行的自定义命令。在命令中,调用函数check
(参见文档)。
patch
。(见文档)如果用作装饰器,该补丁将被注入构造函数或函数参数。对于您的情况,patched_check
。您的patched_check
现在充当check
函数的模拟。
测试用例在做什么?test_wait_for_db_ready(self, patched_check)
验证self.check
被参数databases=['default']
调用一次。
test_wait_for_db_delay
验证如果self.check
抛出异常,则time.sleep(1)
被调用6次。
我面临同样的问题,请检查您的数据库环境变量在docker-compose。yml文件。您没有正确配置任何数据库环境变量。