Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

275 lines · 9.9 KiB · Python

Last changed by

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

History of this file

Take it

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

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 4why, one step back
4import typing

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 7why, one step back
7import httpcore

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 8–10why, one step back
8import pytest
910import httpx

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

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

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

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 13–14why, one step back
13
14

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 15why, one step back
15class MockTransport(httpcore.AsyncHTTPTransport):

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 16why, one step back
16 async def request(

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

line 17why, one step back
17 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 18why, one step back
18 method: bytes,

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 19why, one step back
19 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 20–21why, one step back
20 headers: typing.List[typing.Tuple[bytes, bytes]] = None,
21 stream: httpcore.AsyncByteStream = None,

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 22why, one step back
22 timeout: typing.Mapping[str, typing.Optional[float]] = None,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 23–29why, one step back
23 ) -> typing.Tuple[
24 bytes,25 int,26 bytes,27 typing.List[typing.Tuple[bytes, bytes]],28 httpcore.AsyncByteStream,29 ]:

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 30why, one step back
30 assert stream is not None

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 31–32why, one step back
31 content = AsyncIteratorStream(aiterator=(part async for part in stream))
32 return b"HTTP/1.1", 200, b"OK", [], content

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 33–37why, one step back
33
3435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio37async def test_multipart(value, output):

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 38why, one step back
38 client = httpx.AsyncClient(transport=MockTransport())

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 39–49why, 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>")}43 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)44 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"]

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 50–53why, one step back
50 pdict: dict = {
51 "boundary": boundary.encode("ascii"),52 "CONTENT-LENGTH": content_length,53 }

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 54–64why, one step back
54 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)
5556 # Note that the expected return type for text fields57 # appears to differs from 3.6 to 3.7+58 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]59 assert multipart["file"] == [b"<file content>"]606162@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))63@pytest.mark.asyncio64async def test_multipart_invalid_key(key):

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 65why, one step back
65 client = httpx.AsyncClient(transport=MockTransport())

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 66–75why, one step back
66 data = {key: "abc"}
67 files = {"file": io.BytesIO(b"<file content>")}68 with pytest.raises(TypeError) as e:69 await client.post("http://127.0.0.1:8000/", data=data, files=files)70 assert "Invalid type for name" in str(e.value)717273@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))74@pytest.mark.asyncio75async def test_multipart_invalid_value(value):

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 76why, one step back
76 client = httpx.AsyncClient(transport=MockTransport())

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 77–85why, one step back
77 data = {"text": value}
78 files = {"file": io.BytesIO(b"<file content>")}79 with pytest.raises(TypeError) as e:80 await client.post("http://127.0.0.1:8000/", data=data, files=files)81 assert "Invalid type for value" in str(e.value)828384@pytest.mark.asyncio85async def test_multipart_file_tuple():

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

line 86why, one step back
86 client = httpx.AsyncClient(transport=MockTransport())

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 87–97why, one step back
87
88 # Test with a list of values 'data' argument, and a tuple style 'files' argument.89 data = {"text": ["abc"]}90 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}91 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)92 assert response.status_code == 2009394 # We're using the cgi module to verify the behavior here, which is a95 # bit grungy, but sufficient just for our testing purposes.96 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]97 content_length = response.request.headers["Content-Length"]

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

lines 98–101why, one step back
98 pdict: dict = {
99 "boundary": boundary.encode("ascii"),100 "CONTENT-LENGTH": content_length,101 }

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 102–109why, one step back
102 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)
103104 # Note that the expected return type for text fields105 # appears to differs from 3.6 to 3.7+106 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]107 assert multipart["file"] == [b"<file content>"]108109

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 110–114why, one step back
110def test_multipart_encode(tmp_path: typing.Any) -> None:
111 path = str(tmp_path / "name.txt")112 with open(path, "wb") as f:113 f.write(b"<file content>")114

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 115–118why, one step back
115 data = {
116 "a": "1",117 "b": b"C",118 "c": ["11", "22", "33"],

Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152

line 119why, one step back
119 "d": "",

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

line 120why, one step back
120 }

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 122–123why, one step back
122
123 with mock.patch("os.urandom", return_value=os.urandom(16)):

Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc

line 124why, one step back
124 boundary = os.urandom(16).hex()

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 125why, one step back
125

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 127why, one step back
127 assert isinstance(stream, MultipartStream)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 128–129why, one step back
128 assert stream.can_replay()
129

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 131why, one step back
131 content = (

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 132–136why, one step back
132 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'
133 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'134 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'135 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'136 '--{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 137why, one step back
137 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 138–143why, one step back
138 '--{0}\r\nContent-Disposition: form-data; name="file";'
139 ' filename="name.txt"\r\n'140 "Content-Type: text/plain\r\n\r\n<file content>\r\n"141 "--{0}--\r\n"142 "".format(boundary).encode("ascii")143 )

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 144–145why, one step back
144 assert stream.get_headers()["Content-Length"] == str(len(content))
145 assert b"".join(stream) == content

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 146–147why, one step back
146
147

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 149–150why, one step back
149 files = {"file": (None, io.BytesIO(b"<file content>"))}
150 with mock.patch("os.urandom", return_value=os.urandom(16)):

Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc

line 151why, one step back
151 boundary = os.urandom(16).hex()

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 152–153why, one step back
152
153 stream = encode(data={}, files=files)

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 154why, one step back
154 assert isinstance(stream, MultipartStream)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 156–157why, one step back
156
157 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 158why, one step back
158 assert b"".join(stream) == (

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 159–173why, one step back
159 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'
160 "<file content>\r\n--{0}--\r\n"161 "".format(boundary).encode("ascii")162 )163164165@pytest.mark.parametrize(166 "file_name,expected_content_type",167 [168 ("example.json", "application/json"),169 ("example.txt", "text/plain"),170 ("no-extension", "application/octet-stream"),171 ],172)173def test_multipart_encode_files_guesses_correct_content_type(

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 174–175why, one step back
174 file_name: str, expected_content_type: str
175) -> None:

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 176–177why, one step back
176 files = {"file": (file_name, io.BytesIO(b"<file content>"))}
177 with mock.patch("os.urandom", return_value=os.urandom(16)):

Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc

line 178why, one step back
178 boundary = os.urandom(16).hex()

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 179–180why, one step back
179
180 stream = encode(data={}, files=files)

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 181why, one step back
181 assert isinstance(stream, MultipartStream)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 183–184why, one step back
183
184 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 185why, one step back
185 assert b"".join(stream) == (

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 186–192why, one step back
186 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '
187 f'filename="{file_name}"\r\nContent-Type: '188 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"189 "".encode("ascii")190 )191192

Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2

lines 193–200why, one step back
193@pytest.mark.parametrize(
194 "value, output",195 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),196)197def test_multipart_encode_files_allows_bytes_or_str_content(198 value: typing.Union[str, bytes], output: str199) -> None:200 files = {"file": ("test.txt", value, "text/plain")}

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

line 201why, one step back
201 with mock.patch("os.urandom", return_value=os.urandom(16)):

Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc

line 202why, one step back
202 boundary = os.urandom(16).hex()

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 203–204why, one step back
203
204 stream = encode(data={}, files=files)

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 205why, one step back
205 assert isinstance(stream, MultipartStream)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 207–208why, one step back
207
208 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 209why, one step back
209 content = (

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 210–211why, one step back
210 '--{0}\r\nContent-Disposition: form-data; name="file"; '
211 'filename="test.txt"\r\n'

Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2

line 212why, one step back
212 "Content-Type: text/plain\r\n\r\n{1}\r\n"

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

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

Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2

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

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

line 215why, one step back
215 )

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 216–239why, one step back
216 assert stream.get_headers()["Content-Length"] == str(len(content))
217 assert b"".join(stream) == content218219220def test_multipart_encode_non_seekable_filelike() -> None:221 """222 Test that special readable but non-seekable filelike objects are supported,223 at the cost of reading them into memory at most once.224 """225226 class IteratorIO(io.IOBase):227 def __init__(self, iterator: typing.Iterator[bytes]) -> None:228 self._iterator = iterator229230 def seekable(self) -> bool:231 return False232233 def read(self, *args: typing.Any) -> bytes:234 return b"".join(self._iterator)235236 def data() -> typing.Iterator[bytes]:237 yield b"Hello"238 yield b"World"239

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 240why, one step back
240 fileobj: typing.Any = IteratorIO(data())

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 241–257why, one step back
241 files = {"file": fileobj}
242 stream = encode(files=files, boundary=b"+++")243 assert not stream.can_replay()244245 content = (246 b"--+++\r\n"247 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'248 b"Content-Type: application/octet-stream\r\n"249 b"\r\n"250 b"HelloWorld\r\n"251 b"--+++--\r\n"252 )253 assert stream.get_headers() == {254 "Content-Type": "multipart/form-data; boundary=+++",255 "Content-Length": str(len(content)),256 }257 assert b"".join(stream) == content

Load SSL Context on init (#709)Tom Christiebefore adoption79a9748

lines 258–275why, one step back
258
259260class TestHeaderParamHTML5Formatting:261 def test_unicode(self):262 param = format_form_param("filename", "n\u00e4me")263 assert param == b'filename="n\xc3\xa4me"'264265 def test_ascii(self):266 param = format_form_param("filename", b"name")267 assert param == b'filename="name"'268269 def test_unicode_escape(self):270 param = format_form_param("filename", "hello\\world\u0022")271 assert param == b'filename="hello\\\\world%22"'272273 def test_unicode_with_control_character(self):274 param = format_form_param("filename", "hello\x1A\x1B\x1C")275 assert param == b'filename="hello%1A\x1B%1C"'