mock.call 返回 False 什么时候应该返回 True

时间:2021-03-08 19:37:54

标签: python python-3.x django unit-testing signals

我有一个在保存用户时调用的信号,并对此信号进行测试:

from django.db.models.signals import post_save
from django.dispatch import receiver
from notifications.signals import notify


@receiver(post_save, sender='users.User', dispatch_uid='Testing_post_save')
def testing_notification_signal(sender, instance, **kwargs):
    notify.send(verb='was saved', sender=sender, recipient=instance)
from unittest import TestCase
from unittest.mock import patch

from users.models import User


class SignalsTestCase(TestCase):

    def setUp(self):
        self.user = User(
            email='testing@example.com',
            first_name='test',
            last_name='test',
            username='test123'
        )

        self.user.save()


    @patch('notifications_center.notifications.signals.testing_notification_signal')
    def test_if_signals_test_is_being_called(self, mock):

        self.assertTrue(mock.called)
        self.assertEqual(mock.call_count, 1)

我的测试为断言返回 False,但如果我将打印内容放入信号中,则正在调用函数信号。为什么会这样?我怎样才能让这个测试通过?

------ 更新

我在测试中进行了一些更改,现在它通过了:

from unittest import TestCase
from unittest.mock import patch

from users.models import User


class SignalsTestCase(TestCase):

    def setUp(self):
        self.user = User(
            email='testing@example.com',
            first_name='test',
            last_name='test',
            username='test123'
        )

        self.user.save()

    @patch('notifications_center.notifications.signals.testing_notification_signal')
    def test_if_signals_test_is_being_called(self, mock_signal):

        self.assertTrue(mock_signal.connect)

        with patch('notifications.signals.notify.send') as mock_notify:

            self.assertTrue(mock_notify.connect)

使用连接方法测试信号是否正确?

0 个答案:

没有答案