django 使用RequestFactory()时测试消息

v1l68za4  于 2022-11-26  发布在  Go
关注(0)|答案(1)|浏览(122)

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

检视

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': 'test@test.com', '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/')

我的问题是,如何检索消息,以便可以针对消息生成assertEqual:“出现错误,请尝试重新注册”?

eagi6jfj

eagi6jfj1#

深入挖掘后,可以在此处找到消息:

request._messages._queued_messages[0]

因此,assertEqual将是:

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

相关问题