nlassaux
nlassaux

Reputation: 2406

Use request's user informations in tests

I use an information in user.userprofile to manage permissions.

How I use it :

# List of status
STATUS_CHOICES = (
    ('teacher', 'Teacher'),
    ('student', 'Student'),
)

# More field for an user.
class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='student')

Now, in a view, I have for exemple :

# Only the owner view this template
if request.user.userprofile.status != 'teacher':
    return redirect('Penelope.views.home')

How I'm tring to test :

def login_function(self, username, password, status):
    # Create a new user
    user = User.objects.create_user(username=username, password=password)
    user.userprofile.status = status
    user.save()

    # Use test client to perform login
    user = self.client.login(username=username, password=password)
    response = self.client.post('/login/')

class LoggedAsTeacherCase(TestCase):
    def setUp(self):
        # I create and log with a teacher user
        login_function(self, 'teststudent', 'password', 'teacher') 

    def test_login(self):  # Verify if login has been validated by server
        response = self.client.get('/login/')
        self.assertRedirects(response, '/')   # <<< It is ok (My user is detected as connected, he is redirected)

    def test_dashboard(self): 
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)   # <<< It is ok (Confirmation, my user is not redirected to login url, perfect)

    def test_newcourse(self):
        response = self.client.get('/newcourse/')
        self.assertEqual(response.status_code, 200)   # <<<  /!\ It is false, I have a redirection (302), not a 200...

So, it means that when the view tests if the user is a teacher (cf: top of my subject), it has sent False...

How can I access to this information and perform tests?

Upvotes: 1

Views: 86

Answers (2)

nlassaux
nlassaux

Reputation: 2406

I have found the problem !

user = User.objects.create_user(username=username, password=password)
user.userprofile.status = status
user.save()

When I do that, i suppose user = User.objects.create_user(username=username, password=password)returns an user (false).

So, I have to make a request :

user = User.objects.create_user(username=username, password=password)
test = UserProfile.objects.filter(user=username)
test.status = status
test.save()

And it is ok !

Upvotes: 0

thikonom
thikonom

Reputation: 4267

Your definition of your status field is incorrect. CharFields require a "max_length" attribute that is a positive integer.

Change it to the following:

models.CharField(max_length=..., choices=STATUS_CHOICES)

See also here

Upvotes: 2

Related Questions