我正在上一门关于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'])
1条答案
按热度按时间xytpbqjk1#
测试实用程序的背景
所以你要创建一个你想要执行的自定义命令,在你的命令中,你调用函数
check
(见文档)。关于您的测试用例。您正在执行2个测试场景。但在运行测试之前,您提供了一个
patch
。(请参阅文档)这个补丁--如果用作装饰器--将被注入到构造函数或函数参数中。对于你的情况
patched_check
。你的patched_check
现在作为你的check
函数的一个模拟。测试用例在做什么?
test_wait_for_db_ready(self, patched_check)
验证是否使用参数databases=['default']
调用了self.check
,且仅调用一次。test_wait_for_db_delay
验证如果self.check
引发异常,则time.sleep(1)
被调用6次。