如何解决如何测试基于类的 FormView 的 Django 消息?
我正在努力寻找测试 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',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']))
我将不胜感激。
提前致谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。