環境
Django 2.1.1
Python 3.6.1
やりたかったこと
DjangoのTestCaseのassertTemplateUsedメソッドで、レスポンスが特定のテンプレートを利用していることを確かめたかった。
class TestIndexView(TestCase):
def test_get(self):
response = self.client.get('/')
self.assertTemplateUsed(response, 'application/index.html')
問題
テストを実行したところ、以下のエラーが発生した。
F
======================================================================
FAIL: test_get (application.tests.test_views.TestIndexView)
----------------------------------------------------------------------
Traceback (most recent call last):
File "project/application/tests/test_views.py", line 8, in test_get
self.assertTemplateUsed(response, 'application/index.html')
File ".pyenv/versions/3.6.1/lib/python3.6/site-packages/django/test/testcases.py", line 554, in assertTemplateUsed
self.fail(msg_prefix + "No templates used to render the response")
AssertionError: No templates used to render the response
原因
settings.pyのSECURE_SSL_REDIRECTをTRUEにしていたため、HTTPからHTTPSにリダイレクトが発生し、ステータスコード301が返却されたことが原因ではないか?と考えた。
<HttpResponsePermanentRedirect status_code=301, "text/html; charset=utf-8", url="https://testserver/">
解決策
テスト時にはsettings.pyのSECURE_SSL_REDIRECTをFALSEにした。