Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

268 lines · 9.5 KiB · Python

Last changed by

Include invalid name/value when raising TypeError in DataField (#1368)plotskibefore adoption589c6e0

History of this file

Take it

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

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

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

line 12why, one step back
12from tests.utils import MockTransport

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 13–14why, one step back
13
14

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 17–19why, one step back
17
1819@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))

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

line 20why, one step back
20def test_multipart(value, output):

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 22why, one step back
22

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

lines 23–27why, one step back
23 # Test with a single-value 'data' argument, and a plain file 'files' argument.
24 data = {"text": value}25 files = {"file": io.BytesIO(b"<file content>")}26 response = client.post("http://127.0.0.1:8000/", data=data, files=files)27 assert response.status_code == 200

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 28why, one step back
28

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

lines 29–37why, one step back
29 # We're using the cgi module to verify the behavior here, which is a
30 # bit grungy, but sufficient just for our testing purposes.31 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]32 content_length = response.request.headers["Content-Length"]33 pdict: dict = {34 "boundary": boundary.encode("ascii"),35 "CONTENT-LENGTH": content_length,36 }37 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 38why, one step back
38

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 43why, one step back
43

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

line 44why, one step back
44

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

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

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

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

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 48why, one step back
48

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

lines 49–57why, one step back
49 data = {key: "abc"}
50 files = {"file": io.BytesIO(b"<file content>")}51 with pytest.raises(TypeError) as e:52 client.post(53 "http://127.0.0.1:8000/",54 data=data,55 files=files,56 )57 assert "Invalid type for name" in str(e.value)

Include invalid name/value when raising TypeError in DataField (#1368)plotskibefore adoption589c6e0

line 58why, one step back
58 assert repr(key) in str(e.value)

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 59why, one step back
59

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

line 60why, one step back
60

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

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

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

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

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 64why, one step back
64

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

lines 65–69why, one step back
65 data = {"text": value}
66 files = {"file": io.BytesIO(b"<file content>")}67 with pytest.raises(TypeError) as e:68 client.post("http://127.0.0.1:8000/", data=data, files=files)69 assert "Invalid type for value" in str(e.value)

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 70–71why, one step back
70
71

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

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

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 74why, one step back
74

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

lines 75–95why, one step back
75 # Test with a list of values 'data' argument,
76 # and a tuple style 'files' argument.77 data = {"text": ["abc"]}78 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}79 response = client.post("http://127.0.0.1:8000/", data=data, files=files)80 assert response.status_code == 2008182 # We're using the cgi module to verify the behavior here, which is a83 # bit grungy, but sufficient just for our testing purposes.84 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]85 content_length = response.request.headers["Content-Length"]86 pdict: dict = {87 "boundary": boundary.encode("ascii"),88 "CONTENT-LENGTH": content_length,89 }90 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9192 # Note that the expected return type for text fields93 # appears to differs from 3.6 to 3.7+94 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]95 assert multipart["file"] == [b"<file content>"]

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 96–111why, one step back
96
9798def test_multipart_encode(tmp_path: typing.Any) -> None:99 path = str(tmp_path / "name.txt")100 with open(path, "wb") as f:101 f.write(b"<file content>")102103 data = {104 "a": "1",105 "b": b"C",106 "c": ["11", "22", "33"],107 "d": "",108 }109 files = {"file": ("name.txt", open(path, "rb"))}110111 with mock.patch("os.urandom", return_value=os.urandom(16)):

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 113why, one step back
113

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

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

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 135–139why, one step back
135
136137def test_multipart_encode_files_allows_filenames_as_none() -> None:138 files = {"file": (None, io.BytesIO(b"<file content>"))}139 with mock.patch("os.urandom", return_value=os.urandom(16)):

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 141why, one step back
141

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 144why, one step back
144

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 145why, one step back
145 content = (

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

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

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

lines 150–154why, one step back
150 assert headers == {
151 "Content-Type": f"multipart/form-data; boundary={boundary}",152 "Content-Length": str(len(content)),153 }154 assert content == b"".join(stream)

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 155–169why, one step back
155
156157@pytest.mark.parametrize(158 "file_name,expected_content_type",159 [160 ("example.json", "application/json"),161 ("example.txt", "text/plain"),162 ("no-extension", "application/octet-stream"),163 ],164)165def test_multipart_encode_files_guesses_correct_content_type(166 file_name: str, expected_content_type: str167) -> None:168 files = {"file": (file_name, io.BytesIO(b"<file content>"))}169 with mock.patch("os.urandom", return_value=os.urandom(16)):

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 171why, one step back
171

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 174why, one step back
174

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

line 175why, one step back
175 content = (

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 176–180why, one step back
176 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '
177 f'filename="{file_name}"\r\nContent-Type: '178 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"179 "".encode("ascii")180 )

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

lines 181–185why, one step back
181 assert headers == {
182 "Content-Type": f"multipart/form-data; boundary={boundary}",183 "Content-Length": str(len(content)),184 }185 assert content == b"".join(stream)

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 186–196why, one step back
186
187188@pytest.mark.parametrize(189 "value, output",190 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),191)192def test_multipart_encode_files_allows_bytes_or_str_content(193 value: typing.Union[str, bytes], output: str194) -> None:195 files = {"file": ("test.txt", value, "text/plain")}196 with mock.patch("os.urandom", return_value=os.urandom(16)):

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

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 198why, one step back
198

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 201–208why, one step back
201
202 content = (203 '--{0}\r\nContent-Disposition: form-data; name="file"; '204 'filename="test.txt"\r\n'205 "Content-Type: text/plain\r\n\r\n{1}\r\n"206 "--{0}--\r\n"207 "".format(boundary, output).encode("ascii")208 )

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

lines 209–213why, one step back
209 assert headers == {
210 "Content-Type": f"multipart/form-data; boundary={boundary}",211 "Content-Length": str(len(content)),212 }213 assert content == b"".join(stream)

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 214–232why, one step back
214
215216def test_multipart_encode_non_seekable_filelike() -> None:217 """218 Test that special readable but non-seekable filelike objects are supported,219 at the cost of reading them into memory at most once.220 """221222 class IteratorIO(io.IOBase):223 def __init__(self, iterator: typing.Iterator[bytes]) -> None:224 self._iterator = iterator225226 def read(self, *args: typing.Any) -> bytes:227 return b"".join(self._iterator)228229 def data() -> typing.Iterator[bytes]:230 yield b"Hello"231 yield b"World"232

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

line 234why, one step back
234 files = {"file": fileobj}

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 237–245why, one step back
237
238 content = (239 b"--+++\r\n"240 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'241 b"Content-Type: application/octet-stream\r\n"242 b"\r\n"243 b"HelloWorld\r\n"244 b"--+++--\r\n"245 )

Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

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

Refactor content streams (#1296)Tom Christiebefore adoption354c4ca

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

Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1

lines 251–268why, one step back
251
252253class TestHeaderParamHTML5Formatting:254 def test_unicode(self):255 param = format_form_param("filename", "n\u00e4me")256 assert param == b'filename="n\xc3\xa4me"'257258 def test_ascii(self):259 param = format_form_param("filename", b"name")260 assert param == b'filename="name"'261262 def test_unicode_escape(self):263 param = format_form_param("filename", "hello\\world\u0022")264 assert param == b'filename="hello\\\\world%22"'265266 def test_unicode_with_control_character(self):267 param = format_form_param("filename", "hello\x1A\x1B\x1C")268 assert param == b'filename="hello%1A\x1B%1C"'