【问题标题】:Test UpdateView for useraccounts application测试用户帐户应用程序的 UpdateView
【发布时间】:2019-08-07 09:38:12
【问题描述】:

测试没有在用户配置文件 UpdateView 中提供 status_code 302,因此对象上没有发生更新 型号代码

class User(AbstractBaseUser, PermissionsMixin):
    '''
    This a replaced user profile instead of the default django one
    '''
    language_choices=[('en',_('English')),('se',_('Swedish'))]

    email=models.CharField(verbose_name=_('Email'), max_length=128, blank=False, unique=True)
    first_name=models.CharField(verbose_name=_('First Name'), max_length=128)
    last_name=models.CharField(verbose_name=_('Last Name'), max_length=128)
    joined_at=models.DateField(
                                verbose_name=_('Joined at'),
                                auto_now_add=True,
                                blank=False
                                )
    language=models.CharField(
                            verbose_name=_('Language'),
                            max_length=2,
                            choices=language_choices,
                            default=language_choices[0][0]
                            )
    active=models.BooleanField(verbose_name=_('Active'), default=False)
    is_superuser=models.BooleanField(verbose_name=_('Is Superuser'), default=False)
    is_active=models.BooleanField(verbose_name=_('Is Active'), default=True)
    is_staff=models.BooleanField(verbose_name=_('Is Staff'), default=False)

表格代码

class EditUserForm(UserChangeForm):
    '''
    Profile form to update existing user information
    '''
    # error message for email matches
    error_messages = {
        'email_mismatch': _("The two email fields didn't match."),
        }
    # create field for email
    email1 = forms.EmailField(
        label=_("Email"),
        widget=forms.EmailInput,
        help_text=_("If you change your email your account will be inactive untill your reactivate by email link."),
    )
    # get the email from confirmed email field
    email2 = forms.EmailField(
        label=_("Confirm Email"),
        widget=forms.EmailInput,
        help_text=_("Enter the same email as before, for verification."),
    )
    # hide password field
    password = ReadOnlyPasswordHashField(label="Password")

    class Meta:
        '''
        Initial fields and model for the form
        '''
        model = models.User
        fields = ('first_name','last_name','email1','email2', 'language')

    def clean_email2(self):
        '''
        Method for if email and confirmed email are the same
        This method works when confirmed email cleared
        '''
        # get the email from email field
        email1 = self.cleaned_data.get("email1")
        # get the email from confirmed email field
        email2 = self.cleaned_data.get("email2")
        # check if both emails are equal
        if email1 and email2 and BaseUserManager.normalize_email(email1) != BaseUserManager.normalize_email(email2):
            # give an error message if emails not matches
            raise forms.ValidationError(
                self.error_messages['email_mismatch'],
                code='email_mismatch')
        # return the confirmed email
        return BaseUserManager.normalize_email(email2)

    def save(self, commit=True):
        '''
        Method tosave the edited user data
        '''
        # get the initial method
        user = super().save(commit=False)
        # set the email on the model field
        user.email = self.cleaned_data["email1"]
        # save edited user data
        if commit:
            user.save()
        return user

    def __init__(self, *args, **kwargs):
        '''
        Method for initial values and functions for the SignUp form class
        '''
        # get user data from User model
        user = get_user_model().objects.get(email=kwargs['instance'])
        # get the initial form class values
        super(EditUserForm, self).__init__(*args, **kwargs)
        # Add the current email as the inital email
        self.fields['email1'].initial = user.email
        # Add the current email as the intial confirmed email
        self.fields['email2'].initial = user.email
        # Add help text in the password field for change
        self.fields['password'].help_text=(
                    _("Raw passwords are not stored, so there is no way to see "
                    "this user's password, but you can change the password "
                    "using <a href=\"{0}\">this form</a>.")
                    .format(reverse(
                        'core:ChangePassword',
                        kwargs={'pk':user.pk})))

以及查看代码

class EditUser(UserPassesTestMixin, UpdateView):
    '''
    Class view to update user details
    '''
    # used template
    template_name = 'core/edit.html'
    # View model
    model = models.User
    # View form
    form_class = forms.EditUserForm

    def test_func(self):
        return self.request.user == get_user_model().objects.get(pk=self.kwargs['pk'])

    def get_success_url(self):
        '''
        Metho to redirect after a valid form
        '''
        # check if the email is verified
        if self.request.user.active:
            # get the user key
            pk=self.request.user.pk
            # redirect to profile details
            return reverse_lazy('core:details', kwargs={'pk':pk})
        else:
            # send a verification email
            return SendActivationEmail(self.request, self.request.user)

测试代码

   self.viewuser_url = reverse('core:details', kwargs={'pk':self.user.pk})
   self.edituser_url = reverse('core:edit', kwargs={'pk':self.user.pk})

def test_edit_user_post(self):
        first_name = 'Osama'
        response = self.client.post(self.edituser_url,
            data={
                'first_name': first_name,
                'last_name': self.last_name,
                'email': self.email,
                })

        self.assertRedirects(response, self.viewuser_url)

        self.user.refresh_from_db()

        self.assertEqual(self.user.first_name, first_name)

我尝试为状态代码获取 assertEqual,它给我 200 而不是 302

我也尝试输入表单详细信息而不是模型详细信息,它给了我一个错误

get 测试运行良好,权限测试也运行良好。所有模型、表单和 url 测试都运行良好。

我不知道如何测试这个..

【问题讨论】:

    标签: django django-views


    【解决方案1】:

    如果表单无效,则表单将重新呈现并出现错误,您将收到 200 响应。

    要调试问题,请检查您的测试中的response.context['form'].errors 以了解问题所在。

        response = self.client.post(self.edituser_url,
            data={
                'first_name': first_name,
                'last_name': self.last_name,
                'email': self.email,
                })
        print(response.context['form'].errors
    

    您的视图使用EditUserForm,但您没有发布任何email1email2 的值,因此错误中可能存在有关缺失数据的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      • 2023-03-26
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多