Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

278 lines · 10.2 KiB · Python

Last changed by

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

History of this file

Take it

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 4why, one step back
4import typing

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 7why, one step back
7import httpcore

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 12–14why, one step back
12from httpx._utils import format_form_param
1314

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(

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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):

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 38–43why, one step back
38 async with httpx.AsyncClient(transport=MockTransport()) as client:
39 # Test with a single-value 'data' argument, and a plain file 'files' argument.40 data = {"text": value}41 files = {"file": io.BytesIO(b"<file content>")}42 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)43 assert response.status_code == 200

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 44why, one step back
44

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 45–53why, one step back
45 # We're using the cgi module to verify the behavior here, which is a
46 # bit grungy, but sufficient just for our testing purposes.47 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]48 content_length = response.request.headers["Content-Length"]49 pdict: dict = {50 "boundary": boundary.encode("ascii"),51 "CONTENT-LENGTH": content_length,52 }53 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 54why, one step back
54

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 55–58why, one step back
55 # Note that the expected return type for text fields
56 # appears to differs from 3.6 to 3.7+57 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]58 assert multipart["file"] == [b"<file content>"]

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 59–63why, one step back
59
6061@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))62@pytest.mark.asyncio63async def test_multipart_invalid_key(key):

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 64–73why, one step back
64 async with httpx.AsyncClient(transport=MockTransport()) as client:
65 data = {key: "abc"}66 files = {"file": io.BytesIO(b"<file content>")}67 with pytest.raises(TypeError) as e:68 await client.post(69 "http://127.0.0.1:8000/",70 data=data,71 files=files,72 )73 assert "Invalid type for name" in str(e.value)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 74–78why, one step back
74
7576@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))77@pytest.mark.asyncio78async def test_multipart_invalid_value(value):

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 79–84why, one step back
79 async with httpx.AsyncClient(transport=MockTransport()) as client:
80 data = {"text": value}81 files = {"file": io.BytesIO(b"<file content>")}82 with pytest.raises(TypeError) as e:83 await client.post("http://127.0.0.1:8000/", data=data, files=files)84 assert "Invalid type for value" in str(e.value)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 85–88why, one step back
85
8687@pytest.mark.asyncio88async def test_multipart_file_tuple():

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 89–95why, one step back
89 async with httpx.AsyncClient(transport=MockTransport()) as client:
90 # Test with a list of values 'data' argument,91 # and a tuple style 'files' argument.92 data = {"text": ["abc"]}93 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}94 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)95 assert response.status_code == 200

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 96why, one step back
96

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 97–105why, one step back
97 # We're using the cgi module to verify the behavior here, which is a
98 # bit grungy, but sufficient just for our testing purposes.99 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]100 content_length = response.request.headers["Content-Length"]101 pdict: dict = {102 "boundary": boundary.encode("ascii"),103 "CONTENT-LENGTH": content_length,104 }105 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 106why, one step back
106

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

lines 107–110why, one step back
107 # Note that the expected return type for text fields
108 # appears to differs from 3.6 to 3.7+109 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]110 assert multipart["file"] == [b"<file content>"]

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 111–112why, one step back
111
112

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 118–121why, one step back
118 data = {
119 "a": "1",120 "b": b"C",121 "c": ["11", "22", "33"],

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

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 123why, one step back
123 }

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

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

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 128why, one step back
128

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 131–132why, one step back
131 assert stream.can_replay()
132

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 134why, one step back
134 content = (

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 149–150why, one step back
149
150

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

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

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 177–178why, one step back
177 file_name: str, expected_content_type: str
178) -> None:

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

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

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

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

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

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

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 212why, one step back
212 content = (

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

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

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

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

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

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

line 218why, one step back
218 )

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 219–242why, one step back
219 assert stream.get_headers()["Content-Length"] == str(len(content))
220 assert b"".join(stream) == content221222223def test_multipart_encode_non_seekable_filelike() -> None:224 """225 Test that special readable but non-seekable filelike objects are supported,226 at the cost of reading them into memory at most once.227 """228229 class IteratorIO(io.IOBase):230 def __init__(self, iterator: typing.Iterator[bytes]) -> None:231 self._iterator = iterator232233 def seekable(self) -> bool:234 return False235236 def read(self, *args: typing.Any) -> bytes:237 return b"".join(self._iterator)238239 def data() -> typing.Iterator[bytes]:240 yield b"Hello"241 yield b"World"242

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

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

Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831

lines 261–278why, one step back
261
262263class TestHeaderParamHTML5Formatting:264 def test_unicode(self):265 param = format_form_param("filename", "n\u00e4me")266 assert param == b'filename="n\xc3\xa4me"'267268 def test_ascii(self):269 param = format_form_param("filename", b"name")270 assert param == b'filename="name"'271272 def test_unicode_escape(self):273 param = format_form_param("filename", "hello\\world\u0022")274 assert param == b'filename="hello\\\\world%22"'275276 def test_unicode_with_control_character(self):277 param = format_form_param("filename", "hello\x1A\x1B\x1C")278 assert param == b'filename="hello%1A\x1B%1C"'