Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

290 lines · 10.3 KiB · Python

Last changed by

Fix Content-Length for unicode file contents with multipart (#1537)Tom Christiebefore adoptionc75ddc2

History of this file

Take it

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

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 1–9why, one step back
1import cgi
2import io3import os4import typing5from unittest import mock67import pytest89import httpx

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 10why, one step back
10from httpx._content import encode_request

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 11–13why, one step back
11from httpx._utils import format_form_param
1213

Refactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d

lines 14–15why, one step back
14def echo_request_content(request: httpx.Request) -> httpx.Response:
15 return httpx.Response(200, content=request.content)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 16–18why, one step back
16
1718@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 back
19def test_multipart(value, output):

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 20why, one step back
20 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 21why, one step back
21

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 22–26why, one step back
22 # 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 == 200

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 27why, one step back
27

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 28–36why, one step back
28 # We're using the cgi module to verify the behavior here, which is a
29 # 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)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 37why, one step back
37

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 38–41why, one step back
38 # Note that the expected return type for text fields
39 # 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>"]

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 42why, one step back
42

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 43why, one step back
43

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 44why, one step back
44@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 45why, one step back
45def test_multipart_invalid_key(key):

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 46why, one step back
46 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 47why, one step back
47

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 48–56why, one step back
48 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 back
57 assert repr(key) in str(e.value)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 58why, one step back
58

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 59why, one step back
59

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 60why, one step back
60@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 61why, one step back
61def test_multipart_invalid_value(value):

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 62why, one step back
62 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 63why, one step back
63

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 64–68why, one step back
64 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)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 69–70why, one step back
69
70

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 71why, one step back
71def test_multipart_file_tuple():

Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac

line 72why, one step back
72 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 73why, one step back
73

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 74–94why, one step back
74 # 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>"]

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 95–112why, one step back
95
9697def 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": "",107 }108 files = {"file": ("name.txt", open(path, "rb"))}109110 with mock.patch("os.urandom", return_value=os.urandom(16)):111 boundary = os.urandom(16).hex()112

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 113why, one step back
113 headers, stream = encode_request(data=data, files=files)

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 114why, one step back
114 assert isinstance(stream, typing.Iterable)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 115–128why, one step back
115
116 content = (117 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'118 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'119 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'120 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'121 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'122 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'123 '--{0}\r\nContent-Disposition: form-data; name="file";'124 ' filename="name.txt"\r\n'125 "Content-Type: text/plain\r\n\r\n<file content>\r\n"126 "--{0}--\r\n"127 "".format(boundary).encode("ascii")128 )

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

lines 129–133why, one step back
129 assert headers == {
130 "Content-Type": f"multipart/form-data; boundary={boundary}",131 "Content-Length": str(len(content)),132 }133 assert content == b"".join(stream)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 134–135why, one step back
134
135

Fix Content-Length for unicode file contents with multipart (#1537)Tom Christiebefore adoptionc75ddc2

lines 136–158why, one step back
136def test_multipart_encode_unicode_file_contents() -> None:
137 files = {"file": ("name.txt", "<únicode string>")}138139 with mock.patch("os.urandom", return_value=os.urandom(16)):140 boundary = os.urandom(16).hex()141142 headers, stream = encode_request(files=files)143 assert isinstance(stream, typing.Iterable)144145 content = (146 '--{0}\r\nContent-Disposition: form-data; name="file";'147 ' filename="name.txt"\r\n'148 "Content-Type: text/plain\r\n\r\n<únicode string>\r\n"149 "--{0}--\r\n"150 "".format(boundary).encode("utf-8")151 )152 assert headers == {153 "Content-Type": f"multipart/form-data; boundary={boundary}",154 "Content-Length": str(len(content)),155 }156 assert content == b"".join(stream)157158

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 159–163why, one step back
159def test_multipart_encode_files_allows_filenames_as_none() -> None:
160 files = {"file": (None, io.BytesIO(b"<file content>"))}161 with mock.patch("os.urandom", return_value=os.urandom(16)):162 boundary = os.urandom(16).hex()163

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 164why, one step back
164 headers, stream = encode_request(data={}, files=files)

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 165why, one step back
165 assert isinstance(stream, typing.Iterable)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 166why, one step back
166

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 167why, one step back
167 content = (

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 168–171why, one step back
168 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'
169 "<file content>\r\n--{0}--\r\n"170 "".format(boundary).encode("ascii")171 )

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

lines 172–176why, one step back
172 assert headers == {
173 "Content-Type": f"multipart/form-data; boundary={boundary}",174 "Content-Length": str(len(content)),175 }176 assert content == b"".join(stream)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 177–193why, one step back
177
178179@pytest.mark.parametrize(180 "file_name,expected_content_type",181 [182 ("example.json", "application/json"),183 ("example.txt", "text/plain"),184 ("no-extension", "application/octet-stream"),185 ],186)187def test_multipart_encode_files_guesses_correct_content_type(188 file_name: str, expected_content_type: str189) -> None:190 files = {"file": (file_name, io.BytesIO(b"<file content>"))}191 with mock.patch("os.urandom", return_value=os.urandom(16)):192 boundary = os.urandom(16).hex()193

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 194why, one step back
194 headers, stream = encode_request(data={}, files=files)

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 195why, one step back
195 assert isinstance(stream, typing.Iterable)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

line 196why, one step back
196

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 197why, one step back
197 content = (

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 198–202why, one step back
198 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '
199 f'filename="{file_name}"\r\nContent-Type: '200 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"201 "".encode("ascii")202 )

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

lines 203–207why, one step back
203 assert headers == {
204 "Content-Type": f"multipart/form-data; boundary={boundary}",205 "Content-Length": str(len(content)),206 }207 assert content == b"".join(stream)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 208–220why, one step back
208
209210@pytest.mark.parametrize(211 "value, output",212 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),213)214def test_multipart_encode_files_allows_bytes_or_str_content(215 value: typing.Union[str, bytes], output: str216) -> None:217 files = {"file": ("test.txt", value, "text/plain")}218 with mock.patch("os.urandom", return_value=os.urandom(16)):219 boundary = os.urandom(16).hex()220

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 221why, one step back
221 headers, stream = encode_request(data={}, files=files)

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 222why, one step back
222 assert isinstance(stream, typing.Iterable)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 223–230why, one step back
223
224 content = (225 '--{0}\r\nContent-Disposition: form-data; name="file"; '226 'filename="test.txt"\r\n'227 "Content-Type: text/plain\r\n\r\n{1}\r\n"228 "--{0}--\r\n"229 "".format(boundary, output).encode("ascii")230 )

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

lines 231–235why, one step back
231 assert headers == {
232 "Content-Type": f"multipart/form-data; boundary={boundary}",233 "Content-Length": str(len(content)),234 }235 assert content == b"".join(stream)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 236–256why, one step back
236
237238def test_multipart_encode_non_seekable_filelike() -> None:239 """240 Test that special readable but non-seekable filelike objects are supported,241 at the cost of reading them into memory at most once.242 """243244 class IteratorIO(io.IOBase):245 def __init__(self, iterator: typing.Iterator[bytes]) -> None:246 self._iterator = iterator247248 def read(self, *args: typing.Any) -> bytes:249 return b"".join(self._iterator)250251 def data() -> typing.Iterator[bytes]:252 yield b"Hello"253 yield b"World"254255 fileobj: typing.Any = IteratorIO(data())256 files = {"file": fileobj}

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

lines 257–258why, one step back
257 headers, stream = encode_request(files=files, boundary=b"+++")
258 assert isinstance(stream, typing.Iterable)

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 259–267why, one step back
259
260 content = (261 b"--+++\r\n"262 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'263 b"Content-Type: application/octet-stream\r\n"264 b"\r\n"265 b"HelloWorld\r\n"266 b"--+++--\r\n"267 )

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

line 268why, one step back
268 assert headers == {

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 269–271why, one step back
269 "Content-Type": "multipart/form-data; boundary=+++",
270 "Content-Length": str(len(content)),271 }

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

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

Tighten public API on auth classes (#1084)Tom Christiebefore adoption6421575

lines 273–290why, one step back
273
274275class TestHeaderParamHTML5Formatting:276 def test_unicode(self):277 param = format_form_param("filename", "n\u00e4me")278 assert param == b'filename="n\xc3\xa4me"'279280 def test_ascii(self):281 param = format_form_param("filename", b"name")282 assert param == b'filename="name"'283284 def test_unicode_escape(self):285 param = format_form_param("filename", "hello\\world\u0022")286 assert param == b'filename="hello\\\\world%22"'287288 def test_unicode_with_control_character(self):289 param = format_form_param("filename", "hello\x1A\x1B\x1C")290 assert param == b'filename="hello%1A\x1B%1C"'