| 1 |
import copy |
| 2 |
import json |
| 3 |
import os |
| 4 |
import pickle |
| 5 |
import unittest |
| 6 |
import uuid |
| 7 |
|
| 8 |
from django.core.exceptions import DisallowedRedirect |
| 9 |
from django.core.serializers.json import DjangoJSONEncoder |
| 10 |
from django.core.signals import request_finished |
| 11 |
from django.db import close_old_connections |
| 12 |
from django.http import ( |
| 13 |
BadHeaderError, |
| 14 |
HttpResponse, |
| 15 |
HttpResponseNotAllowed, |
| 16 |
HttpResponseNotModified, |
| 17 |
HttpResponsePermanentRedirect, |
| 18 |
HttpResponseRedirect, |
| 19 |
JsonResponse, |
| 20 |
QueryDict, |
| 21 |
SimpleCookie, |
| 22 |
StreamingHttpResponse, |
| 23 |
parse_cookie, |
| 24 |
) |
| 25 |
from django.test import SimpleTestCase |
| 26 |
from django.utils.functional import lazystr |
| 27 |
from django.utils.http import MAX_URL_REDIRECT_LENGTH |
| 28 |
|
| 29 |
|
| 30 |
class QueryDictTests(SimpleTestCase): |
| 31 |
def test_create_with_no_args(self): |
| 32 |
self.assertEqual(QueryDict(), QueryDict("")) |
| 33 |
|
| 34 |
def test_missing_key(self): |
| 35 |
q = QueryDict() |
| 36 |
with self.assertRaises(KeyError): |
| 37 |
q.__getitem__("foo") |
| 38 |
|
| 39 |
def test_immutability(self): |
| 40 |
q = QueryDict() |
| 41 |
with self.assertRaises(AttributeError): |
| 42 |
q.__setitem__("something", "bar") |
| 43 |
with self.assertRaises(AttributeError): |
| 44 |
q.setlist("foo", ["bar"]) |
| 45 |
with self.assertRaises(AttributeError): |
| 46 |
q.appendlist("foo", ["bar"]) |
| 47 |
with self.assertRaises(AttributeError): |
| 48 |
q.update({"foo": "bar"}) |
| 49 |
with self.assertRaises(AttributeError): |
| 50 |
q.pop("foo") |
| 51 |
with self.assertRaises(AttributeError): |
| 52 |
q.popitem() |
| 53 |
with self.assertRaises(AttributeError): |
| 54 |
q.clear() |
| 55 |
|
| 56 |
def test_immutable_get_with_default(self): |
| 57 |
q = QueryDict() |
| 58 |
self.assertEqual(q.get("foo", "default"), "default") |
| 59 |
|
| 60 |
def test_immutable_basic_operations(self): |
| 61 |
q = QueryDict() |
| 62 |
self.assertEqual(q.getlist("foo"), []) |
| 63 |
self.assertNotIn("foo", q) |
| 64 |
self.assertEqual(list(q), []) |
| 65 |
self.assertEqual(list(q.items()), []) |
| 66 |
self.assertEqual(list(q.lists()), []) |
| 67 |
self.assertEqual(list(q.keys()), []) |
| 68 |
self.assertEqual(list(q.values()), []) |
| 69 |
self.assertEqual(len(q), 0) |
| 70 |
self.assertEqual(q.urlencode(), "") |
| 71 |
|
| 72 |
def test_single_key_value(self): |
| 73 |
"""Test QueryDict with one key/value pair""" |
| 74 |
|
| 75 |
q = QueryDict("foo=bar") |
| 76 |
self.assertEqual(q["foo"], "bar") |
| 77 |
with self.assertRaises(KeyError): |
| 78 |
q.__getitem__("bar") |
| 79 |
with self.assertRaises(AttributeError): |
| 80 |
q.__setitem__("something", "bar") |
| 81 |
|
| 82 |
self.assertEqual(q.get("foo", "default"), "bar") |
| 83 |
self.assertEqual(q.get("bar", "default"), "default") |
| 84 |
self.assertEqual(q.getlist("foo"), ["bar"]) |
| 85 |
self.assertEqual(q.getlist("bar"), []) |
| 86 |
|
| 87 |
with self.assertRaises(AttributeError): |
| 88 |
q.setlist("foo", ["bar"]) |
| 89 |
with self.assertRaises(AttributeError): |
| 90 |
q.appendlist("foo", ["bar"]) |
| 91 |
|
| 92 |
self.assertIn("foo", q) |
| 93 |
self.assertNotIn("bar", q) |
| 94 |
|
| 95 |
self.assertEqual(list(q), ["foo"]) |
| 96 |
self.assertEqual(list(q.items()), [("foo", "bar")]) |
| 97 |
self.assertEqual(list(q.lists()), [("foo", ["bar"])]) |
| 98 |
self.assertEqual(list(q.keys()), ["foo"]) |
| 99 |
self.assertEqual(list(q.values()), ["bar"]) |
| 100 |
self.assertEqual(len(q), 1) |
| 101 |
|
| 102 |
with self.assertRaises(AttributeError): |
| 103 |
q.update({"foo": "bar"}) |
| 104 |
with self.assertRaises(AttributeError): |
| 105 |
q.pop("foo") |
| 106 |
with self.assertRaises(AttributeError): |
| 107 |
q.popitem() |
| 108 |
with self.assertRaises(AttributeError): |
| 109 |
q.clear() |
| 110 |
with self.assertRaises(AttributeError): |
| 111 |
q.setdefault("foo", "bar") |
| 112 |
|
| 113 |
self.assertEqual(q.urlencode(), "foo=bar") |
| 114 |
|
| 115 |
def test_urlencode(self): |
| 116 |
q = QueryDict(mutable=True) |
| 117 |
q["next"] = "/a&b/" |
| 118 |
self.assertEqual(q.urlencode(), "next=%2Fa%26b%2F") |
| 119 |
self.assertEqual(q.urlencode(safe="/"), "next=/a%26b/") |
| 120 |
q = QueryDict(mutable=True) |
| 121 |
q["next"] = "/t\xebst&key/" |
| 122 |
self.assertEqual(q.urlencode(), "next=%2Ft%C3%ABst%26key%2F") |
| 123 |
self.assertEqual(q.urlencode(safe="/"), "next=/t%C3%ABst%26key/") |
| 124 |
|
| 125 |
def test_urlencode_int(self): |
| 126 |
# Normally QueryDict doesn't contain non-string values but lazily |
| 127 |
# written tests may make that mistake. |
| 128 |
q = QueryDict(mutable=True) |
| 129 |
q["a"] = 1 |
| 130 |
self.assertEqual(q.urlencode(), "a=1") |
| 131 |
|
| 132 |
def test_mutable_copy(self): |
| 133 |
"""A copy of a QueryDict is mutable.""" |
| 134 |
q = QueryDict().copy() |
| 135 |
with self.assertRaises(KeyError): |
| 136 |
q.__getitem__("foo") |
| 137 |
q["name"] = "john" |
| 138 |
self.assertEqual(q["name"], "john") |
| 139 |
|
| 140 |
def test_mutable_delete(self): |
| 141 |
q = QueryDict(mutable=True) |
| 142 |
q["name"] = "john" |
| 143 |
del q["name"] |
| 144 |
self.assertNotIn("name", q) |
| 145 |
|
| 146 |
def test_basic_mutable_operations(self): |
| 147 |
q = QueryDict(mutable=True) |
| 148 |
q["name"] = "john" |
| 149 |
self.assertEqual(q.get("foo", "default"), "default") |
| 150 |
self.assertEqual(q.get("name", "default"), "john") |
| 151 |
self.assertEqual(q.getlist("name"), ["john"]) |
| 152 |
self.assertEqual(q.getlist("foo"), []) |
| 153 |
|
| 154 |
q.setlist("foo", ["bar", "baz"]) |
| 155 |
self.assertEqual(q.get("foo", "default"), "baz") |
| 156 |
self.assertEqual(q.getlist("foo"), ["bar", "baz"]) |
| 157 |
|
| 158 |
q.appendlist("foo", "another") |
| 159 |
self.assertEqual(q.getlist("foo"), ["bar", "baz", "another"]) |
| 160 |
self.assertEqual(q["foo"], "another") |
| 161 |
self.assertIn("foo", q) |
| 162 |
|
| 163 |
self.assertCountEqual(q, ["foo", "name"]) |
| 164 |
self.assertCountEqual(q.items(), [("foo", "another"), ("name", "john")]) |
| 165 |
self.assertCountEqual( |
| 166 |
q.lists(), [("foo", ["bar", "baz", "another"]), ("name", ["john"])] |
| 167 |
) |
| 168 |
self.assertCountEqual(q.keys(), ["foo", "name"]) |
| 169 |
self.assertCountEqual(q.values(), ["another", "john"]) |
| 170 |
|
| 171 |
q.update({"foo": "hello"}) |
| 172 |
self.assertEqual(q["foo"], "hello") |
| 173 |
self.assertEqual(q.get("foo", "not available"), "hello") |
| 174 |
self.assertEqual(q.getlist("foo"), ["bar", "baz", "another", "hello"]) |
| 175 |
self.assertEqual(q.pop("foo"), ["bar", "baz", "another", "hello"]) |
| 176 |
self.assertEqual(q.pop("foo", "not there"), "not there") |
| 177 |
self.assertEqual(q.get("foo", "not there"), "not there") |
| 178 |
self.assertEqual(q.setdefault("foo", "bar"), "bar") |
| 179 |
self.assertEqual(q["foo"], "bar") |
| 180 |
self.assertEqual(q.getlist("foo"), ["bar"]) |
| 181 |
self.assertIn(q.urlencode(), ["foo=bar&name=john", "name=john&foo=bar"]) |
| 182 |
|
| 183 |
q.clear() |
| 184 |
self.assertEqual(len(q), 0) |
| 185 |
|
| 186 |
def test_multiple_keys(self): |
| 187 |
"""Test QueryDict with two key/value pairs with same keys.""" |
| 188 |
|
| 189 |
q = QueryDict("vote=yes&vote=no") |
| 190 |
|
| 191 |
self.assertEqual(q["vote"], "no") |
| 192 |
with self.assertRaises(AttributeError): |
| 193 |
q.__setitem__("something", "bar") |
| 194 |
|
| 195 |
self.assertEqual(q.get("vote", "default"), "no") |
| 196 |
self.assertEqual(q.get("foo", "default"), "default") |
| 197 |
self.assertEqual(q.getlist("vote"), ["yes", "no"]) |
| 198 |
self.assertEqual(q.getlist("foo"), []) |
| 199 |
|
| 200 |
with self.assertRaises(AttributeError): |
| 201 |
q.setlist("foo", ["bar", "baz"]) |
| 202 |
with self.assertRaises(AttributeError): |
| 203 |
q.setlist("foo", ["bar", "baz"]) |
| 204 |
with self.assertRaises(AttributeError): |
| 205 |
q.appendlist("foo", ["bar"]) |
| 206 |
|
| 207 |
self.assertIn("vote", q) |
| 208 |
self.assertNotIn("foo", q) |
| 209 |
self.assertEqual(list(q), ["vote"]) |
| 210 |
self.assertEqual(list(q.items()), [("vote", "no")]) |
| 211 |
self.assertEqual(list(q.lists()), [("vote", ["yes", "no"])]) |
| 212 |
self.assertEqual(list(q.keys()), ["vote"]) |
| 213 |
self.assertEqual(list(q.values()), ["no"]) |
| 214 |
self.assertEqual(len(q), 1) |
| 215 |
|
| 216 |
with self.assertRaises(AttributeError): |
| 217 |
q.update({"foo": "bar"}) |
| 218 |
with self.assertRaises(AttributeError): |
| 219 |
q.pop("foo") |
| 220 |
with self.assertRaises(AttributeError): |
| 221 |
q.popitem() |
| 222 |
with self.assertRaises(AttributeError): |
| 223 |
q.clear() |
| 224 |
with self.assertRaises(AttributeError): |
| 225 |
q.setdefault("foo", "bar") |
| 226 |
with self.assertRaises(AttributeError): |
| 227 |
q.__delitem__("vote") |
| 228 |
|
| 229 |
def test_pickle(self): |
| 230 |
q = QueryDict() |
| 231 |
q1 = pickle.loads(pickle.dumps(q, 2)) |
| 232 |
self.assertEqual(q, q1) |
| 233 |
q = QueryDict("a=b&c=d") |
| 234 |
q1 = pickle.loads(pickle.dumps(q, 2)) |
| 235 |
self.assertEqual(q, q1) |
| 236 |
q = QueryDict("a=b&c=d&a=1") |
| 237 |
q1 = pickle.loads(pickle.dumps(q, 2)) |
| 238 |
self.assertEqual(q, q1) |
| 239 |
|
| 240 |
def test_update_from_querydict(self): |
| 241 |
"""Regression test for #8278: QueryDict.update(QueryDict)""" |
| 242 |
x = QueryDict("a=1&a=2", mutable=True) |
| 243 |
y = QueryDict("a=3&a=4") |
| 244 |
x.update(y) |
| 245 |
self.assertEqual(x.getlist("a"), ["1", "2", "3", "4"]) |
| 246 |
|
| 247 |
def test_non_default_encoding(self): |
| 248 |
"""#13572 - QueryDict with a non-default encoding""" |
| 249 |
q = QueryDict("cur=%A4", encoding="iso-8859-15") |
| 250 |
self.assertEqual(q.encoding, "iso-8859-15") |
| 251 |
self.assertEqual(list(q.items()), [("cur", "€")]) |
| 252 |
self.assertEqual(q.urlencode(), "cur=%A4") |
| 253 |
q = q.copy() |
| 254 |
self.assertEqual(q.encoding, "iso-8859-15") |
| 255 |
self.assertEqual(list(q.items()), [("cur", "€")]) |
| 256 |
self.assertEqual(q.urlencode(), "cur=%A4") |
| 257 |
self.assertEqual(copy.copy(q).encoding, "iso-8859-15") |
| 258 |
self.assertEqual(copy.deepcopy(q).encoding, "iso-8859-15") |
| 259 |
|
| 260 |
def test_querydict_fromkeys(self): |
| 261 |
self.assertEqual( |
| 262 |
QueryDict.fromkeys(["key1", "key2", "key3"]), QueryDict("key1&key2&key3") |
| 263 |
) |
| 264 |
|
| 265 |
def test_fromkeys_with_nonempty_value(self): |
| 266 |
self.assertEqual( |
| 267 |
QueryDict.fromkeys(["key1", "key2", "key3"], value="val"), |
| 268 |
QueryDict("key1=val&key2=val&key3=val"), |
| 269 |
) |
| 270 |
|
| 271 |
def test_fromkeys_is_immutable_by_default(self): |
| 272 |
# Match behavior of __init__() which is also immutable by default. |
| 273 |
q = QueryDict.fromkeys(["key1", "key2", "key3"]) |
| 274 |
with self.assertRaisesMessage( |
| 275 |
AttributeError, "This QueryDict instance is immutable" |
| 276 |
): |
| 277 |
q["key4"] = "nope" |
| 278 |
|
| 279 |
def test_fromkeys_mutable_override(self): |
| 280 |
q = QueryDict.fromkeys(["key1", "key2", "key3"], mutable=True) |
| 281 |
q["key4"] = "yep" |
| 282 |
self.assertEqual(q, QueryDict("key1&key2&key3&key4=yep")) |
| 283 |
|
| 284 |
def test_duplicates_in_fromkeys_iterable(self): |
| 285 |
self.assertEqual(QueryDict.fromkeys("xyzzy"), QueryDict("x&y&z&z&y")) |
| 286 |
|
| 287 |
def test_fromkeys_with_nondefault_encoding(self): |
| 288 |
key_utf16 = b"\xff\xfe\x8e\x02\xdd\x01\x9e\x02" |
| 289 |
value_utf16 = b"\xff\xfe\xdd\x01n\x00l\x00P\x02\x8c\x02" |
| 290 |
q = QueryDict.fromkeys([key_utf16], value=value_utf16, encoding="utf-16") |
| 291 |
expected = QueryDict("", mutable=True) |
| 292 |
expected["ʎǝʞ"] = "ǝnlɐʌ" |
| 293 |
self.assertEqual(q, expected) |
| 294 |
|
| 295 |
def test_fromkeys_empty_iterable(self): |
| 296 |
self.assertEqual(QueryDict.fromkeys([]), QueryDict("")) |
| 297 |
|
| 298 |
def test_fromkeys_noniterable(self): |
| 299 |
with self.assertRaises(TypeError): |
| 300 |
QueryDict.fromkeys(0) |
| 301 |
|
| 302 |
|
| 303 |
class HttpResponseTests(SimpleTestCase): |
| 304 |
def test_headers_type(self): |
| 305 |
r = HttpResponse() |
| 306 |
|
| 307 |
# ASCII strings or bytes values are converted to strings. |
| 308 |
r.headers["key"] = "test" |
| 309 |
self.assertEqual(r.headers["key"], "test") |
| 310 |
r.headers["key"] = b"test" |
| 311 |
self.assertEqual(r.headers["key"], "test") |
| 312 |
self.assertIn(b"test", r.serialize_headers()) |
| 313 |
|
| 314 |
# Non-ASCII values are serialized to Latin-1. |
| 315 |
r.headers["key"] = "café" |
| 316 |
self.assertIn("café".encode("latin-1"), r.serialize_headers()) |
| 317 |
|
| 318 |
# Other Unicode values are MIME-encoded (there's no way to pass them as |
| 319 |
# bytes). |
| 320 |
r.headers["key"] = "†" |
| 321 |
self.assertEqual(r.headers["key"], "=?utf-8?b?4oCg?=") |
| 322 |
self.assertIn(b"=?utf-8?b?4oCg?=", r.serialize_headers()) |
| 323 |
|
| 324 |
# The response also converts string or bytes keys to strings, but requires |
| 325 |
# them to contain ASCII |
| 326 |
r = HttpResponse() |
| 327 |
del r.headers["Content-Type"] |
| 328 |
r.headers["foo"] = "bar" |
| 329 |
headers = list(r.headers.items()) |
| 330 |
self.assertEqual(len(headers), 1) |
| 331 |
self.assertEqual(headers[0], ("foo", "bar")) |
| 332 |
|
| 333 |
r = HttpResponse() |
| 334 |
del r.headers["Content-Type"] |
| 335 |
r.headers[b"foo"] = "bar" |
| 336 |
headers = list(r.headers.items()) |
| 337 |
self.assertEqual(len(headers), 1) |
| 338 |
self.assertEqual(headers[0], ("foo", "bar")) |
| 339 |
self.assertIsInstance(headers[0][0], str) |
| 340 |
|
| 341 |
r = HttpResponse() |
| 342 |
with self.assertRaises(UnicodeError): |
| 343 |
r.headers.__setitem__("føø", "bar") |
| 344 |
with self.assertRaises(UnicodeError): |
| 345 |
r.headers.__setitem__("føø".encode(), "bar") |
| 346 |
|
| 347 |
def test_long_line(self): |
| 348 |
# Bug #20889: long lines trigger newlines to be added to headers |
| 349 |
# (which is not allowed due to bug #10188) |
| 350 |
h = HttpResponse() |
| 351 |
f = b"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz a\xcc\x88" |
| 352 |
f = f.decode("utf-8") |
| 353 |
h.headers["Content-Disposition"] = 'attachment; filename="%s"' % f |
| 354 |
# This one is triggering https://bugs.python.org/issue20747, that is Python |
| 355 |
# will itself insert a newline in the header |
| 356 |
h.headers["Content-Disposition"] = ( |
| 357 |
'attachment; filename="EdelRot_Blu\u0308te (3)-0.JPG"' |
| 358 |
) |
| 359 |
|
| 360 |
def test_newlines_in_headers(self): |
| 361 |
# Bug #10188: Do not allow newlines in headers (CR or LF) |
| 362 |
r = HttpResponse() |
| 363 |
with self.assertRaises(BadHeaderError): |
| 364 |
r.headers.__setitem__("test\rstr", "test") |
| 365 |
with self.assertRaises(BadHeaderError): |
| 366 |
r.headers.__setitem__("test\nstr", "test") |
| 367 |
|
| 368 |
def test_encoded_with_newlines_in_headers(self): |
| 369 |
""" |
| 370 |
Keys & values which throw a UnicodeError when encoding/decoding should |
| 371 |
still be checked for newlines and re-raised as a BadHeaderError. |
| 372 |
These specifically would still throw BadHeaderError after decoding |
| 373 |
successfully, because the newlines are sandwiched in the middle of the |
| 374 |
string and email.Header leaves those as they are. |
| 375 |
""" |
| 376 |
r = HttpResponse() |
| 377 |
pairs = ( |
| 378 |
("†\nother", "test"), |
| 379 |
("test", "†\nother"), |
| 380 |
(b"\xe2\x80\xa0\nother", "test"), |
| 381 |
("test", b"\xe2\x80\xa0\nother"), |
| 382 |
) |
| 383 |
msg = "Header values can't contain newlines" |
| 384 |
for key, value in pairs: |
| 385 |
with self.subTest(key=key, value=value): |
| 386 |
with self.assertRaisesMessage(BadHeaderError, msg): |
| 387 |
r[key] = value |
| 388 |
|
| 389 |
def test_dict_behavior(self): |
| 390 |
""" |
| 391 |
Test for bug #14020: Make HttpResponse.get work like dict.get |
| 392 |
""" |
| 393 |
r = HttpResponse() |
| 394 |
self.assertIsNone(r.get("test")) |
| 395 |
|
| 396 |
def test_non_string_content(self): |
| 397 |
# Bug 16494: HttpResponse should behave consistently with non-strings |
| 398 |
r = HttpResponse(12345) |
| 399 |
self.assertEqual(r.content, b"12345") |
| 400 |
|
| 401 |
# test content via property |
| 402 |
r = HttpResponse() |
| 403 |
r.content = 12345 |
| 404 |
self.assertEqual(r.content, b"12345") |
| 405 |
|
| 406 |
def test_memoryview_content(self): |
| 407 |
r = HttpResponse(memoryview(b"memoryview")) |
| 408 |
self.assertEqual(r.content, b"memoryview") |
| 409 |
|
| 410 |
def test_iter_content(self): |
| 411 |
r = HttpResponse(["abc", "def", "ghi"]) |
| 412 |
self.assertEqual(r.content, b"abcdefghi") |
| 413 |
|
| 414 |
# test iter content via property |
| 415 |
r = HttpResponse() |
| 416 |
r.content = ["idan", "alex", "jacob"] |
| 417 |
self.assertEqual(r.content, b"idanalexjacob") |
| 418 |
|
| 419 |
r = HttpResponse() |
| 420 |
r.content = [1, 2, 3] |
| 421 |
self.assertEqual(r.content, b"123") |
| 422 |
|
| 423 |
# test odd inputs |
| 424 |
r = HttpResponse() |
| 425 |
r.content = ["1", "2", 3, "\u079e"] |
| 426 |
# '\xde\x9e' == unichr(1950).encode() |
| 427 |
self.assertEqual(r.content, b"123\xde\x9e") |
| 428 |
|
| 429 |
# .content can safely be accessed multiple times. |
| 430 |
r = HttpResponse(iter(["hello", "world"])) |
| 431 |
self.assertEqual(r.content, r.content) |
| 432 |
self.assertEqual(r.content, b"helloworld") |
| 433 |
# __iter__ can safely be called multiple times (#20187). |
| 434 |
self.assertEqual(b"".join(r), b"helloworld") |
| 435 |
self.assertEqual(b"".join(r), b"helloworld") |
| 436 |
# Accessing .content still works. |
| 437 |
self.assertEqual(r.content, b"helloworld") |
| 438 |
|
| 439 |
# Accessing .content also works if the response was iterated first. |
| 440 |
r = HttpResponse(iter(["hello", "world"])) |
| 441 |
self.assertEqual(b"".join(r), b"helloworld") |
| 442 |
self.assertEqual(r.content, b"helloworld") |
| 443 |
|
| 444 |
# Additional content can be written to the response. |
| 445 |
r = HttpResponse(iter(["hello", "world"])) |
| 446 |
self.assertEqual(r.content, b"helloworld") |
| 447 |
r.write("!") |
| 448 |
self.assertEqual(r.content, b"helloworld!") |
| 449 |
|
| 450 |
def test_iterator_isnt_rewound(self): |
| 451 |
# Regression test for #13222 |
| 452 |
r = HttpResponse("abc") |
| 453 |
i = iter(r) |
| 454 |
self.assertEqual(list(i), [b"abc"]) |
| 455 |
self.assertEqual(list(i), []) |
| 456 |
|
| 457 |
def test_lazy_content(self): |
| 458 |
r = HttpResponse(lazystr("helloworld")) |
| 459 |
self.assertEqual(r.content, b"helloworld") |
| 460 |
|
| 461 |
def test_file_interface(self): |
| 462 |
r = HttpResponse() |
| 463 |
r.write(b"hello") |
| 464 |
self.assertEqual(r.tell(), 5) |
| 465 |
r.write("привет") |
| 466 |
self.assertEqual(r.tell(), 17) |
| 467 |
|
| 468 |
r = HttpResponse(["abc"]) |
| 469 |
r.write("def") |
| 470 |
self.assertEqual(r.tell(), 6) |
| 471 |
self.assertEqual(r.content, b"abcdef") |
| 472 |
|
| 473 |
# with Content-Encoding header |
| 474 |
r = HttpResponse() |
| 475 |
r.headers["Content-Encoding"] = "winning" |
| 476 |
r.write(b"abc") |
| 477 |
r.write(b"def") |
| 478 |
self.assertEqual(r.content, b"abcdef") |
| 479 |
|
| 480 |
def test_stream_interface(self): |
| 481 |
r = HttpResponse("asdf") |
| 482 |
self.assertEqual(r.getvalue(), b"asdf") |
| 483 |
|
| 484 |
r = HttpResponse() |
| 485 |
self.assertIs(r.writable(), True) |
| 486 |
r.writelines(["foo\n", "bar\n", "baz\n"]) |
| 487 |
self.assertEqual(r.content, b"foo\nbar\nbaz\n") |
| 488 |
|
| 489 |
def test_redirect_url_max_length(self): |
| 490 |
base_url = "https://example.com/" |
| 491 |
for length in ( |
| 492 |
MAX_URL_REDIRECT_LENGTH - 1, |
| 493 |
MAX_URL_REDIRECT_LENGTH, |
| 494 |
): |
| 495 |
long_url = base_url + "x" * (length - len(base_url)) |
| 496 |
with self.subTest(length=length): |
| 497 |
response = HttpResponseRedirect(long_url) |
| 498 |
self.assertEqual(response.url, long_url) |
| 499 |
response = HttpResponsePermanentRedirect(long_url) |
| 500 |
self.assertEqual(response.url, long_url) |
| 501 |
|
| 502 |
def test_unsafe_redirect(self): |
| 503 |
bad_urls = [ |
| 504 |
'data:text/html,<script>window.alert("xss")</script>', |
| 505 |
"mailto:[email protected]", |
| 506 |
"file:///etc/passwd", |
| 507 |
"é" * (MAX_URL_REDIRECT_LENGTH + 1), |
| 508 |
] |
| 509 |
for url in bad_urls: |
| 510 |
with self.assertRaises(DisallowedRedirect): |
| 511 |
HttpResponseRedirect(url) |
| 512 |
with self.assertRaises(DisallowedRedirect): |
| 513 |
HttpResponsePermanentRedirect(url) |
| 514 |
|
| 515 |
def test_header_deletion(self): |
| 516 |
r = HttpResponse("hello") |
| 517 |
r.headers["X-Foo"] = "foo" |
| 518 |
del r.headers["X-Foo"] |
| 519 |
self.assertNotIn("X-Foo", r.headers) |
| 520 |
# del doesn't raise a KeyError on nonexistent headers. |
| 521 |
del r.headers["X-Foo"] |
| 522 |
|
| 523 |
def test_instantiate_with_headers(self): |
| 524 |
r = HttpResponse("hello", headers={"X-Foo": "foo"}) |
| 525 |
self.assertEqual(r.headers["X-Foo"], "foo") |
| 526 |
self.assertEqual(r.headers["x-foo"], "foo") |
| 527 |
|
| 528 |
def test_content_type(self): |
| 529 |
r = HttpResponse("hello", content_type="application/json") |
| 530 |
self.assertEqual(r.headers["Content-Type"], "application/json") |
| 531 |
|
| 532 |
def test_content_type_headers(self): |
| 533 |
r = HttpResponse("hello", headers={"Content-Type": "application/json"}) |
| 534 |
self.assertEqual(r.headers["Content-Type"], "application/json") |
| 535 |
|
| 536 |
def test_content_type_mutually_exclusive(self): |
| 537 |
msg = ( |
| 538 |
"'headers' must not contain 'Content-Type' when the " |
| 539 |
"'content_type' parameter is provided." |
| 540 |
) |
| 541 |
with self.assertRaisesMessage(ValueError, msg): |
| 542 |
HttpResponse( |
| 543 |
"hello", |
| 544 |
content_type="application/json", |
| 545 |
headers={"Content-Type": "text/csv"}, |
| 546 |
) |
| 547 |
|
| 548 |
def test_text_updates_when_content_updates(self): |
| 549 |
response = HttpResponse("Hello, world!") |
| 550 |
self.assertEqual(response.text, "Hello, world!") |
| 551 |
response.content = "Updated content" |
| 552 |
self.assertEqual(response.text, "Updated content") |
| 553 |
|
| 554 |
def test_text_charset(self): |
| 555 |
for content_type, content in [ |
| 556 |
(None, b"Ol\xc3\xa1 Mundo"), |
| 557 |
("text/plain; charset=utf-8", b"Ol\xc3\xa1 Mundo"), |
| 558 |
("text/plain; charset=iso-8859-1", b"Ol\xe1 Mundo"), |
| 559 |
]: |
| 560 |
with self.subTest(content_type=content_type): |
| 561 |
response = HttpResponse(content, content_type=content_type) |
| 562 |
self.assertEqual(response.text, "Olá Mundo") |
| 563 |
|
| 564 |
|
| 565 |
class HttpResponseSubclassesTests(SimpleTestCase): |
| 566 |
def test_redirect(self): |
| 567 |
response = HttpResponseRedirect("/redirected/") |
| 568 |
self.assertEqual(response.status_code, 302) |
| 569 |
# Standard HttpResponse init args can be used |
| 570 |
response = HttpResponseRedirect( |
| 571 |
"/redirected/", |
| 572 |
content="The resource has temporarily moved", |
| 573 |
) |
| 574 |
self.assertContains( |
| 575 |
response, "The resource has temporarily moved", status_code=302 |
| 576 |
) |
| 577 |
self.assertEqual(response.url, response.headers["Location"]) |
| 578 |
|
| 579 |
def test_redirect_lazy(self): |
| 580 |
"""Make sure HttpResponseRedirect works with lazy strings.""" |
| 581 |
r = HttpResponseRedirect(lazystr("/redirected/")) |
| 582 |
self.assertEqual(r.url, "/redirected/") |
| 583 |
|
| 584 |
def test_redirect_modifiers(self): |
| 585 |
cases = [ |
| 586 |
(HttpResponseRedirect, "Moved temporarily", False, 302), |
| 587 |
(HttpResponseRedirect, "Moved temporarily preserve method", True, 307), |
| 588 |
(HttpResponsePermanentRedirect, "Moved permanently", False, 301), |
| 589 |
( |
| 590 |
HttpResponsePermanentRedirect, |
| 591 |
"Moved permanently preserve method", |
| 592 |
True, |
| 593 |
308, |
| 594 |
), |
| 595 |
] |
| 596 |
for response_class, content, preserve_request, expected_status_code in cases: |
| 597 |
with self.subTest(status_code=expected_status_code): |
| 598 |
response = response_class( |
| 599 |
"/redirected/", content=content, preserve_request=preserve_request |
| 600 |
) |
| 601 |
self.assertEqual(response.status_code, expected_status_code) |
| 602 |
self.assertEqual(response.content.decode(), content) |
| 603 |
self.assertEqual(response.url, response.headers["Location"]) |
| 604 |
|
| 605 |
def test_redirect_repr(self): |
| 606 |
response = HttpResponseRedirect("/redirected/") |
| 607 |
expected = ( |
| 608 |
'<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", ' |
| 609 |
'url="/redirected/">' |
| 610 |
) |
| 611 |
self.assertEqual(repr(response), expected) |
| 612 |
|
| 613 |
def test_invalid_redirect_repr(self): |
| 614 |
""" |
| 615 |
If HttpResponseRedirect raises DisallowedRedirect, its __repr__() |
| 616 |
should work (in the debug view, for example). |
| 617 |
""" |
| 618 |
response = HttpResponseRedirect.__new__(HttpResponseRedirect) |
| 619 |
with self.assertRaisesMessage( |
| 620 |
DisallowedRedirect, "Unsafe redirect to URL with protocol 'ssh'" |
| 621 |
): |
| 622 |
HttpResponseRedirect.__init__(response, "ssh://foo") |
| 623 |
expected = ( |
| 624 |
'<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", ' |
| 625 |
'url="ssh://foo">' |
| 626 |
) |
| 627 |
self.assertEqual(repr(response), expected) |
| 628 |
|
| 629 |
def test_not_modified(self): |
| 630 |
response = HttpResponseNotModified() |
| 631 |
self.assertEqual(response.status_code, 304) |
| 632 |
# 304 responses should not have content/content-type |
| 633 |
with self.assertRaises(AttributeError): |
| 634 |
response.content = "Hello dear" |
| 635 |
self.assertNotIn("content-type", response) |
| 636 |
|
| 637 |
def test_not_modified_repr(self): |
| 638 |
response = HttpResponseNotModified() |
| 639 |
self.assertEqual(repr(response), "<HttpResponseNotModified status_code=304>") |
| 640 |
|
| 641 |
def test_not_allowed(self): |
| 642 |
response = HttpResponseNotAllowed(["GET"]) |
| 643 |
self.assertEqual(response.status_code, 405) |
| 644 |
# Standard HttpResponse init args can be used |
| 645 |
response = HttpResponseNotAllowed( |
| 646 |
["GET"], content="Only the GET method is allowed" |
| 647 |
) |
| 648 |
self.assertContains(response, "Only the GET method is allowed", status_code=405) |
| 649 |
|
| 650 |
def test_not_allowed_repr(self): |
| 651 |
response = HttpResponseNotAllowed(["GET", "OPTIONS"], content_type="text/plain") |
| 652 |
expected = ( |
| 653 |
'<HttpResponseNotAllowed [GET, OPTIONS] status_code=405, "text/plain">' |
| 654 |
) |
| 655 |
self.assertEqual(repr(response), expected) |
| 656 |
|
| 657 |
def test_not_allowed_repr_no_content_type(self): |
| 658 |
response = HttpResponseNotAllowed(("GET", "POST")) |
| 659 |
del response.headers["Content-Type"] |
| 660 |
self.assertEqual( |
| 661 |
repr(response), "<HttpResponseNotAllowed [GET, POST] status_code=405>" |
| 662 |
) |
| 663 |
|
| 664 |
|
| 665 |
class JsonResponseTests(SimpleTestCase): |
| 666 |
def test_json_response_non_ascii(self): |
| 667 |
data = {"key": "łóżko"} |
| 668 |
response = JsonResponse(data) |
| 669 |
self.assertEqual(json.loads(response.text), data) |
| 670 |
|
| 671 |
def test_json_response_raises_type_error_with_default_setting(self): |
| 672 |
with self.assertRaisesMessage( |
| 673 |
TypeError, |
| 674 |
"In order to allow non-dict objects to be serialized set the " |
| 675 |
"safe parameter to False", |
| 676 |
): |
| 677 |
JsonResponse([1, 2, 3]) |
| 678 |
|
| 679 |
def test_json_response_text(self): |
| 680 |
response = JsonResponse("foobar", safe=False) |
| 681 |
self.assertEqual(json.loads(response.text), "foobar") |
| 682 |
|
| 683 |
def test_json_response_list(self): |
| 684 |
response = JsonResponse(["foo", "bar"], safe=False) |
| 685 |
self.assertEqual(json.loads(response.text), ["foo", "bar"]) |
| 686 |
|
| 687 |
def test_json_response_uuid(self): |
| 688 |
u = uuid.uuid4() |
| 689 |
response = JsonResponse(u, safe=False) |
| 690 |
self.assertEqual(json.loads(response.text), str(u)) |
| 691 |
|
| 692 |
def test_json_response_custom_encoder(self): |
| 693 |
class CustomDjangoJSONEncoder(DjangoJSONEncoder): |
| 694 |
def encode(self, o): |
| 695 |
return json.dumps({"foo": "bar"}) |
| 696 |
|
| 697 |
response = JsonResponse({}, encoder=CustomDjangoJSONEncoder) |
| 698 |
self.assertEqual(json.loads(response.text), {"foo": "bar"}) |
| 699 |
|
| 700 |
def test_json_response_passing_arguments_to_json_dumps(self): |
| 701 |
response = JsonResponse({"foo": "bar"}, json_dumps_params={"indent": 2}) |
| 702 |
self.assertEqual(response.text, '{\n "foo": "bar"\n}') |
| 703 |
|
| 704 |
|
| 705 |
class StreamingHttpResponseTests(SimpleTestCase): |
| 706 |
def test_streaming_response(self): |
| 707 |
r = StreamingHttpResponse(iter(["hello", "world"])) |
| 708 |
|
| 709 |
# iterating over the response itself yields bytestring chunks. |
| 710 |
chunks = list(r) |
| 711 |
self.assertEqual(chunks, [b"hello", b"world"]) |
| 712 |
for chunk in chunks: |
| 713 |
self.assertIsInstance(chunk, bytes) |
| 714 |
|
| 715 |
# and the response can only be iterated once. |
| 716 |
self.assertEqual(list(r), []) |
| 717 |
|
| 718 |
# even when a sequence that can be iterated many times, like a list, |
| 719 |
# is given as content. |
| 720 |
r = StreamingHttpResponse(["abc", "def"]) |
| 721 |
self.assertEqual(list(r), [b"abc", b"def"]) |
| 722 |
self.assertEqual(list(r), []) |
| 723 |
|
| 724 |
# iterating over strings still yields bytestring chunks. |
| 725 |
r.streaming_content = iter(["hello", "café"]) |
| 726 |
chunks = list(r) |
| 727 |
# '\xc3\xa9' == unichr(233).encode() |
| 728 |
self.assertEqual(chunks, [b"hello", b"caf\xc3\xa9"]) |
| 729 |
for chunk in chunks: |
| 730 |
self.assertIsInstance(chunk, bytes) |
| 731 |
|
| 732 |
# streaming responses don't have a `content` attribute. |
| 733 |
self.assertFalse(hasattr(r, "content")) |
| 734 |
|
| 735 |
# and you can't accidentally assign to a `content` attribute. |
| 736 |
with self.assertRaises(AttributeError): |
| 737 |
r.content = "xyz" |
| 738 |
|
| 739 |
# but they do have a `streaming_content` attribute. |
| 740 |
self.assertTrue(hasattr(r, "streaming_content")) |
| 741 |
|
| 742 |
# that exists so we can check if a response is streaming, and wrap or |
| 743 |
# replace the content iterator. |
| 744 |
r.streaming_content = iter(["abc", "def"]) |
| 745 |
r.streaming_content = (chunk.upper() for chunk in r.streaming_content) |
| 746 |
self.assertEqual(list(r), [b"ABC", b"DEF"]) |
| 747 |
|
| 748 |
# coercing a streaming response to bytes doesn't return a complete HTTP |
| 749 |
# message like a regular response does. it only gives us the headers. |
| 750 |
r = StreamingHttpResponse(iter(["hello", "world"])) |
| 751 |
self.assertEqual(bytes(r), b"Content-Type: text/html; charset=utf-8") |
| 752 |
|
| 753 |
# and this won't consume its content. |
| 754 |
self.assertEqual(list(r), [b"hello", b"world"]) |
| 755 |
|
| 756 |
# additional content cannot be written to the response. |
| 757 |
r = StreamingHttpResponse(iter(["hello", "world"])) |
| 758 |
with self.assertRaises(Exception): |
| 759 |
r.write("!") |
| 760 |
|
| 761 |
# and we can't tell the current position. |
| 762 |
with self.assertRaises(Exception): |
| 763 |
r.tell() |
| 764 |
|
| 765 |
r = StreamingHttpResponse(iter(["hello", "world"])) |
| 766 |
self.assertEqual(r.getvalue(), b"helloworld") |
| 767 |
|
| 768 |
def test_repr(self): |
| 769 |
r = StreamingHttpResponse(iter(["hello", "café"])) |
| 770 |
self.assertEqual( |
| 771 |
repr(r), |
| 772 |
'<StreamingHttpResponse status_code=200, "text/html; charset=utf-8">', |
| 773 |
) |
| 774 |
|
| 775 |
async def test_async_streaming_response(self): |
| 776 |
async def async_iter(): |
| 777 |
yield b"hello" |
| 778 |
yield b"world" |
| 779 |
|
| 780 |
r = StreamingHttpResponse(async_iter()) |
| 781 |
|
| 782 |
chunks = [] |
| 783 |
async for chunk in r: |
| 784 |
chunks.append(chunk) |
| 785 |
self.assertEqual(chunks, [b"hello", b"world"]) |
| 786 |
|
| 787 |
def test_async_streaming_response_warning(self): |
| 788 |
async def async_iter(): |
| 789 |
yield b"hello" |
| 790 |
yield b"world" |
| 791 |
|
| 792 |
r = StreamingHttpResponse(async_iter()) |
| 793 |
|
| 794 |
msg = ( |
| 795 |
"StreamingHttpResponse must consume asynchronous iterators in order to " |
| 796 |
"serve them synchronously. Use a synchronous iterator instead." |
| 797 |
) |
| 798 |
with self.assertWarnsMessage(Warning, msg): |
| 799 |
self.assertEqual(list(r), [b"hello", b"world"]) |
| 800 |
|
| 801 |
async def test_sync_streaming_response_warning(self): |
| 802 |
r = StreamingHttpResponse(iter(["hello", "world"])) |
| 803 |
|
| 804 |
msg = ( |
| 805 |
"StreamingHttpResponse must consume synchronous iterators in order to " |
| 806 |
"serve them asynchronously. Use an asynchronous iterator instead." |
| 807 |
) |
| 808 |
with self.assertWarnsMessage(Warning, msg): |
| 809 |
self.assertEqual(b"hello", await anext(aiter(r))) |
| 810 |
|
| 811 |
def test_text_attribute_error(self): |
| 812 |
r = StreamingHttpResponse(iter(["hello", "world"])) |
| 813 |
msg = "This %s instance has no `text` attribute." % r.__class__.__name__ |
| 814 |
|
| 815 |
with self.assertRaisesMessage(AttributeError, msg): |
| 816 |
r.text |
| 817 |
|
| 818 |
|
| 819 |
class FileCloseTests(SimpleTestCase): |
| 820 |
def setUp(self): |
| 821 |
# Disable the request_finished signal during this test |
| 822 |
# to avoid interfering with the database connection. |
| 823 |
request_finished.disconnect(close_old_connections) |
| 824 |
self.addCleanup(request_finished.connect, close_old_connections) |
| 825 |
|
| 826 |
def test_response(self): |
| 827 |
filename = os.path.join(os.path.dirname(__file__), "abc.txt") |
| 828 |
|
| 829 |
# file isn't closed until we close the response. |
| 830 |
file1 = open(filename) |
| 831 |
r = HttpResponse(file1) |
| 832 |
self.assertTrue(file1.closed) |
| 833 |
r.close() |
| 834 |
|
| 835 |
# when multiple file are assigned as content, make sure they are all |
| 836 |
# closed with the response. |
| 837 |
file1 = open(filename) |
| 838 |
file2 = open(filename) |
| 839 |
r = HttpResponse(file1) |
| 840 |
r.content = file2 |
| 841 |
self.assertTrue(file1.closed) |
| 842 |
self.assertTrue(file2.closed) |
| 843 |
|
| 844 |
def test_streaming_response(self): |
| 845 |
filename = os.path.join(os.path.dirname(__file__), "abc.txt") |
| 846 |
|
| 847 |
# file isn't closed until we close the response. |
| 848 |
file1 = open(filename) |
| 849 |
r = StreamingHttpResponse(file1) |
| 850 |
self.assertFalse(file1.closed) |
| 851 |
r.close() |
| 852 |
self.assertTrue(file1.closed) |
| 853 |
|
| 854 |
# when multiple file are assigned as content, make sure they are all |
| 855 |
# closed with the response. |
| 856 |
file1 = open(filename) |
| 857 |
file2 = open(filename) |
| 858 |
r = StreamingHttpResponse(file1) |
| 859 |
r.streaming_content = file2 |
| 860 |
self.assertFalse(file1.closed) |
| 861 |
self.assertFalse(file2.closed) |
| 862 |
r.close() |
| 863 |
self.assertTrue(file1.closed) |
| 864 |
self.assertTrue(file2.closed) |
| 865 |
|
| 866 |
|
| 867 |
class CookieTests(unittest.TestCase): |
| 868 |
def test_encode(self): |
| 869 |
"""Semicolons and commas are encoded.""" |
| 870 |
c = SimpleCookie() |
| 871 |
c["test"] = "An,awkward;value" |
| 872 |
self.assertNotIn(";", c.output().rstrip(";")) # IE compat |
| 873 |
self.assertNotIn(",", c.output().rstrip(";")) # Safari compat |
| 874 |
|
| 875 |
def test_decode(self): |
| 876 |
"""Semicolons and commas are decoded.""" |
| 877 |
c = SimpleCookie() |
| 878 |
c["test"] = "An,awkward;value" |
| 879 |
c2 = SimpleCookie() |
| 880 |
c2.load(c.output()[12:]) |
| 881 |
self.assertEqual(c["test"].value, c2["test"].value) |
| 882 |
c3 = parse_cookie(c.output()[12:]) |
| 883 |
self.assertEqual(c["test"].value, c3["test"]) |
| 884 |
|
| 885 |
def test_nonstandard_keys(self): |
| 886 |
""" |
| 887 |
A single non-standard cookie name doesn't affect all cookies (#13007). |
| 888 |
""" |
| 889 |
self.assertIn("good_cookie", parse_cookie("good_cookie=yes;bad:cookie=yes")) |
| 890 |
|
| 891 |
def test_repeated_nonstandard_keys(self): |
| 892 |
""" |
| 893 |
A repeated non-standard name doesn't affect all cookies (#15852). |
| 894 |
""" |
| 895 |
self.assertIn("good_cookie", parse_cookie("a:=b; a:=c; good_cookie=yes")) |
| 896 |
|
| 897 |
def test_python_cookies(self): |
| 898 |
""" |
| 899 |
Test cases copied from Python's Lib/test/test_http_cookies.py |
| 900 |
""" |
| 901 |
self.assertEqual( |
| 902 |
parse_cookie("chips=ahoy; vienna=finger"), |
| 903 |
{"chips": "ahoy", "vienna": "finger"}, |
| 904 |
) |
| 905 |
# Here parse_cookie() differs from Python's cookie parsing in that it |
| 906 |
# treats all semicolons as delimiters, even within quotes. |
| 907 |
self.assertEqual( |
| 908 |
parse_cookie('keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;"'), |
| 909 |
{"keebler": '"E=mc2', "L": '\\"Loves\\"', "fudge": "\\012", "": '"'}, |
| 910 |
) |
| 911 |
# Illegal cookies that have an '=' char in an unquoted value. |
| 912 |
self.assertEqual(parse_cookie("keebler=E=mc2"), {"keebler": "E=mc2"}) |
| 913 |
# Cookies with ':' character in their name. |
| 914 |
self.assertEqual( |
| 915 |
parse_cookie("key:term=value:term"), {"key:term": "value:term"} |
| 916 |
) |
| 917 |
# Cookies with '[' and ']'. |
| 918 |
self.assertEqual( |
| 919 |
parse_cookie("a=b; c=[; d=r; f=h"), {"a": "b", "c": "[", "d": "r", "f": "h"} |
| 920 |
) |
| 921 |
|
| 922 |
def test_cookie_edgecases(self): |
| 923 |
# Cookies that RFC 6265 allows. |
| 924 |
self.assertEqual( |
| 925 |
parse_cookie("a=b; Domain=example.com"), {"a": "b", "Domain": "example.com"} |
| 926 |
) |
| 927 |
# parse_cookie() has historically kept only the last cookie with the |
| 928 |
# same name. |
| 929 |
self.assertEqual(parse_cookie("a=b; h=i; a=c"), {"a": "c", "h": "i"}) |
| 930 |
|
| 931 |
def test_invalid_cookies(self): |
| 932 |
""" |
| 933 |
Cookie strings that go against RFC 6265 but browsers will send if set |
| 934 |
via document.cookie. |
| 935 |
""" |
| 936 |
# Chunks without an equals sign appear as unnamed values per |
| 937 |
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091 |
| 938 |
self.assertIn( |
| 939 |
"django_language", parse_cookie("abc=def; unnamed; django_language=en") |
| 940 |
) |
| 941 |
# Even a double quote may be an unnamed value. |
| 942 |
self.assertEqual(parse_cookie('a=b; "; c=d'), {"a": "b", "": '"', "c": "d"}) |
| 943 |
# Spaces in names and values, and an equals sign in values. |
| 944 |
self.assertEqual( |
| 945 |
parse_cookie("a b c=d e = f; gh=i"), {"a b c": "d e = f", "gh": "i"} |
| 946 |
) |
| 947 |
# More characters the spec forbids. |
| 948 |
self.assertEqual( |
| 949 |
parse_cookie('a b,c<>@:/[]?{}=d " =e,f g'), |
| 950 |
{"a b,c<>@:/[]?{}": 'd " =e,f g'}, |
| 951 |
) |
| 952 |
# Unicode characters. The spec only allows ASCII. |
| 953 |
self.assertEqual( |
| 954 |
parse_cookie("saint=André Bessette"), {"saint": "André Bessette"} |
| 955 |
) |
| 956 |
# Browsers don't send extra whitespace or semicolons in Cookie headers, |
| 957 |
# but parse_cookie() should parse whitespace the same way |
| 958 |
# document.cookie parses whitespace. |
| 959 |
self.assertEqual( |
| 960 |
parse_cookie(" = b ; ; = ; c = ; "), {"": "b", "c": ""} |
| 961 |
) |
| 962 |
|
| 963 |
def test_samesite(self): |
| 964 |
c = SimpleCookie("name=value; samesite=lax; httponly") |
| 965 |
self.assertEqual(c["name"]["samesite"], "lax") |
| 966 |
self.assertIn("SameSite=lax", c.output()) |
| 967 |
|
| 968 |
def test_httponly_after_load(self): |
| 969 |
c = SimpleCookie() |
| 970 |
c.load("name=val") |
| 971 |
c["name"]["httponly"] = True |
| 972 |
self.assertTrue(c["name"]["httponly"]) |
| 973 |
|
| 974 |
def test_load_dict(self): |
| 975 |
c = SimpleCookie() |
| 976 |
c.load({"name": "val"}) |
| 977 |
self.assertEqual(c["name"].value, "val") |
| 978 |
|
| 979 |
def test_pickle(self): |
| 980 |
rawdata = 'Customer="WILE_E_COYOTE"; Path=/acme; Version=1' |
| 981 |
expected_output = "Set-Cookie: %s" % rawdata |
| 982 |
|
| 983 |
C = SimpleCookie() |
| 984 |
C.load(rawdata) |
| 985 |
self.assertEqual(C.output(), expected_output) |
| 986 |
|
| 987 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 988 |
C1 = pickle.loads(pickle.dumps(C, protocol=proto)) |
| 989 |
self.assertEqual(C1.output(), expected_output) |
| 990 |
|
| 991 |
|
| 992 |
class HttpResponseHeadersTestCase(SimpleTestCase): |
| 993 |
"""Headers by treating HttpResponse like a dictionary.""" |
| 994 |
|
| 995 |
def test_headers(self): |
| 996 |
response = HttpResponse() |
| 997 |
response["X-Foo"] = "bar" |
| 998 |
self.assertEqual(response["X-Foo"], "bar") |
| 999 |
self.assertEqual(response.headers["X-Foo"], "bar") |
| 1000 |
self.assertIn("X-Foo", response) |
| 1001 |
self.assertIs(response.has_header("X-Foo"), True) |
| 1002 |
del response["X-Foo"] |
| 1003 |
self.assertNotIn("X-Foo", response) |
| 1004 |
self.assertNotIn("X-Foo", response.headers) |
| 1005 |
# del doesn't raise a KeyError on nonexistent headers. |
| 1006 |
del response["X-Foo"] |
| 1007 |
|
| 1008 |
def test_headers_as_iterable_of_tuple_pairs(self): |
| 1009 |
response = HttpResponse(headers=(("X-Foo", "bar"),)) |
| 1010 |
self.assertEqual(response["X-Foo"], "bar") |
| 1011 |
|
| 1012 |
def test_headers_bytestring(self): |
| 1013 |
response = HttpResponse() |
| 1014 |
response["X-Foo"] = b"bar" |
| 1015 |
self.assertEqual(response["X-Foo"], "bar") |
| 1016 |
self.assertEqual(response.headers["X-Foo"], "bar") |
| 1017 |
|
| 1018 |
def test_newlines_in_headers(self): |
| 1019 |
response = HttpResponse() |
| 1020 |
with self.assertRaises(BadHeaderError): |
| 1021 |
response["test\rstr"] = "test" |
| 1022 |
with self.assertRaises(BadHeaderError): |
| 1023 |
response["test\nstr"] = "test" |