John
John

Reputation: 1360

django testing problems

This is my view that I want to be tested.

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))

And here's the test

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 = '[email protected]'
        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()

And when i run this test i got failure on test_login_with_username:

AttributeError: 'dict' object has no attribute 'user'

When i use in views request.user.username in works fine no error this just fails in tests. Thanks in advance for any help edit:Ok I replace the broken part with

self.assertEquals(302, response.status_code)

But now this test breaks and another one too.

AssertionError: 302 != 200

Here is my code for the view that now fail. I want email and username to be unique.

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))

And here is the test that priviously work but now it is broken

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 = '[email protected]'
        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()

End here is the error:

AssertionError: We shoudnt get error during valid registration

If i disable login test everything is ok. How this test can break another one? And why login test is not passing. I try it on website and it works fine.

Upvotes: 2

Views: 2666

Answers (2)

Alasdair
Alasdair

Reputation: 308769

response.request is not the HttpRequest object in the view you are expecting. It's a dictionary of data that stimulated the post request. It doesn't have the user attribute, hence the AttributeError

You could rewrite your test to:

  1. use the RequestFactory class introduced in Django 1.3 and call logIn in your test directly instead of using client.post.
  2. inspect client.session after the post to check whether the user has been logged in.

Why one failing test can break another

When you edited the question, you asked

How this test can break another one?

The test_login_with_username was failing before it reached u.delete, so the user created in that test was not deleted. That caused test_user_register_with_unique_data_and_permission because the user test already existed.

If you use the django.test.TestCase class, the database will be reset in between each test, so this wouldn't be a problem.

Upvotes: 2

Gareth
Gareth

Reputation: 1450

The documentation for the response object returned by the test client says this about the request attribute:

request

The request data that stimulated the response.

That suggests to me one of two things. Either it's just the data of the request, or it's request object as it was before you handled the request. In either case, you would not expect it to contain the logged in user.

Another way to write your test that the login completed successfully would be to add follow=False to the client.post call and check the response code:

self.assertEquals(302, response.status_code)

This checks that the redirect has occurred.

Upvotes: 4

Related Questions