我使用user.userprofile中的信息來管理權限。在測試中使用請求的用戶信息
我如何使用它:
# 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')
現在,在視圖中,我有爲例:
# Only the owner view this template
if request.user.userprofile.status != 'teacher':
return redirect('Penelope.views.home')
如何我特林考:
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...
所以,這意味着當視圖測試用戶是否是老師(cf:我的主題的頂部),它發送了False ...
我如何訪問此信息並執行測試?
哼哼對不起,我在發送之前已經簡化了我的代碼太多了。但是現實中沒問題,我現在編輯它! – nlassaux