I wanted to introduce unit testing to a Django application. Although I started failing on the first thing I wanted to test. Can you tell me what I am doing wrong?
The view I want to test
@user_passes_test(lambda u: u.has_module_perms('myModule'))
def myView(request):
...someCode...
I wanted to test the user_passes_test bit, I also have more complex tests so I wanted to know if my tests let the right users and only them access the view. I focused on the bit that didn't work and simplified it a bit.
from django.contrib.auth.models import User
from django.test import TestCase
from settings import DJANGO_ROOT
class PermissionsTestCase(TestCase):
fixtures = [DJANGO_ROOT + 'testdata.json']
def setUp(self):
self.user = User.objects.create(username='user', password='pass')
self.user.save()
def test_permissions_overview(self):
url = '/secret/'
#User not logged in (guest)
response = self.client.get(url)
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/secret/')
#Logged in user that should not be able to see this page
response = self.client.get(url)
self.client.login(username='user', password='pass')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/secret/')
#Logged in user that has 'myModule' module permissions
self.user.user_permissions.add('myModule.view_myThing')
self.user.save()
self.assertTrue(self.user.has_module_perms('myModule')) #This one fails
self.client.login(username='user',password='pass')
response = self.client.get(url)
self.assertContains(response, "What to look for") #This one too
And the last bit keeps on failing. The permission doesn't get through. Any ideas?
This won't convert the password to hash
User.objects.create(username='user', password='pass')
the correct way to create user is :
User.objects.create_user(username='user', password='pass')
here is full summary
>>> from django.contrib.auth.models import User
>>> x=User.objects.create(username='user', password='pass')
>>> x.password
'pass'
>>> from django.test import Client
>>> c = Client()
>>> c.login(username='user',password='pass')
False
# But create_user works
>>> y=User.objects.create_user(username='user2', password='pass')
>>> y.password
u'pbkdf2_sha256$12000$oh55gfrnCZn5$hwGrkUZx38siegWHLXSYoNDT2SSP1M5+Whh5PnJZD8I='
>>> c.login(username='user2',password='pass')
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With