因此,代码本身可行,但测试失败。我想也许self.user和request.user之间有一些区别?我输了。
views.py:
def index(request, model_name='item'):
if request.user.is_authenticated():
return render(request, 'assets/index.html', {})
else:
#THIS IS RUNNING
return redirect(reverse('login'))
tests.py:
def setUp(self):
self.client = Client()
self.user = create_test_user()
self.user.set_password('test_user')
self.user.save()
self.client.login(
username=self.user.username,
password=self.user.password)
print 'AUTHENTICATED? ', self.user.is_authenticated() #PRINTS TRUE
def test_index(self): # homepage
response = self.client.get(reverse('index'))
self.assertEqual(response.status_code, 200)
答案 0 :(得分:0)
user.password
不是可用于登录用户的纯文本密码。这是加密密码的结果。
您必须保存实际的纯文本密码(在这种情况下为'test_user'
)并使用该密码登录用户:
def setUp(self):
self.client = Client()
self.user = create_test_user()
self.password = 'test_user'
self.user.set_password(self.password)
self.user.save()
self.client.login(
username=self.user.username,
password=self.password)
print 'AUTHENTICATED? ', self.user.is_authenticated() #PRINTS TRUE