Skip to content
Myr

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 file

Take 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 back
1import binascii
2import cgi3import io4import os

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 5why, one step back
5import typing

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 6–7why, one step back
6from unittest import mock
7

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 8why, one step back
8import httpcore

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 9–10why, one step back
9import pytest
10

Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b

line 11why, one step back
11import httpx

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 12why, one step back
12from httpx._content_streams import AsyncIteratorStream, encode

Switch to private module names (#785)Florimond Mancabefore adoption82dc6f3

line 13why, one step back
13from httpx._utils import format_form_param

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 14–15why, one step back
14
15

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 16–17why, one step back
16class MockDispatch(httpcore.AsyncHTTPTransport):
17 async def request(

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

line 18why, one step back
18 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 19–32why, one step back
19 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", [], content

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 33–35why, one step back
33
3435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))

Drop sync (#544)Tom Christiebefore adoption206c537

lines 36–37why, one step back
36@pytest.mark.asyncio
37async def test_multipart(value, output):

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 38why, one step back
38 client = httpx.AsyncClient(dispatch=MockDispatch())

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 39–42why, one step back
39
40 # 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 back
43 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 back
44 assert response.status_code == 200
4546 # 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 back
60@pytest.mark.asyncio
61async def test_multipart_invalid_key(key):

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 62why, one step back
62 client = httpx.AsyncClient(dispatch=MockDispatch())

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 63–65why, one step back
63 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 back
66 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 back
67 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 back
71@pytest.mark.asyncio
72async def test_multipart_invalid_value(value):

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 73why, one step back
73 client = httpx.AsyncClient(dispatch=MockDispatch())

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 74–76why, one step back
74 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 back
77 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 back
78 assert "Invalid type for value" in str(e.value)
7980

Drop sync (#544)Tom Christiebefore adoption206c537

lines 81–82why, one step back
81@pytest.mark.asyncio
82async def test_multipart_file_tuple():

Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84

line 83why, one step back
83 client = httpx.AsyncClient(dispatch=MockDispatch())

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 84–87why, one step back
84
85 # 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 back
88 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 back
89 assert response.status_code == 200
9091 # 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>"]102103

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 104–108why, one step back
104def 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>")108

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 109–112why, one step back
109 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 back
113 "d": "",

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

line 114why, one step back
114 }

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 115why, one step back
115 files = {"file": ("name.txt", open(path, "rb"))}

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 116–118why, one step back
116
117 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 back
119

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 120why, one step back
120 stream = encode(data=data, files=files)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 121–122why, one step back
121 assert stream.can_replay()
122

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 123why, one step back
123 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 124why, one step back
124 content = (

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 125–129why, one step back
125 '--{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 back
130 '--{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 back
131 '--{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 back
137 assert stream.get_headers()["Content-Length"] == str(len(content))
138 assert b"".join(stream) == content

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 139–140why, one step back
139
140

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 141why, one step back
141def test_multipart_encode_files_allows_filenames_as_none() -> None:

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 142–145why, one step back
142 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")145

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 146why, one step back
146 stream = encode(data={}, files=files)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 147why, one step back
147 assert stream.can_replay()

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

line 148why, one step back
148

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 149why, one step back
149 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 150why, one step back
150 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 back
151 '--{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 back
153 "".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 back
154 )
155156157@pytest.mark.parametrize(158 "file_name,expected_content_type",

Minor test fixes (#583)Tom Christiebefore adoption12d00b2

lines 159–163why, one step back
159 [
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 back
164)
165def test_multipart_encode_files_guesses_correct_content_type(

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 166–167why, one step back
166 file_name: str, expected_content_type: str
167) -> None:

Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950

lines 168–171why, one step back
168 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")171

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 172why, one step back
172 stream = encode(data={}, files=files)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 173why, one step back
173 assert stream.can_replay()

Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950

line 174why, one step back
174

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 175why, one step back
175 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 176why, one step back
176 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 back
177 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 back
181 )
182183

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 184why, one step back
184def test_multipart_encode_files_allows_str_content() -> None:

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 185–188why, one step back
185 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")188

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 189why, one step back
189 stream = encode(data={}, files=files)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 190why, one step back
190 assert stream.can_replay()

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

line 191why, one step back
191

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 192why, one step back
192 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 193why, one step back
193 content = (

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 194–199why, one step back
194 '--{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 back
200 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) == content

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 242–245why, one step back
242
243244class TestHeaderParamHTML5Formatting:245 def test_unicode(self):

Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc

line 246why, one step back
246 param = format_form_param("filename", "n\u00e4me")

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 247–249why, one step back
247 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 back
250 param = format_form_param("filename", b"name")

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 251–253why, one step back
251 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 back
254 param = format_form_param("filename", "hello\\world\u0022")

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

lines 255–257why, one step back
255 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 back
258 param = format_form_param("filename", "hello\x1A\x1B\x1C")

Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9

line 259why, one step back
259 assert param == b'filename="hello%1A\x1B%1C"'