2014-12-25 14 views
3

올바른 템플릿을 사용하고 있는지 테스트하고 싶은데 login_required 데코레이터가있는 페이지가 있습니다. stackoverflow에서 단위 테스트에 대한 인증 방법을 찾았지만 나를 위해 어떤 이유로 작동하지 않습니다.unittest에서 인증 할 수 없음

from django.test import TestCase 
from django.test import Client 
import base64 


class TestUsingCorrectTemplates(TestCase): 

def test_correct_classroom_template_used(self): 
    auth_headers = {'HTTP_AUTHORIZATION': 'Basic '+base64.b64encode('[email protected]:admin')} 
    c = Client() 
    response = c.get('/classroom/', **auth_headers) 
    self.assertEqual(response.status_code, 200) 
    self.assertTemplateUsed(response,'classroom.html') 

또한 오픈 ID/AllAuth로 처리 권한 부여를 언급 좋아하고 더 /login 페이지, 사용자가 로그인 따르는 시작 페이지 /

내용 변수 response의에서이없는 것 :

여기 내 테스트입니다
Vary: Cookie 
X-Frame-Options: SAMEORIGIN 
Content-Type: text/html; charset=utf-8 
Location: http://testserver/?next=/classroom/ 

테스트 오류 :

self.assertEqual(response.status_code, 200) 
    AssertionError: 302 != 200 

내가 뭘 잘못하고 있니?

+0

테스트를 실행할 때 인증 할 사용자가 없습니다. 먼저 데이터베이스에 추가해야합니다. Mock을 사용하여 요청과 액세스 토큰을 조롱해야 할 수도 있습니다. – Brandon

+0

그리고'login_required'를 사용한다면 테스트에서 HTTP 인증을 위조하는 것이 전혀 도움이되지 않습니다. –

+0

어떻게 테스트를 통과 할 수 있습니까? – micgeronimo

답변

3

HTTP 코드 302는 서버가 리디렉션 응답을 보내는 것을 의미합니다. 실제 로그인 페이지를 처리 ​​할 수 ​​있도록 리디렉션을 따르도록 클라이언트에게 알려야합니다. 이처럼 get 전화를 변경할 수 있습니다

response = c.get('/classroom/', follow=True, **auth_headers) 

당신이 response.redirect_chain을 검사 할 수 있습니다 중간 리디렉션 단계를 선택하십시오. 모든 문서는 here입니다.

1

Client 인스턴스의 사용자 및 calling the login 메서드를 만들려고 했습니까?

import base64 

from django.test import TestCase 


class TestUsingCorrectTemplates(TestCase): 
    def setUp(self): 
     # Create your user here 
     # self.user = ... 

    def test_correct_classroom_template_used(self): 
     self.client.login('[email protected]', 'admin') 
     response = self.client.get('/classroom/') # XXX: You should use url reversal here. 
     self.assertEqual(response.status_code, 200) 
     self.assertTemplateUsed(response, 'classroom.html')