簡體   English   中英

在 django 單元測試中出現 BadHeaderError 時引發異常的最佳方法是什么?

[英]What is the best way to raise an exception in case of BadHeaderError in django unit testing?

測試失敗並出現錯誤響應,這意味着它可能允許 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)

錯誤

文件“../tests/test_passwordreset.py”,第 55 行,在 test_exception_raised

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

斷言錯誤:200!= 400

失敗代碼

在此處輸入圖像描述

實例化HttpResponse class 時的默認 HTTP 狀態代碼為 200(正常)。 這就是您的測試失敗的原因。

嘗試這個:

...
except BadHeaderError:
    return HttpResponse('Invalid header found', status=400)
    # Or more verbose:
    # return HttpResponse('Invalid header found', status=HttpStatus.BAD_REQUEST)
...

或者

...
except BadHeaderError:
    return HttpResponseBadRequest('Invalid header found')
...

有關詳細信息,請參閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM