test_multipart.py
This file
Path
tests/test_multipart.py
357 lines · 13.1 KiB · Python
Last changed by
Allow custom headers in multipart/form-data requests (#1936)Adrian Garcia Badaraccobefore adoption0f1ff50
History of this fileTake it
1import cgi2import io3import os4import typing5from unittest import mock67import pytest89import httpx10from httpx._content import encode_request11from httpx._utils import format_form_param121314def echo_request_content(request: httpx.Request) -> httpx.Response:15 return httpx.Response(200, content=request.content)161718@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))19def test_multipart(value, output):20 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))2122 # 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 == 2002728 # We're using the cgi module to verify the behavior here, which is a29 # 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)3738 # Note that the expected return type for text fields39 # 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>"]424344@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))45def test_multipart_invalid_key(key):46 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))4748 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)57 assert repr(key) in str(e.value)585960@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))61def test_multipart_invalid_value(value):62 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))6364 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)697071def test_multipart_file_tuple():72 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))7374 # 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>"]959697@pytest.mark.parametrize("content_type", [None, "text/plain"])98def test_multipart_file_tuple_headers(content_type: typing.Optional[str]):99 file_name = "test.txt"100 expected_content_type = "text/plain"101 headers = {"Expires": "0"}102103 files = {"file": (file_name, io.BytesIO(b"<file content>"), content_type, headers)}104 with mock.patch("os.urandom", return_value=os.urandom(16)):105 boundary = os.urandom(16).hex()106107 headers, stream = encode_request(data={}, files=files)108 assert isinstance(stream, typing.Iterable)109110 content = (111 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '112 f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '113 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"114 "".encode("ascii")115 )116 assert headers == {117 "Content-Type": f"multipart/form-data; boundary={boundary}",118 "Content-Length": str(len(content)),119 }120 assert content == b"".join(stream)121122123def test_multipart_headers_include_content_type() -> None:124 """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""125 file_name = "test.txt"126 expected_content_type = "image/png"127 headers = {"Content-Type": "image/png"}128129 files = {"file": (file_name, io.BytesIO(b"<file content>"), "text_plain", headers)}130 with mock.patch("os.urandom", return_value=os.urandom(16)):131 boundary = os.urandom(16).hex()132133 headers, stream = encode_request(data={}, files=files)134 assert isinstance(stream, typing.Iterable)135136 content = (137 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '138 f'filename="{file_name}"\r\nContent-Type: '139 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"140 "".encode("ascii")141 )142 assert headers == {143 "Content-Type": f"multipart/form-data; boundary={boundary}",144 "Content-Length": str(len(content)),145 }146 assert content == b"".join(stream)147148149def test_multipart_encode(tmp_path: typing.Any) -> None:150 path = str(tmp_path / "name.txt")151 with open(path, "wb") as f:152 f.write(b"<file content>")153154 data = {155 "a": "1",156 "b": b"C",157 "c": ["11", "22", "33"],158 "d": "",159 "e": True,160 "f": "",161 }162 with open(path, "rb") as input_file:163 files = {"file": ("name.txt", input_file)}164165 with mock.patch("os.urandom", return_value=os.urandom(16)):166 boundary = os.urandom(16).hex()167168 headers, stream = encode_request(data=data, files=files)169 assert isinstance(stream, typing.Iterable)170171 content = (172 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'173 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'174 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'175 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'176 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'177 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'178 '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'179 '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'180 '--{0}\r\nContent-Disposition: form-data; name="file";'181 ' filename="name.txt"\r\n'182 "Content-Type: text/plain\r\n\r\n<file content>\r\n"183 "--{0}--\r\n"184 "".format(boundary).encode("ascii")185 )186 assert headers == {187 "Content-Type": f"multipart/form-data; boundary={boundary}",188 "Content-Length": str(len(content)),189 }190 assert content == b"".join(stream)191192193def test_multipart_encode_unicode_file_contents() -> None:194 files = {"file": ("name.txt", b"<bytes content>")}195196 with mock.patch("os.urandom", return_value=os.urandom(16)):197 boundary = os.urandom(16).hex()198199 headers, stream = encode_request(files=files)200 assert isinstance(stream, typing.Iterable)201202 content = (203 '--{0}\r\nContent-Disposition: form-data; name="file";'204 ' filename="name.txt"\r\n'205 "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"206 "--{0}--\r\n"207 "".format(boundary).encode("utf-8")208 )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)214215216def test_multipart_encode_files_allows_filenames_as_none() -> None:217 files = {"file": (None, io.BytesIO(b"<file content>"))}218 with mock.patch("os.urandom", return_value=os.urandom(16)):219 boundary = os.urandom(16).hex()220221 headers, stream = encode_request(data={}, files=files)222 assert isinstance(stream, typing.Iterable)223224 content = (225 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'226 "<file content>\r\n--{0}--\r\n"227 "".format(boundary).encode("ascii")228 )229 assert headers == {230 "Content-Type": f"multipart/form-data; boundary={boundary}",231 "Content-Length": str(len(content)),232 }233 assert content == b"".join(stream)234235236@pytest.mark.parametrize(237 "file_name,expected_content_type",238 [239 ("example.json", "application/json"),240 ("example.txt", "text/plain"),241 ("no-extension", "application/octet-stream"),242 ],243)244def test_multipart_encode_files_guesses_correct_content_type(245 file_name: str, expected_content_type: str246) -> None:247 files = {"file": (file_name, io.BytesIO(b"<file content>"))}248 with mock.patch("os.urandom", return_value=os.urandom(16)):249 boundary = os.urandom(16).hex()250251 headers, stream = encode_request(data={}, files=files)252 assert isinstance(stream, typing.Iterable)253254 content = (255 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '256 f'filename="{file_name}"\r\nContent-Type: '257 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"258 "".encode("ascii")259 )260 assert headers == {261 "Content-Type": f"multipart/form-data; boundary={boundary}",262 "Content-Length": str(len(content)),263 }264 assert content == b"".join(stream)265266267def test_multipart_encode_files_allows_bytes_content() -> None:268 files = {"file": ("test.txt", b"<bytes content>", "text/plain")}269 with mock.patch("os.urandom", return_value=os.urandom(16)):270 boundary = os.urandom(16).hex()271272 headers, stream = encode_request(data={}, files=files)273 assert isinstance(stream, typing.Iterable)274275 content = (276 '--{0}\r\nContent-Disposition: form-data; name="file"; '277 'filename="test.txt"\r\n'278 "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"279 "--{0}--\r\n"280 "".format(boundary).encode("ascii")281 )282 assert headers == {283 "Content-Type": f"multipart/form-data; boundary={boundary}",284 "Content-Length": str(len(content)),285 }286 assert content == b"".join(stream)287288289def test_multipart_encode_files_raises_exception_with_str_content() -> None:290 files = {"file": ("test.txt", "<bytes content>", "text/plain")}291 with mock.patch("os.urandom", return_value=os.urandom(16)):292293 with pytest.raises(TypeError):294 encode_request(data={}, files=files) # type: ignore295296297def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:298 files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}299 with mock.patch("os.urandom", return_value=os.urandom(16)):300301 with pytest.raises(TypeError):302 encode_request(data={}, files=files) # type: ignore303304305def test_multipart_encode_non_seekable_filelike() -> None:306 """307 Test that special readable but non-seekable filelike objects are supported,308 at the cost of reading them into memory at most once.309 """310311 class IteratorIO(io.IOBase):312 def __init__(self, iterator: typing.Iterator[bytes]) -> None:313 self._iterator = iterator314315 def read(self, *args: typing.Any) -> bytes:316 return b"".join(self._iterator)317318 def data() -> typing.Iterator[bytes]:319 yield b"Hello"320 yield b"World"321322 fileobj: typing.Any = IteratorIO(data())323 files = {"file": fileobj}324 headers, stream = encode_request(files=files, boundary=b"+++")325 assert isinstance(stream, typing.Iterable)326327 content = (328 b"--+++\r\n"329 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'330 b"Content-Type: application/octet-stream\r\n"331 b"\r\n"332 b"HelloWorld\r\n"333 b"--+++--\r\n"334 )335 assert headers == {336 "Content-Type": "multipart/form-data; boundary=+++",337 "Content-Length": str(len(content)),338 }339 assert content == b"".join(stream)340341342class TestHeaderParamHTML5Formatting:343 def test_unicode(self):344 param = format_form_param("filename", "n\u00e4me")345 assert param == b'filename="n\xc3\xa4me"'346347 def test_ascii(self):348 param = format_form_param("filename", b"name")349 assert param == b'filename="name"'350351 def test_unicode_escape(self):352 param = format_form_param("filename", "hello\\world\u0022")353 assert param == b'filename="hello\\\\world%22"'354355 def test_unicode_with_control_character(self):356 param = format_form_param("filename", "hello\x1A\x1B\x1C")357 assert param == b'filename="hello%1A\x1B%1C"'