2

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.

3
  • you can use Client.login, docs.djangoproject.com/en/1.2/topics/testing/…, to test user logging Commented Jul 10, 2011 at 15:13
  • 1
    @Ashok: Client.login is useful to test views that require authentication, but in this case, Artur wants to test his actual login view Commented Jul 10, 2011 at 16:30
  • I can explain why the login test broke the register test: Before you fixed the login test, it was failing before it got to u.delete - so the test user already existed when the register test ran. The best solution would be to delete the test user in the tearDown method instead of inside the test. Alternatively use different usernames and emails in each test so that one failing test does not affect the others. Commented Jul 10, 2011 at 20:27

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The response status code for the login view will only be 302 if follow=False. When follow=True, the client will load the redirect url, so the status code will be 200.
so 200 code is response code for the page that I am redirecting to? In these case these 200 is for uindex?
yes. Make the edit I just suggested on Alasdair's advice, and see if that test then passes.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.