[英]What is the best way to raise an exception in case of BadHeaderError in django unit testing?
Tests fail with an error response meaning that it is likely to be allowing email with wrong data and yet it should throw an HttpResponse as expected, I have tried to figure it out why my test is failing and returning 200 http status code but not as expected = 400.测试失败并出现错误响应,这意味着它可能允许 email 使用错误数据,但它应该按预期抛出 HttpResponse,我试图弄清楚为什么我的测试失败并返回 200 http 状态代码但不是预期的= 400。
class ResetPassword(View):
form_class = ForgetPasswordForm()
template_name = 'authentication/password_reset.html'
def get(self, request):
form = self.form_class
return render(request, self.template_name, {'form': form})
def post(self, request):
msg = None
form = ForgetPasswordForm(request.POST)
if form.is_valid():
data = form.cleaned_data.get('email')
associated_users = Users.objects.filter(Q(email = data))
if associated_users.exists():
for user in associated_users:
subject = 'Password Reset Requested'
email_template_name = "authentication/password_reset_email.txt"
c = {
"email": user.email,
'domain': '127.0.0.1:8000',
'site_name': 'ATB Project Organizer',
'uid': urlsafe_base64_encode(force_bytes(user.pk)),
'user': user,
'token': default_token_generator.make_token(user),
'protocol': 'http',
}
email = render_to_string(email_template_name, c)
try:
send_mail(subject, email, 'admin@example.com', [user.email], fail_silently=False)
except BadHeaderError:
return HttpResponse('Invalid header found')
msg = 'You have successfully reset your password!'
return redirect('/password_reset/done/')
else:
msg = 'No records found for this email, please make sure you have entered the correct email address!'
form = ForgetPasswordForm()
return render(request, 'authentication/password_reset.html', {'form': form, 'msg': msg})
from django.test import TestCase
from django.urls import reverse
from django.core import mail
from django.contrib.auth import get_user_model
User = get_user_model()
class PasswordResetTest(TestCase):
def setUp(self):
self.user1 = User.objects.create_user("user1", email = "user1@mail.com", password = "password@121", orcid = '1234567890987654')
self.user2 = User.objects.create_user("user2", email = "user2@mail.com", password = "password@122", orcid = '1234567890987655')
self.user3 = User.objects.create_user("user3@mail.com", email = "not-that-mail@mail.com", password = "password@123", orcid = '1234567890987656')
self.user4 = User.objects.create_user("user4", email = "user4@mail.com", password = "passs", orcid = '1234567890987657')
self.user5 = User.objects.create_user("user5", email = "uѕer5@mail.com", password = "password@125", orcid = '1234567890987658') # email contains kyrillic s
self.user={
'username':'username',
'email':'testemail@gmail.com',
'password1':'password@123',
'password2':'password@123',
'orcid': '1234123412341239',
}
def test_user_can_resetpassword(self):
response = self.client.get(reverse('resetpassword'))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'authentication/password_reset.html')
# Then test that the user doesn't have an "email address" and so is not registered
response = self.client.post(reverse('resetpassword'), {'email': 'admin@example.com'}, follow=True)
self.assertEqual(response.status_code, 200)
# Then test that the user doesn't have an "email address" and so is not registered
# Then post the response with our "email address"
# Then post the response with our "email address"
response = self.client.post(reverse('resetpassword'),{'email':'user1@mail.com'})
self.assertEqual(response.status_code, 302)
# At this point the system will "send" us an email. We can "check" it thusly:
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(mail.outbox[0].subject, 'Password Reset Requested')
def test_exception_raised(self):
# verify the email with wrong data
data = {"uid": "wrong-uid", "token": "wrong-token"}
response = self.client.post(reverse('resetpassword'), data, format='text/html')
self.assertEqual(response.status_code, 400)
File "../tests/test_passwordreset.py", line 55, in test_exception_raised文件“../tests/test_passwordreset.py”,第 55 行,在 test_exception_raised
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
AssertionError: 200 != 400断言错误:200!= 400
The default HTTP status code when you instantiate the HttpResponse
class is 200 (OK).实例化
HttpResponse
class 时的默认 HTTP 状态代码为 200(正常)。 This is why your test fails.这就是您的测试失败的原因。
Try this:尝试这个:
...
except BadHeaderError:
return HttpResponse('Invalid header found', status=400)
# Or more verbose:
# return HttpResponse('Invalid header found', status=HttpStatus.BAD_REQUEST)
...
or或者
...
except BadHeaderError:
return HttpResponseBadRequest('Invalid header found')
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.