0

我正在努力寻找测试 FormView 的正确方法。我想检查当用户未通过身份验证时是否呈现消息(通过 django.contrib.messages 生成)。我已经阅读了有关 RequestFactory、Client、Mock、Middleware 的信息,但我无法在 CBV FormView 中实现此测试。

问题不在于特别是对用户进行身份验证,我想使用其他领域的逻辑来测试其他消息。

这是我的代码:

看法:

class MyView(FormView):

    form_class = MyForm
    template_name = 'app/welcome_template.html'
    
    def form_valid(self, form):
        form_data = form.cleaned_data
        auth = LDAPBackend() 
        user = auth.authenticate(self.request, username=form_data['login_field'], password=form_data['password_field'])
                

        if user:
           return super(MyView, self).form_valid(form)
        else:
            messages.add_message(self.request, messages.WARNING, 'some warning' + str(form_data['other_field']))
            return self.form_invalid(form)

形式:

class MyForm(forms.Form):
   
    login_field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Login', 'class': 'form-control form-control-sm'}), 
                                 label='Login:', max_length=20)
    password_field = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control form-control-sm'}), 
                                    label='Password:', max_length=20)
    other_field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Select ...', 
                                                            'class': 'form-control form-control-sm',
                                                            'max': '99999999'}), 
                              label='Other:')

模板:

<form autocomplete="off" onsubmit="$('#ModalCenter').modal({backdrop: 'static', keyboard: false})" action="." target="_top" method="post">
{% csrf_token %}
            <div class="row">
                <div>
                  {% if messages %}
                        {% for message in messages %}
                        <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div>
                        {% endfor %}
                    {% endif %}
                </div>
                <div class="form-group mt-2">
                    {{ form.login_field.label_tag }}
                    {{ form.login_field }}     
                </div>
                <div class="form-group mt-2">
                    {{ form.password_field.label_tag }}
                    {{ form.password_field }}
                </div>
                <div class="form-group autocomplete mt-2">
                    {{ form.other_field.label_tag }}
                    {{ form.other_field }}
                </div>
            
                <button type="submit" class="btn btn-primary mb-2 btnexecute" id="submitbutton">Run</button>
            </div>
        </form>

当我使用这个测试时,消息列表总是空的:

from django.test import TestCase, RequestFactory, Client
from django.urls import reverse
from .views import MyView
from caf.settings import V_USER, V_PWD
from django.contrib.messages import get_messages

class MyViewTestCase(TestCase):

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

    def test_message(self):

        input_data = {'login_field': V_USER,
                      'password_field': V_PWD,
                      'other_field': 'other...'}
        
        request = self.factory.post(reverse('welcome_template'), data=input_data, follow=True)
        response = MyView.as_view()(request)

        print(len(get_messages(response.wsgi_request)))
        print(len(response.context['messages']))

我会很感激任何帮助。

提前致谢。

4

0 回答 0