mirror of
https://github.com/django/django.git
synced 2025-10-31 09:41:08 +00:00
Refs #33476 -- Reformatted code with Black.
This commit is contained in:
committed by
Mariusz Felisiak
parent
f68fa8b45d
commit
9c19aff7c7
@@ -10,7 +10,6 @@ from django.utils.timezone import utc
|
||||
|
||||
|
||||
class SetCookieTests(SimpleTestCase):
|
||||
|
||||
def test_near_expiration(self):
|
||||
"""Cookie will expire when a near expiration time is provided."""
|
||||
response = HttpResponse()
|
||||
@@ -21,38 +20,40 @@ class SetCookieTests(SimpleTestCase):
|
||||
# larger. The sleep guarantees that there will be a time difference.
|
||||
expires = datetime.now(tz=utc).replace(tzinfo=None) + timedelta(seconds=10)
|
||||
time.sleep(0.001)
|
||||
response.set_cookie('datetime', expires=expires)
|
||||
datetime_cookie = response.cookies['datetime']
|
||||
self.assertEqual(datetime_cookie['max-age'], 10)
|
||||
response.set_cookie("datetime", expires=expires)
|
||||
datetime_cookie = response.cookies["datetime"]
|
||||
self.assertEqual(datetime_cookie["max-age"], 10)
|
||||
|
||||
def test_aware_expiration(self):
|
||||
"""set_cookie() accepts an aware datetime as expiration time."""
|
||||
response = HttpResponse()
|
||||
expires = datetime.now(tz=utc) + timedelta(seconds=10)
|
||||
time.sleep(0.001)
|
||||
response.set_cookie('datetime', expires=expires)
|
||||
datetime_cookie = response.cookies['datetime']
|
||||
self.assertEqual(datetime_cookie['max-age'], 10)
|
||||
response.set_cookie("datetime", expires=expires)
|
||||
datetime_cookie = response.cookies["datetime"]
|
||||
self.assertEqual(datetime_cookie["max-age"], 10)
|
||||
|
||||
def test_create_cookie_after_deleting_cookie(self):
|
||||
"""Setting a cookie after deletion clears the expiry date."""
|
||||
response = HttpResponse()
|
||||
response.set_cookie('c', 'old-value')
|
||||
self.assertEqual(response.cookies['c']['expires'], '')
|
||||
response.delete_cookie('c')
|
||||
self.assertEqual(response.cookies['c']['expires'], 'Thu, 01 Jan 1970 00:00:00 GMT')
|
||||
response.set_cookie('c', 'new-value')
|
||||
self.assertEqual(response.cookies['c']['expires'], '')
|
||||
response.set_cookie("c", "old-value")
|
||||
self.assertEqual(response.cookies["c"]["expires"], "")
|
||||
response.delete_cookie("c")
|
||||
self.assertEqual(
|
||||
response.cookies["c"]["expires"], "Thu, 01 Jan 1970 00:00:00 GMT"
|
||||
)
|
||||
response.set_cookie("c", "new-value")
|
||||
self.assertEqual(response.cookies["c"]["expires"], "")
|
||||
|
||||
def test_far_expiration(self):
|
||||
"""Cookie will expire when a distant expiration time is provided."""
|
||||
response = HttpResponse()
|
||||
response.set_cookie('datetime', expires=datetime(2038, 1, 1, 4, 5, 6))
|
||||
datetime_cookie = response.cookies['datetime']
|
||||
response.set_cookie("datetime", expires=datetime(2038, 1, 1, 4, 5, 6))
|
||||
datetime_cookie = response.cookies["datetime"]
|
||||
self.assertIn(
|
||||
datetime_cookie['expires'],
|
||||
datetime_cookie["expires"],
|
||||
# assertIn accounts for slight time dependency (#23450)
|
||||
('Fri, 01 Jan 2038 04:05:06 GMT', 'Fri, 01 Jan 2038 04:05:07 GMT')
|
||||
("Fri, 01 Jan 2038 04:05:06 GMT", "Fri, 01 Jan 2038 04:05:07 GMT"),
|
||||
)
|
||||
|
||||
def test_max_age_expiration(self):
|
||||
@@ -60,57 +61,58 @@ class SetCookieTests(SimpleTestCase):
|
||||
response = HttpResponse()
|
||||
set_cookie_time = time.time()
|
||||
with freeze_time(set_cookie_time):
|
||||
response.set_cookie('max_age', max_age=10)
|
||||
max_age_cookie = response.cookies['max_age']
|
||||
self.assertEqual(max_age_cookie['max-age'], 10)
|
||||
self.assertEqual(max_age_cookie['expires'], http_date(set_cookie_time + 10))
|
||||
response.set_cookie("max_age", max_age=10)
|
||||
max_age_cookie = response.cookies["max_age"]
|
||||
self.assertEqual(max_age_cookie["max-age"], 10)
|
||||
self.assertEqual(max_age_cookie["expires"], http_date(set_cookie_time + 10))
|
||||
|
||||
def test_max_age_int(self):
|
||||
response = HttpResponse()
|
||||
response.set_cookie('max_age', max_age=10.6)
|
||||
self.assertEqual(response.cookies['max_age']['max-age'], 10)
|
||||
response.set_cookie("max_age", max_age=10.6)
|
||||
self.assertEqual(response.cookies["max_age"]["max-age"], 10)
|
||||
|
||||
def test_httponly_cookie(self):
|
||||
response = HttpResponse()
|
||||
response.set_cookie('example', httponly=True)
|
||||
example_cookie = response.cookies['example']
|
||||
self.assertIn('; %s' % cookies.Morsel._reserved['httponly'], str(example_cookie))
|
||||
self.assertIs(example_cookie['httponly'], True)
|
||||
response.set_cookie("example", httponly=True)
|
||||
example_cookie = response.cookies["example"]
|
||||
self.assertIn(
|
||||
"; %s" % cookies.Morsel._reserved["httponly"], str(example_cookie)
|
||||
)
|
||||
self.assertIs(example_cookie["httponly"], True)
|
||||
|
||||
def test_unicode_cookie(self):
|
||||
"""HttpResponse.set_cookie() works with Unicode data."""
|
||||
response = HttpResponse()
|
||||
cookie_value = '清風'
|
||||
response.set_cookie('test', cookie_value)
|
||||
self.assertEqual(response.cookies['test'].value, cookie_value)
|
||||
cookie_value = "清風"
|
||||
response.set_cookie("test", cookie_value)
|
||||
self.assertEqual(response.cookies["test"].value, cookie_value)
|
||||
|
||||
def test_samesite(self):
|
||||
response = HttpResponse()
|
||||
response.set_cookie('example', samesite='None')
|
||||
self.assertEqual(response.cookies['example']['samesite'], 'None')
|
||||
response.set_cookie('example', samesite='Lax')
|
||||
self.assertEqual(response.cookies['example']['samesite'], 'Lax')
|
||||
response.set_cookie('example', samesite='strict')
|
||||
self.assertEqual(response.cookies['example']['samesite'], 'strict')
|
||||
response.set_cookie("example", samesite="None")
|
||||
self.assertEqual(response.cookies["example"]["samesite"], "None")
|
||||
response.set_cookie("example", samesite="Lax")
|
||||
self.assertEqual(response.cookies["example"]["samesite"], "Lax")
|
||||
response.set_cookie("example", samesite="strict")
|
||||
self.assertEqual(response.cookies["example"]["samesite"], "strict")
|
||||
|
||||
def test_invalid_samesite(self):
|
||||
msg = 'samesite must be "lax", "none", or "strict".'
|
||||
with self.assertRaisesMessage(ValueError, msg):
|
||||
HttpResponse().set_cookie('example', samesite='invalid')
|
||||
HttpResponse().set_cookie("example", samesite="invalid")
|
||||
|
||||
|
||||
class DeleteCookieTests(SimpleTestCase):
|
||||
|
||||
def test_default(self):
|
||||
response = HttpResponse()
|
||||
response.delete_cookie('c')
|
||||
cookie = response.cookies['c']
|
||||
self.assertEqual(cookie['expires'], 'Thu, 01 Jan 1970 00:00:00 GMT')
|
||||
self.assertEqual(cookie['max-age'], 0)
|
||||
self.assertEqual(cookie['path'], '/')
|
||||
self.assertEqual(cookie['secure'], '')
|
||||
self.assertEqual(cookie['domain'], '')
|
||||
self.assertEqual(cookie['samesite'], '')
|
||||
response.delete_cookie("c")
|
||||
cookie = response.cookies["c"]
|
||||
self.assertEqual(cookie["expires"], "Thu, 01 Jan 1970 00:00:00 GMT")
|
||||
self.assertEqual(cookie["max-age"], 0)
|
||||
self.assertEqual(cookie["path"], "/")
|
||||
self.assertEqual(cookie["secure"], "")
|
||||
self.assertEqual(cookie["domain"], "")
|
||||
self.assertEqual(cookie["samesite"], "")
|
||||
|
||||
def test_delete_cookie_secure_prefix(self):
|
||||
"""
|
||||
@@ -119,19 +121,19 @@ class DeleteCookieTests(SimpleTestCase):
|
||||
prefixes).
|
||||
"""
|
||||
response = HttpResponse()
|
||||
for prefix in ('Secure', 'Host'):
|
||||
for prefix in ("Secure", "Host"):
|
||||
with self.subTest(prefix=prefix):
|
||||
cookie_name = '__%s-c' % prefix
|
||||
cookie_name = "__%s-c" % prefix
|
||||
response.delete_cookie(cookie_name)
|
||||
self.assertIs(response.cookies[cookie_name]['secure'], True)
|
||||
self.assertIs(response.cookies[cookie_name]["secure"], True)
|
||||
|
||||
def test_delete_cookie_secure_samesite_none(self):
|
||||
# delete_cookie() sets the secure flag if samesite='none'.
|
||||
response = HttpResponse()
|
||||
response.delete_cookie('c', samesite='none')
|
||||
self.assertIs(response.cookies['c']['secure'], True)
|
||||
response.delete_cookie("c", samesite="none")
|
||||
self.assertIs(response.cookies["c"]["secure"], True)
|
||||
|
||||
def test_delete_cookie_samesite(self):
|
||||
response = HttpResponse()
|
||||
response.delete_cookie('c', samesite='lax')
|
||||
self.assertEqual(response.cookies['c']['samesite'], 'lax')
|
||||
response.delete_cookie("c", samesite="lax")
|
||||
self.assertEqual(response.cookies["c"]["samesite"], "lax")
|
||||
|
||||
@@ -17,32 +17,36 @@ class UnseekableBytesIO(io.BytesIO):
|
||||
|
||||
class FileResponseTests(SimpleTestCase):
|
||||
def test_content_length_file(self):
|
||||
response = FileResponse(open(__file__, 'rb'))
|
||||
response = FileResponse(open(__file__, "rb"))
|
||||
response.close()
|
||||
self.assertEqual(response.headers['Content-Length'], str(os.path.getsize(__file__)))
|
||||
self.assertEqual(
|
||||
response.headers["Content-Length"], str(os.path.getsize(__file__))
|
||||
)
|
||||
|
||||
def test_content_length_buffer(self):
|
||||
response = FileResponse(io.BytesIO(b'binary content'))
|
||||
self.assertEqual(response.headers['Content-Length'], '14')
|
||||
response = FileResponse(io.BytesIO(b"binary content"))
|
||||
self.assertEqual(response.headers["Content-Length"], "14")
|
||||
|
||||
def test_content_length_nonzero_starting_position_file(self):
|
||||
file = open(__file__, 'rb')
|
||||
file = open(__file__, "rb")
|
||||
file.seek(10)
|
||||
response = FileResponse(file)
|
||||
response.close()
|
||||
self.assertEqual(response.headers['Content-Length'], str(os.path.getsize(__file__) - 10))
|
||||
self.assertEqual(
|
||||
response.headers["Content-Length"], str(os.path.getsize(__file__) - 10)
|
||||
)
|
||||
|
||||
def test_content_length_nonzero_starting_position_buffer(self):
|
||||
test_tuples = (
|
||||
('BytesIO', io.BytesIO),
|
||||
('UnseekableBytesIO', UnseekableBytesIO),
|
||||
("BytesIO", io.BytesIO),
|
||||
("UnseekableBytesIO", UnseekableBytesIO),
|
||||
)
|
||||
for buffer_class_name, BufferClass in test_tuples:
|
||||
with self.subTest(buffer_class_name=buffer_class_name):
|
||||
buffer = BufferClass(b'binary content')
|
||||
buffer = BufferClass(b"binary content")
|
||||
buffer.seek(10)
|
||||
response = FileResponse(buffer)
|
||||
self.assertEqual(response.headers['Content-Length'], '4')
|
||||
self.assertEqual(response.headers["Content-Length"], "4")
|
||||
|
||||
def test_content_length_nonzero_starting_position_file_seekable_no_tell(self):
|
||||
class TestFile:
|
||||
@@ -73,125 +77,136 @@ class FileResponseTests(SimpleTestCase):
|
||||
def __exit__(self, e_type, e_val, e_tb):
|
||||
self.close()
|
||||
|
||||
file = TestFile(__file__, 'rb')
|
||||
file = TestFile(__file__, "rb")
|
||||
file.seek(10)
|
||||
response = FileResponse(file)
|
||||
response.close()
|
||||
self.assertEqual(response.headers['Content-Length'], str(os.path.getsize(__file__) - 10))
|
||||
self.assertEqual(
|
||||
response.headers["Content-Length"], str(os.path.getsize(__file__) - 10)
|
||||
)
|
||||
|
||||
def test_content_type_file(self):
|
||||
response = FileResponse(open(__file__, 'rb'))
|
||||
response = FileResponse(open(__file__, "rb"))
|
||||
response.close()
|
||||
self.assertIn(response.headers['Content-Type'], ['text/x-python', 'text/plain'])
|
||||
self.assertIn(response.headers["Content-Type"], ["text/x-python", "text/plain"])
|
||||
|
||||
def test_content_type_buffer(self):
|
||||
response = FileResponse(io.BytesIO(b'binary content'))
|
||||
self.assertEqual(response.headers['Content-Type'], 'application/octet-stream')
|
||||
response = FileResponse(io.BytesIO(b"binary content"))
|
||||
self.assertEqual(response.headers["Content-Type"], "application/octet-stream")
|
||||
|
||||
def test_content_type_buffer_explicit(self):
|
||||
response = FileResponse(io.BytesIO(b'binary content'), content_type='video/webm')
|
||||
self.assertEqual(response.headers['Content-Type'], 'video/webm')
|
||||
response = FileResponse(
|
||||
io.BytesIO(b"binary content"), content_type="video/webm"
|
||||
)
|
||||
self.assertEqual(response.headers["Content-Type"], "video/webm")
|
||||
|
||||
def test_content_type_buffer_explicit_default(self):
|
||||
response = FileResponse(io.BytesIO(b'binary content'), content_type='text/html')
|
||||
self.assertEqual(response.headers['Content-Type'], 'text/html')
|
||||
response = FileResponse(io.BytesIO(b"binary content"), content_type="text/html")
|
||||
self.assertEqual(response.headers["Content-Type"], "text/html")
|
||||
|
||||
def test_content_type_buffer_named(self):
|
||||
test_tuples = (
|
||||
(__file__, ['text/x-python', 'text/plain']),
|
||||
(__file__ + 'nosuchfile', ['application/octet-stream']),
|
||||
('test_fileresponse.py', ['text/x-python', 'text/plain']),
|
||||
('test_fileresponse.pynosuchfile', ['application/octet-stream']),
|
||||
(__file__, ["text/x-python", "text/plain"]),
|
||||
(__file__ + "nosuchfile", ["application/octet-stream"]),
|
||||
("test_fileresponse.py", ["text/x-python", "text/plain"]),
|
||||
("test_fileresponse.pynosuchfile", ["application/octet-stream"]),
|
||||
)
|
||||
for filename, content_types in test_tuples:
|
||||
with self.subTest(filename=filename):
|
||||
buffer = io.BytesIO(b'binary content')
|
||||
buffer = io.BytesIO(b"binary content")
|
||||
buffer.name = filename
|
||||
response = FileResponse(buffer)
|
||||
self.assertIn(response.headers['Content-Type'], content_types)
|
||||
self.assertIn(response.headers["Content-Type"], content_types)
|
||||
|
||||
def test_content_disposition_file(self):
|
||||
filenames = (
|
||||
('', 'test_fileresponse.py'),
|
||||
('custom_name.py', 'custom_name.py'),
|
||||
("", "test_fileresponse.py"),
|
||||
("custom_name.py", "custom_name.py"),
|
||||
)
|
||||
dispositions = (
|
||||
(False, 'inline'),
|
||||
(True, 'attachment'),
|
||||
(False, "inline"),
|
||||
(True, "attachment"),
|
||||
)
|
||||
for (filename, header_filename), (as_attachment, header_disposition) in itertools.product(
|
||||
filenames, dispositions
|
||||
):
|
||||
for (filename, header_filename), (
|
||||
as_attachment,
|
||||
header_disposition,
|
||||
) in itertools.product(filenames, dispositions):
|
||||
with self.subTest(filename=filename, disposition=header_disposition):
|
||||
response = FileResponse(open(__file__, 'rb'), filename=filename, as_attachment=as_attachment)
|
||||
response = FileResponse(
|
||||
open(__file__, "rb"), filename=filename, as_attachment=as_attachment
|
||||
)
|
||||
response.close()
|
||||
self.assertEqual(
|
||||
response.headers['Content-Disposition'],
|
||||
response.headers["Content-Disposition"],
|
||||
'%s; filename="%s"' % (header_disposition, header_filename),
|
||||
)
|
||||
|
||||
def test_content_disposition_buffer(self):
|
||||
response = FileResponse(io.BytesIO(b'binary content'))
|
||||
self.assertFalse(response.has_header('Content-Disposition'))
|
||||
response = FileResponse(io.BytesIO(b"binary content"))
|
||||
self.assertFalse(response.has_header("Content-Disposition"))
|
||||
|
||||
def test_content_disposition_buffer_attachment(self):
|
||||
response = FileResponse(io.BytesIO(b'binary content'), as_attachment=True)
|
||||
self.assertEqual(response.headers['Content-Disposition'], 'attachment')
|
||||
response = FileResponse(io.BytesIO(b"binary content"), as_attachment=True)
|
||||
self.assertEqual(response.headers["Content-Disposition"], "attachment")
|
||||
|
||||
def test_content_disposition_buffer_explicit_filename(self):
|
||||
dispositions = (
|
||||
(False, 'inline'),
|
||||
(True, 'attachment'),
|
||||
(False, "inline"),
|
||||
(True, "attachment"),
|
||||
)
|
||||
for as_attachment, header_disposition in dispositions:
|
||||
response = FileResponse(
|
||||
io.BytesIO(b'binary content'),
|
||||
io.BytesIO(b"binary content"),
|
||||
as_attachment=as_attachment,
|
||||
filename='custom_name.py',
|
||||
filename="custom_name.py",
|
||||
)
|
||||
self.assertEqual(
|
||||
response.headers['Content-Disposition'], '%s; filename="custom_name.py"' % header_disposition,
|
||||
response.headers["Content-Disposition"],
|
||||
'%s; filename="custom_name.py"' % header_disposition,
|
||||
)
|
||||
|
||||
def test_response_buffer(self):
|
||||
response = FileResponse(io.BytesIO(b'binary content'))
|
||||
self.assertEqual(list(response), [b'binary content'])
|
||||
response = FileResponse(io.BytesIO(b"binary content"))
|
||||
self.assertEqual(list(response), [b"binary content"])
|
||||
|
||||
def test_response_nonzero_starting_position(self):
|
||||
test_tuples = (
|
||||
('BytesIO', io.BytesIO),
|
||||
('UnseekableBytesIO', UnseekableBytesIO),
|
||||
("BytesIO", io.BytesIO),
|
||||
("UnseekableBytesIO", UnseekableBytesIO),
|
||||
)
|
||||
for buffer_class_name, BufferClass in test_tuples:
|
||||
with self.subTest(buffer_class_name=buffer_class_name):
|
||||
buffer = BufferClass(b'binary content')
|
||||
buffer = BufferClass(b"binary content")
|
||||
buffer.seek(10)
|
||||
response = FileResponse(buffer)
|
||||
self.assertEqual(list(response), [b'tent'])
|
||||
self.assertEqual(list(response), [b"tent"])
|
||||
|
||||
def test_buffer_explicit_absolute_filename(self):
|
||||
"""
|
||||
Headers are set correctly with a buffer when an absolute filename is
|
||||
provided.
|
||||
"""
|
||||
response = FileResponse(io.BytesIO(b'binary content'), filename=__file__)
|
||||
self.assertEqual(response.headers['Content-Length'], '14')
|
||||
self.assertEqual(response.headers['Content-Disposition'], 'inline; filename="test_fileresponse.py"')
|
||||
response = FileResponse(io.BytesIO(b"binary content"), filename=__file__)
|
||||
self.assertEqual(response.headers["Content-Length"], "14")
|
||||
self.assertEqual(
|
||||
response.headers["Content-Disposition"],
|
||||
'inline; filename="test_fileresponse.py"',
|
||||
)
|
||||
|
||||
@skipIf(sys.platform == 'win32', "Named pipes are Unix-only.")
|
||||
@skipIf(sys.platform == "win32", "Named pipes are Unix-only.")
|
||||
def test_file_from_named_pipe_response(self):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
pipe_file = os.path.join(temp_dir, 'named_pipe')
|
||||
pipe_file = os.path.join(temp_dir, "named_pipe")
|
||||
os.mkfifo(pipe_file)
|
||||
pipe_for_read = os.open(pipe_file, os.O_RDONLY | os.O_NONBLOCK)
|
||||
with open(pipe_file, 'wb') as pipe_for_write:
|
||||
pipe_for_write.write(b'binary content')
|
||||
with open(pipe_file, "wb") as pipe_for_write:
|
||||
pipe_for_write.write(b"binary content")
|
||||
|
||||
response = FileResponse(os.fdopen(pipe_for_read, mode='rb'))
|
||||
response = FileResponse(os.fdopen(pipe_for_read, mode="rb"))
|
||||
response_content = list(response)
|
||||
response.close()
|
||||
self.assertEqual(response_content, [b'binary content'])
|
||||
self.assertFalse(response.has_header('Content-Length'))
|
||||
self.assertEqual(response_content, [b"binary content"])
|
||||
self.assertFalse(response.has_header("Content-Length"))
|
||||
|
||||
def test_compressed_response(self):
|
||||
"""
|
||||
@@ -200,33 +215,34 @@ class FileResponseTests(SimpleTestCase):
|
||||
uncompress the file, which is most probably not wanted.
|
||||
"""
|
||||
test_tuples = (
|
||||
('.tar.gz', 'application/gzip'),
|
||||
('.tar.bz2', 'application/x-bzip'),
|
||||
('.tar.xz', 'application/x-xz'),
|
||||
(".tar.gz", "application/gzip"),
|
||||
(".tar.bz2", "application/x-bzip"),
|
||||
(".tar.xz", "application/x-xz"),
|
||||
)
|
||||
for extension, mimetype in test_tuples:
|
||||
with self.subTest(ext=extension):
|
||||
with tempfile.NamedTemporaryFile(suffix=extension) as tmp:
|
||||
response = FileResponse(tmp)
|
||||
self.assertEqual(response.headers['Content-Type'], mimetype)
|
||||
self.assertFalse(response.has_header('Content-Encoding'))
|
||||
self.assertEqual(response.headers["Content-Type"], mimetype)
|
||||
self.assertFalse(response.has_header("Content-Encoding"))
|
||||
|
||||
def test_unicode_attachment(self):
|
||||
response = FileResponse(
|
||||
ContentFile(b'binary content', name="祝您平安.odt"), as_attachment=True,
|
||||
content_type='application/vnd.oasis.opendocument.text',
|
||||
ContentFile(b"binary content", name="祝您平安.odt"),
|
||||
as_attachment=True,
|
||||
content_type="application/vnd.oasis.opendocument.text",
|
||||
)
|
||||
self.assertEqual(
|
||||
response.headers['Content-Type'],
|
||||
'application/vnd.oasis.opendocument.text',
|
||||
response.headers["Content-Type"],
|
||||
"application/vnd.oasis.opendocument.text",
|
||||
)
|
||||
self.assertEqual(
|
||||
response.headers['Content-Disposition'],
|
||||
response.headers["Content-Disposition"],
|
||||
"attachment; filename*=utf-8''%E7%A5%9D%E6%82%A8%E5%B9%B3%E5%AE%89.odt",
|
||||
)
|
||||
|
||||
def test_repr(self):
|
||||
response = FileResponse(io.BytesIO(b'binary content'))
|
||||
response = FileResponse(io.BytesIO(b"binary content"))
|
||||
self.assertEqual(
|
||||
repr(response),
|
||||
'<FileResponse status_code=200, "application/octet-stream">',
|
||||
|
||||
@@ -6,8 +6,8 @@ from django.http import HttpResponse
|
||||
from django.http.response import HttpResponseBase
|
||||
from django.test import SimpleTestCase
|
||||
|
||||
UTF8 = 'utf-8'
|
||||
ISO88591 = 'iso-8859-1'
|
||||
UTF8 = "utf-8"
|
||||
ISO88591 = "iso-8859-1"
|
||||
|
||||
|
||||
class HttpResponseBaseTests(SimpleTestCase):
|
||||
@@ -22,14 +22,20 @@ class HttpResponseBaseTests(SimpleTestCase):
|
||||
r = HttpResponseBase()
|
||||
self.assertIs(r.writable(), False)
|
||||
|
||||
with self.assertRaisesMessage(OSError, 'This HttpResponseBase instance is not writable'):
|
||||
r.write('asdf')
|
||||
with self.assertRaisesMessage(OSError, 'This HttpResponseBase instance is not writable'):
|
||||
r.writelines(['asdf\n', 'qwer\n'])
|
||||
with self.assertRaisesMessage(
|
||||
OSError, "This HttpResponseBase instance is not writable"
|
||||
):
|
||||
r.write("asdf")
|
||||
with self.assertRaisesMessage(
|
||||
OSError, "This HttpResponseBase instance is not writable"
|
||||
):
|
||||
r.writelines(["asdf\n", "qwer\n"])
|
||||
|
||||
def test_tell(self):
|
||||
r = HttpResponseBase()
|
||||
with self.assertRaisesMessage(OSError, 'This HttpResponseBase instance cannot tell its position'):
|
||||
with self.assertRaisesMessage(
|
||||
OSError, "This HttpResponseBase instance cannot tell its position"
|
||||
):
|
||||
r.tell()
|
||||
|
||||
def test_setdefault(self):
|
||||
@@ -39,12 +45,12 @@ class HttpResponseBaseTests(SimpleTestCase):
|
||||
"""
|
||||
r = HttpResponseBase()
|
||||
|
||||
r.headers['Header'] = 'Value'
|
||||
r.setdefault('header', 'changed')
|
||||
self.assertEqual(r.headers['header'], 'Value')
|
||||
r.headers["Header"] = "Value"
|
||||
r.setdefault("header", "changed")
|
||||
self.assertEqual(r.headers["header"], "Value")
|
||||
|
||||
r.setdefault('x-header', 'DefaultValue')
|
||||
self.assertEqual(r.headers['X-Header'], 'DefaultValue')
|
||||
r.setdefault("x-header", "DefaultValue")
|
||||
self.assertEqual(r.headers["X-Header"], "DefaultValue")
|
||||
|
||||
|
||||
class HttpResponseTests(SimpleTestCase):
|
||||
@@ -60,16 +66,18 @@ class HttpResponseTests(SimpleTestCase):
|
||||
self.assertEqual(resp.reason_phrase, "Service Unavailable")
|
||||
|
||||
def test_valid_status_code_string(self):
|
||||
resp = HttpResponse(status='100')
|
||||
resp = HttpResponse(status="100")
|
||||
self.assertEqual(resp.status_code, 100)
|
||||
resp = HttpResponse(status='404')
|
||||
resp = HttpResponse(status="404")
|
||||
self.assertEqual(resp.status_code, 404)
|
||||
resp = HttpResponse(status='599')
|
||||
resp = HttpResponse(status="599")
|
||||
self.assertEqual(resp.status_code, 599)
|
||||
|
||||
def test_invalid_status_code(self):
|
||||
must_be_integer = 'HTTP status code must be an integer.'
|
||||
must_be_integer_in_range = 'HTTP status code must be an integer from 100 to 599.'
|
||||
must_be_integer = "HTTP status code must be an integer."
|
||||
must_be_integer_in_range = (
|
||||
"HTTP status code must be an integer from 100 to 599."
|
||||
)
|
||||
with self.assertRaisesMessage(TypeError, must_be_integer):
|
||||
HttpResponse(status=object())
|
||||
with self.assertRaisesMessage(TypeError, must_be_integer):
|
||||
@@ -86,27 +94,31 @@ class HttpResponseTests(SimpleTestCase):
|
||||
self.assertEqual(resp.reason_phrase, reason)
|
||||
|
||||
def test_charset_detection(self):
|
||||
""" HttpResponse should parse charset from content_type."""
|
||||
response = HttpResponse('ok')
|
||||
"""HttpResponse should parse charset from content_type."""
|
||||
response = HttpResponse("ok")
|
||||
self.assertEqual(response.charset, settings.DEFAULT_CHARSET)
|
||||
|
||||
response = HttpResponse(charset=ISO88591)
|
||||
self.assertEqual(response.charset, ISO88591)
|
||||
self.assertEqual(response.headers['Content-Type'], 'text/html; charset=%s' % ISO88591)
|
||||
self.assertEqual(
|
||||
response.headers["Content-Type"], "text/html; charset=%s" % ISO88591
|
||||
)
|
||||
|
||||
response = HttpResponse(content_type='text/plain; charset=%s' % UTF8, charset=ISO88591)
|
||||
response = HttpResponse(
|
||||
content_type="text/plain; charset=%s" % UTF8, charset=ISO88591
|
||||
)
|
||||
self.assertEqual(response.charset, ISO88591)
|
||||
|
||||
response = HttpResponse(content_type='text/plain; charset=%s' % ISO88591)
|
||||
response = HttpResponse(content_type="text/plain; charset=%s" % ISO88591)
|
||||
self.assertEqual(response.charset, ISO88591)
|
||||
|
||||
response = HttpResponse(content_type='text/plain; charset="%s"' % ISO88591)
|
||||
self.assertEqual(response.charset, ISO88591)
|
||||
|
||||
response = HttpResponse(content_type='text/plain; charset=')
|
||||
response = HttpResponse(content_type="text/plain; charset=")
|
||||
self.assertEqual(response.charset, settings.DEFAULT_CHARSET)
|
||||
|
||||
response = HttpResponse(content_type='text/plain')
|
||||
response = HttpResponse(content_type="text/plain")
|
||||
self.assertEqual(response.charset, settings.DEFAULT_CHARSET)
|
||||
|
||||
def test_response_content_charset(self):
|
||||
@@ -118,13 +130,15 @@ class HttpResponseTests(SimpleTestCase):
|
||||
response = HttpResponse(utf8_content)
|
||||
self.assertContains(response, utf8_content)
|
||||
|
||||
response = HttpResponse(iso_content, content_type='text/plain; charset=%s' % ISO88591)
|
||||
response = HttpResponse(
|
||||
iso_content, content_type="text/plain; charset=%s" % ISO88591
|
||||
)
|
||||
self.assertContains(response, iso_content)
|
||||
|
||||
response = HttpResponse(iso_content)
|
||||
self.assertContains(response, iso_content)
|
||||
|
||||
response = HttpResponse(iso_content, content_type='text/plain')
|
||||
response = HttpResponse(iso_content, content_type="text/plain")
|
||||
self.assertContains(response, iso_content)
|
||||
|
||||
def test_repr(self):
|
||||
@@ -134,8 +148,8 @@ class HttpResponseTests(SimpleTestCase):
|
||||
|
||||
def test_repr_no_content_type(self):
|
||||
response = HttpResponse(status=204)
|
||||
del response.headers['Content-Type']
|
||||
self.assertEqual(repr(response), '<HttpResponse status_code=204>')
|
||||
del response.headers["Content-Type"]
|
||||
self.assertEqual(repr(response), "<HttpResponse status_code=204>")
|
||||
|
||||
def test_wrap_textiowrapper(self):
|
||||
content = "Café :)"
|
||||
@@ -147,10 +161,10 @@ class HttpResponseTests(SimpleTestCase):
|
||||
def test_generator_cache(self):
|
||||
generator = (str(i) for i in range(10))
|
||||
response = HttpResponse(content=generator)
|
||||
self.assertEqual(response.content, b'0123456789')
|
||||
self.assertEqual(response.content, b"0123456789")
|
||||
with self.assertRaises(StopIteration):
|
||||
next(generator)
|
||||
|
||||
cache.set('my-response-key', response)
|
||||
response = cache.get('my-response-key')
|
||||
self.assertEqual(response.content, b'0123456789')
|
||||
cache.set("my-response-key", response)
|
||||
response = cache.get("my-response-key")
|
||||
self.assertEqual(response.content, b"0123456789")
|
||||
|
||||
Reference in New Issue
Block a user