test_multipart.py
This file
Path
tests/test_multipart.py
305 lines · 11.0 KiB · Python
Last changed by
enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2
History of this fileTake it
The walk stopped after 200 commits: lines older than 891d865 point at it.
Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 1–9why, one step back1import cgi2import io3import os4import typing5from unittest import mock67import pytest89import httpxRefactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 10why, one step back10from httpx._content import encode_requestCorrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 11–13why, one step back11from httpx._utils import format_form_param1213Refactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d
lines 14–15why, one step back14def echo_request_content(request: httpx.Request) -> httpx.Response:15 return httpx.Response(200, content=request.content)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 16–18why, one step back161718@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 19why, one step back19def test_multipart(value, output):Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 20why, one step back20 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 21why, one step back21Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 22–26why, one step back22 # 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 == 200Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 27why, one step back27Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 28–36why, one step back28 # 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)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 37why, one step back37Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 38–41why, one step back38 # 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>"]Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 42why, one step back42Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 43why, one step back43Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 44why, one step back44@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 45why, one step back45def test_multipart_invalid_key(key):Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 46why, one step back46 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 47why, one step back47Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 48–56why, one step back48 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 back57 assert repr(key) in str(e.value)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 58why, one step back58Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 59why, one step back59Handle `data={"key": [None|int|float|bool]}` cases. (#1539)Tom Christiebefore adoptionc26425a
line 60why, one step back60@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 61why, one step back61def test_multipart_invalid_value(value):Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 62why, one step back62 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 63why, one step back63Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 64–68why, one step back64 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)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 69–70why, one step back6970Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 71why, one step back71def test_multipart_file_tuple():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 72why, one step back72 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 73why, one step back73Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 74–94why, one step back74 # 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>"]Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 95–106why, one step back959697def test_multipart_encode(tmp_path: typing.Any) -> None:98 path = str(tmp_path / "name.txt")99 with open(path, "wb") as f:100 f.write(b"<file content>")101102 data = {103 "a": "1",104 "b": b"C",105 "c": ["11", "22", "33"],106 "d": "",Handle `data={"key": [None|int|float|bool]}` cases. (#1539)Tom Christiebefore adoptionc26425a
lines 107–108why, one step back107 "e": True,108 "f": "",Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 109why, one step back109 }Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72
lines 110–111why, one step back110 with open(path, "rb") as input_file:111 files = {"file": ("name.txt", input_file)}Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 112why, one step back112Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72
lines 113–114why, one step back113 with mock.patch("os.urandom", return_value=os.urandom(16)):114 boundary = os.urandom(16).hex()Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 115why, one step back115Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72
lines 116–117why, one step back116 headers, stream = encode_request(data=data, files=files)117 assert isinstance(stream, typing.Iterable)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 118why, one step back118Treat warnings as errors (#1687)Tom Christiebefore adoptionb43af72
lines 119–138why, one step back119 content = (120 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'121 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'122 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'123 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'124 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'125 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'126 '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'128 '--{0}\r\nContent-Disposition: form-data; name="file";'129 ' filename="name.txt"\r\n'130 "Content-Type: text/plain\r\n\r\n<file content>\r\n"131 "--{0}--\r\n"132 "".format(boundary).encode("ascii")133 )134 assert headers == {135 "Content-Type": f"multipart/form-data; boundary={boundary}",136 "Content-Length": str(len(content)),137 }138 assert content == b"".join(stream)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 139–140why, one step back139140Fix Content-Length for unicode file contents with multipart (#1537)Tom Christiebefore adoptionc75ddc2
line 141why, one step back141def test_multipart_encode_unicode_file_contents() -> None:enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2
line 142why, one step back142 files = {"file": ("name.txt", b"<bytes content>")}Fix Content-Length for unicode file contents with multipart (#1537)Tom Christiebefore adoptionc75ddc2
lines 143–152why, one step back143144 with mock.patch("os.urandom", return_value=os.urandom(16)):145 boundary = os.urandom(16).hex()146147 headers, stream = encode_request(files=files)148 assert isinstance(stream, typing.Iterable)149150 content = (151 '--{0}\r\nContent-Disposition: form-data; name="file";'152 ' filename="name.txt"\r\n'enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2
line 153why, one step back153 "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 154–163why, one step back154 "--{0}--\r\n"155 "".format(boundary).encode("utf-8")156 )157 assert headers == {158 "Content-Type": f"multipart/form-data; boundary={boundary}",159 "Content-Length": str(len(content)),160 }161 assert content == b"".join(stream)162163Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 164–168why, one step back164def test_multipart_encode_files_allows_filenames_as_none() -> None:165 files = {"file": (None, io.BytesIO(b"<file content>"))}166 with mock.patch("os.urandom", return_value=os.urandom(16)):167 boundary = os.urandom(16).hex()168Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 169why, one step back169 headers, stream = encode_request(data={}, files=files)Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 170why, one step back170 assert isinstance(stream, typing.Iterable)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 171why, one step back171Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 172why, one step back172 content = (Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 173–176why, one step back173 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'174 "<file content>\r\n--{0}--\r\n"175 "".format(boundary).encode("ascii")176 )Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
lines 177–181why, one step back177 assert headers == {178 "Content-Type": f"multipart/form-data; boundary={boundary}",179 "Content-Length": str(len(content)),180 }181 assert content == b"".join(stream)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 182–198why, one step back182183184@pytest.mark.parametrize(185 "file_name,expected_content_type",186 [187 ("example.json", "application/json"),188 ("example.txt", "text/plain"),189 ("no-extension", "application/octet-stream"),190 ],191)192def test_multipart_encode_files_guesses_correct_content_type(193 file_name: str, expected_content_type: str194) -> None:195 files = {"file": (file_name, io.BytesIO(b"<file content>"))}196 with mock.patch("os.urandom", return_value=os.urandom(16)):197 boundary = os.urandom(16).hex()198Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 199why, one step back199 headers, stream = encode_request(data={}, files=files)Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 200why, one step back200 assert isinstance(stream, typing.Iterable)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 201why, one step back201Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 202why, one step back202 content = (Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 203–207why, one step back203 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '204 f'filename="{file_name}"\r\nContent-Type: '205 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"206 "".encode("ascii")207 )Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
lines 208–212why, one step back208 assert headers == {209 "Content-Type": f"multipart/form-data; boundary={boundary}",210 "Content-Length": str(len(content)),211 }212 assert content == b"".join(stream)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 213–214why, one step back213214enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2
lines 215–216why, one step back215def test_multipart_encode_files_allows_bytes_content() -> None:216 files = {"file": ("test.txt", b"<bytes content>", "text/plain")}Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 217–219why, one step back217 with mock.patch("os.urandom", return_value=os.urandom(16)):218 boundary = os.urandom(16).hex()219Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 220why, one step back220 headers, stream = encode_request(data={}, files=files)Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 221why, one step back221 assert isinstance(stream, typing.Iterable)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 222–225why, one step back222223 content = (224 '--{0}\r\nContent-Disposition: form-data; name="file"; '225 'filename="test.txt"\r\n'enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2
line 226why, one step back226 "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 227why, one step back227 "--{0}--\r\n"enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2
line 228why, one step back228 "".format(boundary).encode("ascii")Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
line 229why, one step back229 )Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
lines 230–234why, one step back230 assert headers == {231 "Content-Type": f"multipart/form-data; boundary={boundary}",232 "Content-Length": str(len(content)),233 }234 assert content == b"".join(stream)enforce-upload-files-binary-type (#1736)Amin Alaeebefore adoption20e66d2
lines 235–250why, one step back235236237def test_multipart_encode_files_raises_exception_with_str_content() -> None:238 files = {"file": ("test.txt", "<bytes content>", "text/plain")}239 with mock.patch("os.urandom", return_value=os.urandom(16)):240241 with pytest.raises(TypeError):242 encode_request(data={}, files=files) # type: ignore243244245def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:246 files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}247 with mock.patch("os.urandom", return_value=os.urandom(16)):248249 with pytest.raises(TypeError):250 encode_request(data={}, files=files) # type: ignoreCorrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 251–271why, one step back251252253def test_multipart_encode_non_seekable_filelike() -> None:254 """255 Test that special readable but non-seekable filelike objects are supported,256 at the cost of reading them into memory at most once.257 """258259 class IteratorIO(io.IOBase):260 def __init__(self, iterator: typing.Iterator[bytes]) -> None:261 self._iterator = iterator262263 def read(self, *args: typing.Any) -> bytes:264 return b"".join(self._iterator)265266 def data() -> typing.Iterator[bytes]:267 yield b"Hello"268 yield b"World"269270 fileobj: typing.Any = IteratorIO(data())271 files = {"file": fileobj}Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
lines 272–273why, one step back272 headers, stream = encode_request(files=files, boundary=b"+++")273 assert isinstance(stream, typing.Iterable)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 274–282why, one step back274275 content = (276 b"--+++\r\n"277 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'278 b"Content-Type: application/octet-stream\r\n"279 b"\r\n"280 b"HelloWorld\r\n"281 b"--+++--\r\n"282 )Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 283why, one step back283 assert headers == {Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 284–286why, one step back284 "Content-Type": "multipart/form-data; boundary=+++",285 "Content-Length": str(len(content)),286 }Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 287why, one step back287 assert content == b"".join(stream)Corrected docstring on async def request() (#1181)Simon Willisonbefore adoption891d865
lines 288–305why, one step back288289290class TestHeaderParamHTML5Formatting:291 def test_unicode(self):292 param = format_form_param("filename", "n\u00e4me")293 assert param == b'filename="n\xc3\xa4me"'294295 def test_ascii(self):296 param = format_form_param("filename", b"name")297 assert param == b'filename="name"'298299 def test_unicode_escape(self):300 param = format_form_param("filename", "hello\\world\u0022")301 assert param == b'filename="hello\\\\world%22"'302303 def test_unicode_with_control_character(self):304 param = format_form_param("filename", "hello\x1A\x1B\x1C")305 assert param == b'filename="hello%1A\x1B%1C"'