[英]Mocking time.sleep will cause the test to fail
我写了这个测试,但是为了不耽误测试,我模拟了time.sleep,测试会遇到失败。
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)
通过评论第二行(@patch),程序将正常运行。 这是错误:
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
您需要向您的test_wait_for_db
添加一个参数。 由于您使用装饰器,因此模拟函数作为参数传递给该函数
class CommandsTest(TestCase):
@patch('time.sleep', return_value=None)
def test_wait_for_db(self, mocked_sleep):
在您的测试中,您可以测试断言是否确实被调用。 更多信息在这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.