Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

377 lines · 13.8 KiB · Python

Last changed by

Always rewind files on multipart uploads. (#2065)Tom Christiebefore adoption0088253

History of this file

Take it

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

lines 1–3why, one step back
1import cgi
2import io3import os

Always rewind files on multipart uploads. (#2065)Tom Christiebefore adoption0088253

line 4why, one step back
4import tempfile

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

lines 5–20why, one step back
5import typing
6from unittest import mock78import pytest910import httpx11from httpx._content import encode_request12from httpx._utils import format_form_param131415def echo_request_content(request: httpx.Request) -> httpx.Response:16 return httpx.Response(200, content=request.content)171819@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))20def test_multipart(value, output):

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

lines 98–149why, one step back
98@pytest.mark.parametrize("content_type", [None, "text/plain"])
99def test_multipart_file_tuple_headers(content_type: typing.Optional[str]):100 file_name = "test.txt"101 expected_content_type = "text/plain"102 headers = {"Expires": "0"}103104 files = {"file": (file_name, io.BytesIO(b"<file content>"), content_type, headers)}105 with mock.patch("os.urandom", return_value=os.urandom(16)):106 boundary = os.urandom(16).hex()107108 headers, stream = encode_request(data={}, files=files)109 assert isinstance(stream, typing.Iterable)110111 content = (112 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '113 f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '114 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"115 "".encode("ascii")116 )117 assert headers == {118 "Content-Type": f"multipart/form-data; boundary={boundary}",119 "Content-Length": str(len(content)),120 }121 assert content == b"".join(stream)122123124def test_multipart_headers_include_content_type() -> None:125 """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""126 file_name = "test.txt"127 expected_content_type = "image/png"128 headers = {"Content-Type": "image/png"}129130 files = {"file": (file_name, io.BytesIO(b"<file content>"), "text_plain", headers)}131 with mock.patch("os.urandom", return_value=os.urandom(16)):132 boundary = os.urandom(16).hex()133134 headers, stream = encode_request(data={}, files=files)135 assert isinstance(stream, typing.Iterable)136137 content = (138 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '139 f'filename="{file_name}"\r\nContent-Type: '140 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"141 "".encode("ascii")142 )143 assert headers == {144 "Content-Type": f"multipart/form-data; boundary={boundary}",145 "Content-Length": str(len(content)),146 }147 assert content == b"".join(stream)148149

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

line 162why, one step back
162 }

Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

line 165why, one step back
165

Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

line 168why, one step back
168

Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

line 171why, one step back
171

Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

lines 192–193why, one step back
192
193

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

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

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

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

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

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

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

line 206why, one step back
206 "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 207–216why, one step back
207 "--{0}--\r\n"
208 "".format(boundary).encode("utf-8")209 )210 assert headers == {211 "Content-Type": f"multipart/form-data; boundary={boundary}",212 "Content-Length": str(len(content)),213 }214 assert content == b"".join(stream)215216

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

lines 217–267why, one step back
217def test_multipart_encode_files_allows_filenames_as_none() -> None:
218 files = {"file": (None, io.BytesIO(b"<file content>"))}219 with mock.patch("os.urandom", return_value=os.urandom(16)):220 boundary = os.urandom(16).hex()221222 headers, stream = encode_request(data={}, files=files)223 assert isinstance(stream, typing.Iterable)224225 content = (226 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'227 "<file content>\r\n--{0}--\r\n"228 "".format(boundary).encode("ascii")229 )230 assert headers == {231 "Content-Type": f"multipart/form-data; boundary={boundary}",232 "Content-Length": str(len(content)),233 }234 assert content == b"".join(stream)235236237@pytest.mark.parametrize(238 "file_name,expected_content_type",239 [240 ("example.json", "application/json"),241 ("example.txt", "text/plain"),242 ("no-extension", "application/octet-stream"),243 ],244)245def test_multipart_encode_files_guesses_correct_content_type(246 file_name: str, expected_content_type: str247) -> None:248 files = {"file": (file_name, io.BytesIO(b"<file content>"))}249 with mock.patch("os.urandom", return_value=os.urandom(16)):250 boundary = os.urandom(16).hex()251252 headers, stream = encode_request(data={}, files=files)253 assert isinstance(stream, typing.Iterable)254255 content = (256 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '257 f'filename="{file_name}"\r\nContent-Type: '258 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"259 "".encode("ascii")260 )261 assert headers == {262 "Content-Type": f"multipart/form-data; boundary={boundary}",263 "Content-Length": str(len(content)),264 }265 assert content == b"".join(stream)266267

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

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

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

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

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

lines 288–303why, one step back
288
289290def test_multipart_encode_files_raises_exception_with_str_content() -> None:291 files = {"file": ("test.txt", "<bytes content>", "text/plain")}292 with mock.patch("os.urandom", return_value=os.urandom(16)):293294 with pytest.raises(TypeError):295 encode_request(data={}, files=files) # type: ignore296297298def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:299 files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}300 with mock.patch("os.urandom", return_value=os.urandom(16)):301302 with pytest.raises(TypeError):303 encode_request(data={}, files=files) # type: ignore

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

lines 304–340why, one step back
304
305306def test_multipart_encode_non_seekable_filelike() -> None:307 """308 Test that special readable but non-seekable filelike objects are supported,309 at the cost of reading them into memory at most once.310 """311312 class IteratorIO(io.IOBase):313 def __init__(self, iterator: typing.Iterator[bytes]) -> None:314 self._iterator = iterator315316 def read(self, *args: typing.Any) -> bytes:317 return b"".join(self._iterator)318319 def data() -> typing.Iterator[bytes]:320 yield b"Hello"321 yield b"World"322323 fileobj: typing.Any = IteratorIO(data())324 files = {"file": fileobj}325 headers, stream = encode_request(files=files, boundary=b"+++")326 assert isinstance(stream, typing.Iterable)327328 content = (329 b"--+++\r\n"330 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'331 b"Content-Type: application/octet-stream\r\n"332 b"\r\n"333 b"HelloWorld\r\n"334 b"--+++--\r\n"335 )336 assert headers == {337 "Content-Type": "multipart/form-data; boundary=+++",338 "Content-Length": str(len(content)),339 }340 assert content == b"".join(stream)

Always rewind files on multipart uploads. (#2065)Tom Christiebefore adoption0088253

lines 341–359why, one step back
341
342343def test_multipart_rewinds_files():344 with tempfile.TemporaryFile() as upload:345 upload.write(b"Hello, world!")346347 transport = httpx.MockTransport(echo_request_content)348 client = httpx.Client(transport=transport)349350 files = {"file": upload}351 response = client.post("http://127.0.0.1:8000/", files=files)352 assert response.status_code == 200353 assert b"\r\nHello, world!\r\n" in response.content354355 # POSTing the same file instance a second time should have the same content.356 files = {"file": upload}357 response = client.post("http://127.0.0.1:8000/", files=files)358 assert response.status_code == 200359 assert b"\r\nHello, world!\r\n" in response.content

Add curio docs in Supported async environments (#1437)shan7030before adoptionf4165e9

lines 360–377why, one step back
360
361362class TestHeaderParamHTML5Formatting:363 def test_unicode(self):364 param = format_form_param("filename", "n\u00e4me")365 assert param == b'filename="n\xc3\xa4me"'366367 def test_ascii(self):368 param = format_form_param("filename", b"name")369 assert param == b'filename="name"'370371 def test_unicode_escape(self):372 param = format_form_param("filename", "hello\\world\u0022")373 assert param == b'filename="hello\\\\world%22"'374375 def test_unicode_with_control_character(self):376 param = format_form_param("filename", "hello\x1A\x1B\x1C")377 assert param == b'filename="hello%1A\x1B%1C"'