I wrote this test, but in order not to delay the test, I mock the time.sleep and the test will encounter an fail.
from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase
class CommandsTest(TestCase):
@patch('time.sleep', return_value=None)
def test_wait_for_db(self):
"""Test waiting for db"""
with patch('django.utils.connection.BaseConnectionHandler.__getitem__') as gi:
gi.side_effect = [OperationalError] * 5 [True]
call_command('wait_for_db')
self.assertEqual(gi.call_count, 6)
By commenting on this second line(@patch), the program will run properly. here is the error:
ERROR: test_wait_for_db (core.tests.test_commands.CommandsTest)
Test waiting for db
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python3.10/unittest/mock.py", line 1369, in patched
return func(*newargs, **newkeywargs)
TypeError: CommandsTest.test_wait_for_db() takes 1 positional argument but 2 were given
CodePudding user response:
You'll need to add an argument to your test_wait_for_db
.
Since you use a decorator, the mocked function is passed as argument to that function
class CommandsTest(TestCase):
@patch('time.sleep', return_value=None)
def test_wait_for_db(self, mocked_sleep):
In your test you can then test assert if indeed was called. More information here.