views:

98

answers:

1

This is a simple structure in my project:

MyAPP---
        note---
               __init__.py
               views.py
               urls.py
               test.py
               models.py
        auth--
              ...
        template---
                   auth---
                          login.html
                          register.html
                   note---
                          noteshow.html
                   media---
                           css---
                                 ...
                           js---
                                 ...
        settings.py
        urls.py
        __init__.py
        manage.py

I want to make a unittest which can test the noteshow page working propeyly or not.

The code:

from django.test import TestCase

class Note(TestCase):
    def test_noteshow(self):
        response = self.client.get('/note/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, '/note/noteshow.html')

The problem is that my project include an auth mod, it will force the unlogin user redirecting into the login.html page when they visit the noteshow.html.

So, when I run my unittest, in the bash it raise an failure that the response.status_code is always 302 instead of 200.

All right though through this result I can check the auth mod is running well, it is not like what I want it to be.

OK, the question is that how can I make another unittest to check my noteshow.template is used or not?

Thanks for all.

django version: 1.1.1

python version: 2.6.4

Use Eclipse for MAC OS

+5  A: 

Just login a user for each test. The best way to do this is to use a setUp() method that creates a client, creates a user, and then logs user in. Also use a tearDown() method that does the reverse (logs out user and deletes user).

The methods setUp() and tearDown() are run automatically for each test in the set of tests.

It would look something like this:

class Note(TestCase):
    def setUp(self):
        self.client = Client()
        self.new_user = User.objects.create_user('blah', '[email protected]', 'blah')
        self.new_user.save()
        self.client.login(username='blah', password='blah')

    def tearDown(self):
        self.client.logout()
        self.new_user.delete()

    def test_noteshow(self):
        response = self.client.get('/note/')
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, '/note/noteshow.html')

Hope this helps.

tdedecko
Thanks a lot.This is really helpful!
Malcom.Z