test_multipart.py
This file
Path
tests/test_multipart.py
259 lines · 9.5 KiB · Python
Last changed by
Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
History of this fileTake it
The walk stopped after 200 commits: lines older than 07586f9 point at it.
Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 1–4why, one step back1import binascii2import cgi3import io4import osHttpcore interface (#804)Tom Christiebefore adoption3046e92
line 5why, one step back5import typingConvert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 6–7why, one step back6from unittest import mock7Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 8why, one step back8import httpcoreConvert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 9–10why, one step back9import pytest10Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
line 11why, one step back11import httpxHttpcore interface (#804)Tom Christiebefore adoption3046e92
line 12why, one step back12from httpx._content_streams import AsyncIteratorStream, encodeSwitch to private module names (#785)Florimond Mancabefore adoption82dc6f3
line 13why, one step back13from httpx._utils import format_form_paramConvert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 14–15why, one step back1415Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 16–17why, one step back16class MockDispatch(httpcore.AsyncHTTPTransport):17 async def request(Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 18why, one step back18 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 19–32why, one step back19 method: bytes,20 url: typing.Tuple[bytes, bytes, int, bytes],21 headers: typing.List[typing.Tuple[bytes, bytes]] = None,22 stream: httpcore.AsyncByteStream = None,23 timeout: typing.Dict[str, typing.Optional[float]] = None,24 ) -> typing.Tuple[25 bytes,26 int,27 bytes,28 typing.List[typing.Tuple[bytes, bytes]],29 httpcore.AsyncByteStream,30 ]:31 content = AsyncIteratorStream(aiterator=(part async for part in stream))32 return b"HTTP/1.1", 200, b"OK", [], contentConvert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 33–35why, one step back333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))Drop sync (#544)Tom Christiebefore adoption206c537
lines 36–37why, one step back36@pytest.mark.asyncio37async def test_multipart(value, output):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 38why, one step back38 client = httpx.AsyncClient(dispatch=MockDispatch())Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 39–42why, one step back3940 # Test with a single-value 'data' argument, and a plain file 'files' argument.41 data = {"text": value}42 files = {"file": io.BytesIO(b"<file content>")}Drop sync (#544)Tom Christiebefore adoption206c537
line 43why, one step back43 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 44–59why, one step back44 assert response.status_code == 2004546 # We're using the cgi module to verify the behavior here, which is a47 # bit grungy, but sufficient just for our testing purposes.48 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]49 content_length = response.request.headers["Content-Length"]50 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}51 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5253 # Note that the expected return type for text fields54 # appears to differs from 3.6 to 3.7+55 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]56 assert multipart["file"] == [b"<file content>"]575859@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))Drop sync (#544)Tom Christiebefore adoption206c537
lines 60–61why, one step back60@pytest.mark.asyncio61async def test_multipart_invalid_key(key):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 62why, one step back62 client = httpx.AsyncClient(dispatch=MockDispatch())Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 63–65why, one step back63 data = {key: "abc"}64 files = {"file": io.BytesIO(b"<file content>")}65 with pytest.raises(TypeError) as e:Drop sync (#544)Tom Christiebefore adoption206c537
line 66why, one step back66 await client.post("http://127.0.0.1:8000/", data=data, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 67–70why, one step back67 assert "Invalid type for name" in str(e.value)686970@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))Drop sync (#544)Tom Christiebefore adoption206c537
lines 71–72why, one step back71@pytest.mark.asyncio72async def test_multipart_invalid_value(value):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 73why, one step back73 client = httpx.AsyncClient(dispatch=MockDispatch())Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 74–76why, one step back74 data = {"text": value}75 files = {"file": io.BytesIO(b"<file content>")}76 with pytest.raises(TypeError) as e:Drop sync (#544)Tom Christiebefore adoption206c537
line 77why, one step back77 await client.post("http://127.0.0.1:8000/", data=data, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 78–80why, one step back78 assert "Invalid type for value" in str(e.value)7980Drop sync (#544)Tom Christiebefore adoption206c537
lines 81–82why, one step back81@pytest.mark.asyncio82async def test_multipart_file_tuple():Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 83why, one step back83 client = httpx.AsyncClient(dispatch=MockDispatch())Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 84–87why, one step back8485 # Test with a list of values 'data' argument, and a tuple style 'files' argument.86 data = {"text": ["abc"]}87 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}Drop sync (#544)Tom Christiebefore adoption206c537
line 88why, one step back88 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 89–103why, one step back89 assert response.status_code == 2009091 # We're using the cgi module to verify the behavior here, which is a92 # bit grungy, but sufficient just for our testing purposes.93 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]94 content_length = response.request.headers["Content-Length"]95 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}96 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9798 # Note that the expected return type for text fields99 # appears to differs from 3.6 to 3.7+100 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]101 assert multipart["file"] == [b"<file content>"]102103Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 104–108why, one step back104def test_multipart_encode(tmp_path: typing.Any) -> None:105 path = str(tmp_path / "name.txt")106 with open(path, "wb") as f:107 f.write(b"<file content>")108Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 109–112why, one step back109 data = {110 "a": "1",111 "b": b"C",112 "c": ["11", "22", "33"],Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 113why, one step back113 "d": "",Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 114why, one step back114 }Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 115why, one step back115 files = {"file": ("name.txt", open(path, "rb"))}Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 116–118why, one step back116117 with mock.patch("os.urandom", return_value=os.urandom(16)):118 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 119why, one step back119Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 120why, one step back120 stream = encode(data=data, files=files)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 121–122why, one step back121 assert stream.can_replay()122Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 123why, one step back123 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 124why, one step back124 content = (Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 125–129why, one step back125 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'126 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'128 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'129 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 130why, one step back130 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 131–136why, one step back131 '--{0}\r\nContent-Disposition: form-data; name="file";'132 ' filename="name.txt"\r\n'133 "Content-Type: text/plain\r\n\r\n<file content>\r\n"134 "--{0}--\r\n"135 "".format(boundary).encode("ascii")136 )Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 137–138why, one step back137 assert stream.get_headers()["Content-Length"] == str(len(content))138 assert b"".join(stream) == contentConvert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 139–140why, one step back139140Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 141why, one step back141def test_multipart_encode_files_allows_filenames_as_none() -> None:Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 142–145why, one step back142 files = {"file": (None, io.BytesIO(b"<file content>"))}143 with mock.patch("os.urandom", return_value=os.urandom(16)):144 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")145Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 146why, one step back146 stream = encode(data={}, files=files)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 147why, one step back147 assert stream.can_replay()Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 148why, one step back148Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 149why, one step back149 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 150why, one step back150 assert b"".join(stream) == (Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 151–152why, one step back151 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'152 "<file content>\r\n--{0}--\r\n"Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 153why, one step back153 "".format(boundary).encode("ascii")Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 154–158why, one step back154 )155156157@pytest.mark.parametrize(158 "file_name,expected_content_type",Minor test fixes (#583)Tom Christiebefore adoption12d00b2
lines 159–163why, one step back159 [160 ("example.json", "application/json"),161 ("example.txt", "text/plain"),162 ("no-extension", "application/octet-stream"),163 ],Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 164–165why, one step back164)165def test_multipart_encode_files_guesses_correct_content_type(Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 166–167why, one step back166 file_name: str, expected_content_type: str167) -> None:Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 168–171why, one step back168 files = {"file": (file_name, io.BytesIO(b"<file content>"))}169 with mock.patch("os.urandom", return_value=os.urandom(16)):170 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")171Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 172why, one step back172 stream = encode(data={}, files=files)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 173why, one step back173 assert stream.can_replay()Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
line 174why, one step back174Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 175why, one step back175 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 176why, one step back176 assert b"".join(stream) == (Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 177–180why, one step back177 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '178 f'filename="{file_name}"\r\nContent-Type: '179 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"180 "".encode("ascii")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 181–183why, one step back181 )182183Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 184why, one step back184def test_multipart_encode_files_allows_str_content() -> None:Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 185–188why, one step back185 files = {"file": ("test.txt", "<string content>", "text/plain")}186 with mock.patch("os.urandom", return_value=os.urandom(16)):187 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")188Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 189why, one step back189 stream = encode(data={}, files=files)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 190why, one step back190 assert stream.can_replay()Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 191why, one step back191Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 192why, one step back192 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 193why, one step back193 content = (Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 194–199why, one step back194 '--{0}\r\nContent-Disposition: form-data; name="file"; '195 'filename="test.txt"\r\n'196 "Content-Type: text/plain\r\n\r\n<string content>\r\n"197 "--{0}--\r\n"198 "".format(boundary).encode("ascii")199 )Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 200–241why, one step back200 assert stream.get_headers()["Content-Length"] == str(len(content))201 assert b"".join(stream) == content202203204def test_multipart_encode_non_seekable_filelike() -> None:205 """206 Test that special readable but non-seekable filelike objects are supported,207 at the cost of reading them into memory at most once.208 """209210 class IteratorIO(io.IOBase):211 def __init__(self, iterator: typing.Iterator[bytes]) -> None:212 self._iterator = iterator213214 def seekable(self) -> bool:215 return False216217 def read(self, *args: typing.Any) -> bytes:218 return b"".join(self._iterator)219220 def data() -> typing.Iterator[bytes]:221 yield b"Hello"222 yield b"World"223224 fileobj = IteratorIO(data())225 files = {"file": fileobj}226 stream = encode(files=files, boundary=b"+++")227 assert not stream.can_replay()228229 content = (230 b"--+++\r\n"231 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'232 b"Content-Type: application/octet-stream\r\n"233 b"\r\n"234 b"HelloWorld\r\n"235 b"--+++--\r\n"236 )237 assert stream.get_headers() == {238 "Content-Type": "multipart/form-data; boundary=+++",239 "Content-Length": str(len(content)),240 }241 assert b"".join(stream) == contentConvert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 242–245why, one step back242243244class TestHeaderParamHTML5Formatting:245 def test_unicode(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 246why, one step back246 param = format_form_param("filename", "n\u00e4me")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 247–249why, one step back247 assert param == b'filename="n\xc3\xa4me"'248249 def test_ascii(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 250why, one step back250 param = format_form_param("filename", b"name")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 251–253why, one step back251 assert param == b'filename="name"'252253 def test_unicode_escape(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 254why, one step back254 param = format_form_param("filename", "hello\\world\u0022")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 255–257why, one step back255 assert param == b'filename="hello\\\\world%22"'256257 def test_unicode_with_control_character(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 258why, one step back258 param = format_form_param("filename", "hello\x1A\x1B\x1C")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 259why, one step back259 assert param == b'filename="hello%1A\x1B%1C"'