使用RequestFactory()时测试消息

问题描述 投票:0回答:2

我正在使用模拟测试基于类的视图以引发异常。 出现异常时,应创建一条消息,然后执行重定向。 虽然我能够测试重定向是否已执行,但我还无法检索消息来验证它。

查看

CustomUser = get_user_model()

class SignUpView(FormView):
    template_name = 'accounts/signup.html'
    form_class = SignUpForm

    def form_valid(self, form):

        try:
            self.user = CustomUser.objects.filter(email=form.cleaned_data['email']).first()

            if not self.user:

                self.user = CustomUser.objects.create_user(email=form.cleaned_data['email'],
                                                           full_name=form.cleaned_data['full_name'],
                                                           password=form.cleaned_data['password'],
                                                           is_verified=False
                                                           )
            else:
                if self.user.is_verified:

                    self.send_reminder()

                    return super().form_valid(form)

            self.send_code()
        except:
            messages.error(self.request, _('Something went wrong, please try to register again'))
            return redirect(reverse('accounts:signup'))

        return super().form_valid(form)

到目前为止我的测试:

class SignUpViewTest(TestCase):

    def setUp(self):
        self.factory = RequestFactory()

    def test_database_fail(self):
        with patch.object(CustomUserManager, 'create_user') as mock_method:
            mock_method.side_effect = Exception(ValueError)

            view = SignUpView.as_view()
            url = reverse('accounts:signup')
            data = {'email': '[email protected]', 'full_name': 'Test Tester', 'password': 'Abnm1234'}
            request = self.factory.post(url, data)
            setattr(request, 'session', 'session')
            messages = FallbackStorage(request)
            request._messages = messages

            response = view(request)

            self.assertEqual(response.status_code, 302)
            self.assertEqual(response.url, '/accounts/signup/')
           

我的问题是,如何检索消息,以便我可以针对消息进行断言:“出现问题,请尝试重新注册”?

python django django-forms mocking django-testing
2个回答
0
投票

深入挖掘后,可以在这里找到消息:

request._messages._queued_messages[0]

因此,assertEqual 将是:

self.assertEqual(str(request._messages._queued_messages[0]), 'Something went wrong, please try to register again')

0
投票

深入挖掘后,可以在这里找到消息:

request._messages._queued_messages[0]
因此 断言Equal将是:
self.assertEqual(str(request._messages._queued_messages[0]), 'Something went wrong, please try to register again')

这看起来有点hacky,经过几个小时的研究,我发现了一种稍微更强大的方法来实现测试视图生成的用户消息的方法(消息的数量,最后生成的/唯一的消息中存在某些字符串,每个生成的消息中存在特定字符串):

from django.contrib.messages import get_messages

self.assertEqual(len(get_messages(request)), expected_nb_messages)


user_messages_sent = [str(i) for i in get_messages(request)] 
# the resulting BaseStorage class has an iterator method
# string conversion is needed to access to the actual text of the Message object 
           
if type(text_to_test_in_message)==dict:
   for k,v in text_to_test_in_message.items():
       self.assertIn(v, user_messages_sent[k])
   else:
       self.assertIn(text_to_test_in_message, user_messages_sent[-1])
© www.soinside.com 2019 - 2024. All rights reserved.