微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的测试功能无法激活用户?

如何解决为什么我的测试功能无法激活用户?

我有一个django电子邮件验证应用程序,该应用程序发送带有包含已编码用户pk和令牌的激活网址的电子邮件,然后当该应用程序接收到网址中的正确数据时,它将user.is_active布尔值设置为True 。我编写了一个应该创建用户并发送带有编码的pk和令牌的get请求的测试,但是即使url正确,它也无法激活我的用户(如下所示)

views.py 包含注册功能和基于验证类别的视图。

def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            #  ... process form data
            user.save()

            # Verification
            email_subject = 'Activate your followerr account'
            domain = get_current_site(request).domain
            user_id = urlsafe_base64_encode(force_bytes(user.pk))
            link = reverse('activate',kwargs={
                'user_id': user_id,'token': token_generator.make_token(user),})
            activate_url = 'http://' + domain + link
            email_body = 'Hello ' + user.name + \
                     ' please use this link to verify your account\n' + activate_url
            email = EmailMessage(
                email_subject,email_body,'noreply@domain.com',[user.email],)
            email.send()
            return redirect('login')
    else:
        form = SignupForm()
    return render(request,'signup.html',{'form': form})


class VerificationView(View):
    def get(self,request,user_id,token):
        try:
            id = urlsafe_base64_decode(force_text(user_id))
            user = User.objects.get(pk=id)

            if not token_generator.check_token(user,token):
                return HttpResponse('login Failed')
            if user.is_active:
                return redirect('login')
            user.is_active = True
            user.save()
            return redirect('login')
        except Exception as ex:
            pass
        return redirect('login')

在我的测试中,我创建了一个具有发帖请求的新用户,并检查电子邮件是否存在,然后我从发件箱中的唯一电子邮件获取令牌(我确定这不是最好的方法,但是可以正常使用现在),获取user_id并将其编码为url,然后向该视图发送一个get请求,该视图应查找具有user_id的用户,查看令牌是否与该用户匹配,并将user.is_active设置为True重定向login页,但是在完成所有这些操作后,我的user.is_active值仍然保持False。这是测试:

tests.py

def test_signup_email_confirmation(self):
            response = self.client.post('/signup/',data={'email': 'test1@gmail.com','name': 'test1','gender': True,'password1': 'test1','password2': 'test1'},follow=True)
    self.assertEqual(len(mail.outBox),1)

    for i in mail.outBox:
        token = i.body.split(' ')[-1]
        print(i.body) #  <-- the entire email body with the activation url
    token = token[38:-1]
    user = User.objects.get(email='test1@gmail.com')
    user_id = urlsafe_base64_encode(force_bytes(user.pk))

    activation_url = reverse('activate',kwargs={'user_id': user_id,'token': token})
    activation_url = 'http://testserver' + activation_url
    res = self.client.get(activation_url,follow=True)

    print(activation_url) 
    print(token_generator.check_token(user,token))
    print(res.status_code)
    print(user.is_active)

    self.assertEqual(res.status_code,200)
    self.assertRedirects(response,'/login/')

我已经尝试使用activation_url部分的'http://testserver'

打印语句的结果在这里

Hello test1 please use this link to verify your account
http://testserver/activate/Mg/ad1ap1-887a3ff4466d2e1d098603ddad24355e/
http://testserver/activate/Mg/ad1ap1-887a3ff4466d2e1d098603ddad24355e/
200
True
False

您可以看到url的匹配项,但is_active的值仍然为False

解决方法

发生这种情况的原因是,您的测试类中的user对象是在is_activeFalse时从数据库加载的。当视图设置is_active=True并保存用户时,测试方法无法知道实例已被修改。

因此,现在测试方法中的user实例仍然具有旧值。

如果要测试修改后的字段,必须在保存后要求Django刷新对象:

user.refresh_from_db()
print(user.is_active)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。