Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

357 lines · 13.1 KiB · Python

Last changed by

Allow custom headers in multipart/form-data requests (#1936)Adrian Garcia Badaraccobefore adoption0f1ff50

History of this file

Take it

The walk stopped after 200 commits: lines older than ac7704e point at it.

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 1–19why, one step back
1import cgi
2import io3import os4import typing5from unittest import mock67import pytest89import httpx10from httpx._content import encode_request11from httpx._utils import format_form_param121314def echo_request_content(request: httpx.Request) -> httpx.Response:15 return httpx.Response(200, content=request.content)161718@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))19def test_multipart(value, output):

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 20why, one step back
20 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 21–45why, one step back
21
22 # Test with a single-value 'data' argument, and a plain file 'files' argument.23 data = {"text": value}24 files = {"file": io.BytesIO(b"<file content>")}25 response = client.post("http://127.0.0.1:8000/", data=data, files=files)26 assert response.status_code == 2002728 # We're using the cgi module to verify the behavior here, which is a29 # bit grungy, but sufficient just for our testing purposes.30 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]31 content_length = response.request.headers["Content-Length"]32 pdict: dict = {33 "boundary": boundary.encode("ascii"),34 "CONTENT-LENGTH": content_length,35 }36 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)3738 # Note that the expected return type for text fields39 # appears to differs from 3.6 to 3.7+40 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]41 assert multipart["file"] == [b"<file content>"]424344@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))45def test_multipart_invalid_key(key):

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 46why, one step back
46 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 47–56why, one step back
47
48 data = {key: "abc"}49 files = {"file": io.BytesIO(b"<file content>")}50 with pytest.raises(TypeError) as e:51 client.post(52 "http://127.0.0.1:8000/",53 data=data,54 files=files,55 )56 assert "Invalid type for name" in str(e.value)

Include invalid name/value when raising TypeError in DataField (#1368)plotskibefore adoption589c6e0

line 57why, one step back
57 assert repr(key) in str(e.value)

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 58–59why, one step back
58
59

Handle `data={"key": [None|int|float|bool]}` cases. (#1539)Tom Christiebefore adoptionc26425a

line 60why, one step back
60@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

line 61why, one step back
61def test_multipart_invalid_value(value):

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 62why, one step back
62 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 63–71why, one step back
63
64 data = {"text": value}65 files = {"file": io.BytesIO(b"<file content>")}66 with pytest.raises(TypeError) as e:67 client.post("http://127.0.0.1:8000/", data=data, files=files)68 assert "Invalid type for value" in str(e.value)697071def test_multipart_file_tuple():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 72why, one step back
72 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 73–96why, one step back
73
74 # Test with a list of values 'data' argument,75 # and a tuple style 'files' argument.76 data = {"text": ["abc"]}77 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}78 response = client.post("http://127.0.0.1:8000/", data=data, files=files)79 assert response.status_code == 2008081 # We're using the cgi module to verify the behavior here, which is a82 # bit grungy, but sufficient just for our testing purposes.83 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]84 content_length = response.request.headers["Content-Length"]85 pdict: dict = {86 "boundary": boundary.encode("ascii"),87 "CONTENT-LENGTH": content_length,88 }89 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9091 # Note that the expected return type for text fields92 # appears to differs from 3.6 to 3.7+93 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]94 assert multipart["file"] == [b"<file content>"]9596

Allow custom headers in multipart/form-data requests (#1936)Adrian Garcia Badaraccobefore adoption0f1ff50

lines 97–148why, one step back
97@pytest.mark.parametrize("content_type", [None, "text/plain"])
98def test_multipart_file_tuple_headers(content_type: typing.Optional[str]):99 file_name = "test.txt"100 expected_content_type = "text/plain"101 headers = {"Expires": "0"}102103 files = {"file": (file_name, io.BytesIO(b"<file content>"), content_type, headers)}104 with mock.patch("os.urandom", return_value=os.urandom(16)):105 boundary = os.urandom(16).hex()106107 headers, stream = encode_request(data={}, files=files)108 assert isinstance(stream, typing.Iterable)109110 content = (111 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '112 f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '113 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"114 "".encode("ascii")115 )116 assert headers == {117 "Content-Type": f"multipart/form-data; boundary={boundary}",118 "Content-Length": str(len(content)),119 }120 assert content == b"".join(stream)121122123def test_multipart_headers_include_content_type() -> None:124 """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""125 file_name = "test.txt"126 expected_content_type = "image/png"127 headers = {"Content-Type": "image/png"}128129 files = {"file": (file_name, io.BytesIO(b"<file content>"), "text_plain", headers)}130 with mock.patch("os.urandom", return_value=os.urandom(16)):131 boundary = os.urandom(16).hex()132133 headers, stream = encode_request(data={}, files=files)134 assert isinstance(stream, typing.Iterable)135136 content = (137 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '138 f'filename="{file_name}"\r\nContent-Type: '139 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"140 "".encode("ascii")141 )142 assert headers == {143 "Content-Type": f"multipart/form-data; boundary={boundary}",144 "Content-Length": str(len(content)),145 }146 assert content == b"".join(stream)147148

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 149–158why, one step back
149def test_multipart_encode(tmp_path: typing.Any) -> None:
150 path = str(tmp_path / "name.txt")151 with open(path, "wb") as f:152 f.write(b"<file content>")153154 data = {155 "a": "1",156 "b": b"C",157 "c": ["11", "22", "33"],158 "d": "",

Handle `data={"key": [None|int|float|bool]}` cases. (#1539)Tom Christiebefore adoptionc26425a

lines 159–160why, one step back
159 "e": True,
160 "f": "",

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

line 161why, one step back
161 }

Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72

lines 162–163why, one step back
162 with open(path, "rb") as input_file:
163 files = {"file": ("name.txt", input_file)}

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

line 164why, one step back
164

Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72

lines 165–166why, one step back
165 with mock.patch("os.urandom", return_value=os.urandom(16)):
166 boundary = os.urandom(16).hex()

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

line 167why, one step back
167

Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72

lines 168–169why, one step back
168 headers, stream = encode_request(data=data, files=files)
169 assert isinstance(stream, typing.Iterable)

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

line 170why, one step back
170

Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72

lines 171–190why, one step back
171 content = (
172 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'173 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'174 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'175 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'176 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'177 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'178 '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'179 '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'180 '--{0}\r\nContent-Disposition: form-data; name="file";'181 ' filename="name.txt"\r\n'182 "Content-Type: text/plain\r\n\r\n<file content>\r\n"183 "--{0}--\r\n"184 "".format(boundary).encode("ascii")185 )186 assert headers == {187 "Content-Type": f"multipart/form-data; boundary={boundary}",188 "Content-Length": str(len(content)),189 }190 assert content == b"".join(stream)

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 191–192why, one step back
191
192

Fix Content-Length for unicode file contents with multipart (#1537)Tom Christiebefore adoptionc75ddc2

line 193why, one step back
193def test_multipart_encode_unicode_file_contents() -> None:

enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2

line 194why, one step back
194 files = {"file": ("name.txt", b"<bytes content>")}

Fix Content-Length for unicode file contents with multipart (#1537)Tom Christiebefore adoptionc75ddc2

lines 195–204why, one step back
195
196 with mock.patch("os.urandom", return_value=os.urandom(16)):197 boundary = os.urandom(16).hex()198199 headers, stream = encode_request(files=files)200 assert isinstance(stream, typing.Iterable)201202 content = (203 '--{0}\r\nContent-Disposition: form-data; name="file";'204 ' filename="name.txt"\r\n'

enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2

line 205why, one step back
205 "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"

Fix Content-Length for unicode file contents with multipart (#1537)Tom Christiebefore adoptionc75ddc2

lines 206–215why, one step back
206 "--{0}--\r\n"
207 "".format(boundary).encode("utf-8")208 )209 assert headers == {210 "Content-Type": f"multipart/form-data; boundary={boundary}",211 "Content-Length": str(len(content)),212 }213 assert content == b"".join(stream)214215

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 216–266why, one step back
216def test_multipart_encode_files_allows_filenames_as_none() -> None:
217 files = {"file": (None, io.BytesIO(b"<file content>"))}218 with mock.patch("os.urandom", return_value=os.urandom(16)):219 boundary = os.urandom(16).hex()220221 headers, stream = encode_request(data={}, files=files)222 assert isinstance(stream, typing.Iterable)223224 content = (225 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'226 "<file content>\r\n--{0}--\r\n"227 "".format(boundary).encode("ascii")228 )229 assert headers == {230 "Content-Type": f"multipart/form-data; boundary={boundary}",231 "Content-Length": str(len(content)),232 }233 assert content == b"".join(stream)234235236@pytest.mark.parametrize(237 "file_name,expected_content_type",238 [239 ("example.json", "application/json"),240 ("example.txt", "text/plain"),241 ("no-extension", "application/octet-stream"),242 ],243)244def test_multipart_encode_files_guesses_correct_content_type(245 file_name: str, expected_content_type: str246) -> None:247 files = {"file": (file_name, io.BytesIO(b"<file content>"))}248 with mock.patch("os.urandom", return_value=os.urandom(16)):249 boundary = os.urandom(16).hex()250251 headers, stream = encode_request(data={}, files=files)252 assert isinstance(stream, typing.Iterable)253254 content = (255 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '256 f'filename="{file_name}"\r\nContent-Type: '257 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"258 "".encode("ascii")259 )260 assert headers == {261 "Content-Type": f"multipart/form-data; boundary={boundary}",262 "Content-Length": str(len(content)),263 }264 assert content == b"".join(stream)265266

enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2

lines 267–268why, one step back
267def test_multipart_encode_files_allows_bytes_content() -> None:
268 files = {"file": ("test.txt", b"<bytes content>", "text/plain")}

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 269–277why, one step back
269 with mock.patch("os.urandom", return_value=os.urandom(16)):
270 boundary = os.urandom(16).hex()271272 headers, stream = encode_request(data={}, files=files)273 assert isinstance(stream, typing.Iterable)274275 content = (276 '--{0}\r\nContent-Disposition: form-data; name="file"; '277 'filename="test.txt"\r\n'

enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2

line 278why, one step back
278 "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

line 279why, one step back
279 "--{0}--\r\n"

enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2

line 280why, one step back
280 "".format(boundary).encode("ascii")

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 281–286why, one step back
281 )
282 assert headers == {283 "Content-Type": f"multipart/form-data; boundary={boundary}",284 "Content-Length": str(len(content)),285 }286 assert content == b"".join(stream)

enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2

lines 287–302why, one step back
287
288289def test_multipart_encode_files_raises_exception_with_str_content() -> None:290 files = {"file": ("test.txt", "<bytes content>", "text/plain")}291 with mock.patch("os.urandom", return_value=os.urandom(16)):292293 with pytest.raises(TypeError):294 encode_request(data={}, files=files) # type: ignore295296297def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:298 files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}299 with mock.patch("os.urandom", return_value=os.urandom(16)):300301 with pytest.raises(TypeError):302 encode_request(data={}, files=files) # type: ignore

Remove seed-isort-config (#1321)Johannesbefore adoptionac7704e

lines 303–357why, one step back
303
304305def test_multipart_encode_non_seekable_filelike() -> None:306 """307 Test that special readable but non-seekable filelike objects are supported,308 at the cost of reading them into memory at most once.309 """310311 class IteratorIO(io.IOBase):312 def __init__(self, iterator: typing.Iterator[bytes]) -> None:313 self._iterator = iterator314315 def read(self, *args: typing.Any) -> bytes:316 return b"".join(self._iterator)317318 def data() -> typing.Iterator[bytes]:319 yield b"Hello"320 yield b"World"321322 fileobj: typing.Any = IteratorIO(data())323 files = {"file": fileobj}324 headers, stream = encode_request(files=files, boundary=b"+++")325 assert isinstance(stream, typing.Iterable)326327 content = (328 b"--+++\r\n"329 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'330 b"Content-Type: application/octet-stream\r\n"331 b"\r\n"332 b"HelloWorld\r\n"333 b"--+++--\r\n"334 )335 assert headers == {336 "Content-Type": "multipart/form-data; boundary=+++",337 "Content-Length": str(len(content)),338 }339 assert content == b"".join(stream)340341342class TestHeaderParamHTML5Formatting:343 def test_unicode(self):344 param = format_form_param("filename", "n\u00e4me")345 assert param == b'filename="n\xc3\xa4me"'346347 def test_ascii(self):348 param = format_form_param("filename", b"name")349 assert param == b'filename="name"'350351 def test_unicode_escape(self):352 param = format_form_param("filename", "hello\\world\u0022")353 assert param == b'filename="hello\\\\world%22"'354355 def test_unicode_with_control_character(self):356 param = format_form_param("filename", "hello\x1A\x1B\x1C")357 assert param == b'filename="hello%1A\x1B%1C"'