Nice programing

Django : 페이지가 원하는 URL로 리디렉션되었는지 테스트

nicepro 2020. 12. 13. 11:08
반응형

Django : 페이지가 원하는 URL로 리디렉션되었는지 테스트


내 장고 앱에는 인증 시스템이 있습니다. 따라서 로그인하지 않고 일부 프로필의 개인 정보에 액세스하려고하면 로그인 페이지로 리디렉션됩니다.

이제 이에 대한 테스트 케이스를 작성해야합니다. 내가 얻는 브라우저의 응답은 다음과 같습니다.

GET /myprofile/data/some_id/ HTTP/1.1 302 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 301 0
GET /account/login?next=/myprofile/data/some_id/ HTTP/1.1 200 6533

테스트는 어떻게 작성합니까? 이것은 내가 지금까지 가지고있는 것 :

self.client.login(user="user", password="passwd")
response = self.client.get('/myprofile/data/some_id/')
self.assertEqual(response.status,200)
self.client.logout()
response = self.client.get('/myprofile/data/some_id/')

다음에 무엇이 올 수 있습니까?


장고 1.4 :

https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.TestCase.assertRedirects

장고 2.0 :

https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.SimpleTestCase.assertRedirects

SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True)

응답이 status_code 리디렉션 상태를 반환하고 expected_url (모든 GET 데이터 포함)로 리디렉션되었으며 최종 페이지가 target_status_code 와 함께 수신 되었는지 확인 합니다.

요청에서 follow 인수를 사용한 경우 expected_urltarget_status_code 는 리디렉션 체인의 마지막 지점에 대한 URL 및 상태 코드가됩니다.

경우 fetch_redirect_response이 있다 거짓 , 마지막 페이지가로드되지 않습니다. 테스트 클라이언트가 외부 URL을 가져올 수 없기 때문에 expected_url 이 Django 앱의 일부가 아닌 경우 특히 유용합니다 .

두 URL을 비교할 때 체계가 올바르게 처리됩니다. 리디렉션되는 위치에 지정된 체계가 없으면 원래 요청의 체계가 사용됩니다. 있는 경우 expected_url 의 스키마 는 비교에 사용되는 스키마입니다 .


다음과 같이 리디렉션을 따를 수도 있습니다.

response = self.client.get('/myprofile/data/some_id/', follow=True)

이는 브라우저의 사용자 경험을 미러링하고 다음과 같이 브라우저에서 찾을 것으로 예상되는 내용을 주장합니다.

self.assertContains(response, "You must be logged in", status_code=401)

response['Location']예상 URL과 일치하는지 확인할 수 있습니다 . 상태 코드가 302인지 확인하십시오.


response['Location']1.9에는 존재하지 않습니다. 대신 사용 :

response = self.client.get('/myprofile/data/some_id/', follow=True)
last_url, status_code = response.redirect_chain[-1]
print(last_url)

참고 URL : https://stackoverflow.com/questions/14951356/django-testing-if-the-page-has-redirected-to-the-desired-url

반응형