django测试问题

时间:2011-07-10 10:53:19

标签: django unit-testing

我认为我想要接受测试。

def logIn(request):
    """
    This method will log in user using  username or email
    """
    if request.method == 'POST':
        form = LogInForm(request.POST)
        if form.is_valid():
            user = authenticate(username=form.cleaned_data['name'],password=form.cleaned_data['password'])
            if user:
                login(request,user)
                return redirect('uindex')
            else:
                error = "Nie prawidlowy login lub haslo.Upewnij sie ze wpisales prawidlowe dane"
    else:
        form = LogInForm(auto_id=False)
    return render_to_response('login.html',locals(),context_instance=RequestContext(request))

这是测试

class LoginTest(unittest.TestCase):
    def setUp(self):
        self.client  = Client()
    def test_response_for_get(self):
        response =  self.client.get(reverse('logIn'))
        self.assertEqual(response.status_code, 200)
    def test_login_with_username(self):
        """
        Test if user can login wit username and password
        """
        user_name = 'test'
        user_email = 'test@test.com'
        user_password = 'zaq12wsx'
        u =  User.objects.create_user(user_name,user_email,user_password)
        response = self.client.post(reverse('logIn'),data={'name':user_name,'password':user_password},follow=True)
        self.assertEquals(response.request.user.username,user_name)
        u.delete()

当我运行此测试时,我在test_login_with_username:

上失败了
AttributeError: 'dict' object has no attribute 'user'

当我在视图中使用request.user.username工作正常没有错误,这只是在测试中失败。在此先感谢您的帮助 编辑:好的我用

替换损坏的部分
self.assertEquals(302, response.status_code)

但现在这个测试打破了另一个测试。

AssertionError: 302 != 200

以下是我现在失败的视图代码。我希望电子邮件和用户名是唯一的。

def register(request):
    """
    Function to register new user.
    This function will have to care for email uniqueness,and login
    """
    if request.method == 'POST':
        error=[]
        form = RegisterForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            email = form.cleaned_data['email']
            if  form.cleaned_data['password'] ==  form.cleaned_data['password_confirmation']:
                password = form.cleaned_data['password']
                if len(User.objects.filter(username=username)) == 0 and len(User.objects.filter(email=email)) == 0:
                    #email and username are bouth unique
                    u = User()
                    u.username = username
                    u.set_password(password)
                    u.email = email
                    u.is_active = False
                    u.is_superuser = False
                    u.is_active = True
                    u.save()
                    return render_to_response('success_register.html',locals(),context_instance=RequestContext(request))
                else:
                    if len(User.objects.filter(username=username)) > 0:
                        error.append("Podany login jest juz zajety")
                    if len(User.objects.filter(email=email)) > 0:
                        error.append("Podany email jest juz zajety")
            else:
                error.append("Hasla nie pasuja do siebie")
        #return render_to_response('register.html',locals(),context_instance=RequestContext(request))
    else:
        form = RegisterForm(auto_id=False)
    return render_to_response('register.html',locals(),context_instance=RequestContext(request))

这是一项非常有效的测试,但现在已经破了

def test_user_register_with_unique_data_and_permission(self):
        """
        Will try to register user which provided for sure unique credentials
        And also make sure that profile will be automatically created for him, and also that he he have valid privileges
        """
        user_name = 'test'
        user_email = 'test@test.com'
        password = 'zaq12wsx'
        response = self.client.post(reverse('register'),{'username': user_name,'email':user_email,
        'password':password,'password_confirmation':password},follow=True)
        #check if code is 200
        self.assertEqual(response.status_code, 200)
        u = User.objects.get(username=user_name,email = user_email)
        self.assertTrue(u,"User after creation coudn't be fetched")
        self.assertFalse(u.is_staff,msg="User after registration belong to staff")
        self.assertFalse(u.is_superuser,msg="User after registration is superuser")
        p = UserProfile.objects.get(user__username__iexact = user_name)
        self.assertTrue(p,"After user creation coudn't fetch user profile")
        self.assertEqual(len(response.context['error']),0,msg = 'We shoudnt get error during valid registration')
        u.delete()
        p.delete()

这里结束是错误:

AssertionError: We shoudnt get error during valid registration

如果我禁用登录测试,一切正常。这个测试如何打破另一个?为什么登录测试没有通过。我在网站上试一试,效果很好。

2 个答案:

答案 0 :(得分:4)

测试客户端返回的响应对象的

The documentation说明了请求属性:

  

请求

     

刺激响应的请求数据

这对我来说是两件事之一。它只是请求的数据,或者是处理请求之前的请求对象。在任何一种情况下,您都不希望它包含登录用户。

另一种编写测试表明登录成功完成的方法是将follow=False添加到client.post调用并检查响应代码:

self.assertEquals(302, response.status_code)

检查是否发生了重定向。

答案 1 :(得分:2)

response.request不是您期望的视图中的HttpRequest对象。这是一个刺激帖子请求的数据字典。它没有用户属性,因此AttributeError

您可以将测试重写为:

  1. 使用Django 1.3中引入的RequestFactory类,直接在测试中调用logIn,而不是使用client.post
  2. 在帖子后检查client.session以检查用户是否已登录。
  3. 为什么一个失败的测试可以打破另一个

    编辑问题后,您问了

      

    此测试如何打破另一个?

    test_login_with_username在达到u.delete之前失败,因此在该测试中创建的用户未被删除。这导致了test_user_register_with_unique_data_and_permission,因为用户test已经存在。

    如果你使用django.test.TestCase类,数据库将在每次测试之间重置,所以这不会有问题。