Django テンプレート テストで奇妙な問題が発生しました。テストでビューを実行すると、ビューは HttpResponse オブジェクトを返します。しかし、その応答オブジェクトを Django TestCase の assertContains メソッドに渡すと、応答オブジェクトは文字列になります。この文字列には、応答オブジェクトのような「status_code」属性がないため、テストは失敗します。これが私のコードです:
template_tests.py
from django.test import TestCase
from django.test.client import RequestFactory
class TestUploadMainPhotoTemplate(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_user_selects_non_jpeg_photo_file(self):
"""
User is trying to upload a photo file via a form
with an ImageField. However, the file doesn't have
a '.jpg' extension so the form's is_valid function, which
I've overridden, flags this as an error and returns False.
"""
with open('photo.png') as test_photo:
request = self.factory.post(reverse('upload-photo'),
{'upload_photo': '[Upload Photo]',
'photo': test_photo})
kwargs = {'template': 'upload_photo.html'}
response = upload_photo(request, **kwargs)
# pdb.set_trace()
self.assertContains(response, 'Error: photo file must be a JPEG file')
このコードをデバッガーで実行し、assertContains を呼び出す前に「type(response)」を実行すると、「response」が HttpResponse オブジェクトであることがわかります。ただし、assertContains が呼び出されると、次のエラーが発生します。
AttributeError: 'str' object has no attribute 'status_code'
assertContains メソッドの .../django/test/testcases.py:638 に追加のブレークポイントを設定しました。
self.assertEqual(response.status_code, status_code...
この時点で、もう一度「type(response)」を実行すると、文字列オブジェクトになり、status_code 属性がないことがわかります。誰が何が起こっているのか説明できますか? この同じテスト パターンを他の 12 個のテンプレート テストで使用して成功しましたが、すべてのテストで機能しました。このテストにファイルのアップロードが含まれているという事実と何か関係があるのでしょうか?
ありがとう。