test_multipart.py
This file
Path
tests/test_multipart.py
259 lines · 9.5 KiB · Python
Last changed by
Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
History of this fileTake it
1import binascii2import cgi3import io4import os5import typing6from unittest import mock78import httpcore9import pytest1011import httpx12from httpx._content_streams import AsyncIteratorStream, encode13from httpx._utils import format_form_param141516class MockDispatch(httpcore.AsyncHTTPTransport):17 async def request(18 self,19 method: bytes,20 url: typing.Tuple[bytes, bytes, int, bytes],21 headers: typing.List[typing.Tuple[bytes, bytes]] = None,22 stream: httpcore.AsyncByteStream = None,23 timeout: typing.Dict[str, typing.Optional[float]] = None,24 ) -> typing.Tuple[25 bytes,26 int,27 bytes,28 typing.List[typing.Tuple[bytes, bytes]],29 httpcore.AsyncByteStream,30 ]:31 content = AsyncIteratorStream(aiterator=(part async for part in stream))32 return b"HTTP/1.1", 200, b"OK", [], content333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio37async def test_multipart(value, output):38 client = httpx.AsyncClient(dispatch=MockDispatch())3940 # 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"]50 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}51 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5253 # Note that the expected return type for text fields54 # appears to differs from 3.6 to 3.7+55 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]56 assert multipart["file"] == [b"<file content>"]575859@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))60@pytest.mark.asyncio61async def test_multipart_invalid_key(key):62 client = httpx.AsyncClient(dispatch=MockDispatch())63 data = {key: "abc"}64 files = {"file": io.BytesIO(b"<file content>")}65 with pytest.raises(TypeError) as e:66 await client.post("http://127.0.0.1:8000/", data=data, files=files)67 assert "Invalid type for name" in str(e.value)686970@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))71@pytest.mark.asyncio72async def test_multipart_invalid_value(value):73 client = httpx.AsyncClient(dispatch=MockDispatch())74 data = {"text": value}75 files = {"file": io.BytesIO(b"<file content>")}76 with pytest.raises(TypeError) as e:77 await client.post("http://127.0.0.1:8000/", data=data, files=files)78 assert "Invalid type for value" in str(e.value)798081@pytest.mark.asyncio82async def test_multipart_file_tuple():83 client = httpx.AsyncClient(dispatch=MockDispatch())8485 # Test with a list of values 'data' argument, and a tuple style 'files' argument.86 data = {"text": ["abc"]}87 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}88 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)89 assert response.status_code == 2009091 # We're using the cgi module to verify the behavior here, which is a92 # bit grungy, but sufficient just for our testing purposes.93 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]94 content_length = response.request.headers["Content-Length"]95 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}96 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9798 # Note that the expected return type for text fields99 # appears to differs from 3.6 to 3.7+100 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]101 assert multipart["file"] == [b"<file content>"]102103104def test_multipart_encode(tmp_path: typing.Any) -> None:105 path = str(tmp_path / "name.txt")106 with open(path, "wb") as f:107 f.write(b"<file content>")108109 data = {110 "a": "1",111 "b": b"C",112 "c": ["11", "22", "33"],113 "d": "",114 }115 files = {"file": ("name.txt", open(path, "rb"))}116117 with mock.patch("os.urandom", return_value=os.urandom(16)):118 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")119120 stream = encode(data=data, files=files)121 assert stream.can_replay()122123 assert stream.content_type == f"multipart/form-data; boundary={boundary}"124 content = (125 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'126 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'128 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'129 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'130 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'131 '--{0}\r\nContent-Disposition: form-data; name="file";'132 ' filename="name.txt"\r\n'133 "Content-Type: text/plain\r\n\r\n<file content>\r\n"134 "--{0}--\r\n"135 "".format(boundary).encode("ascii")136 )137 assert stream.get_headers()["Content-Length"] == str(len(content))138 assert b"".join(stream) == content139140141def test_multipart_encode_files_allows_filenames_as_none() -> None:142 files = {"file": (None, io.BytesIO(b"<file content>"))}143 with mock.patch("os.urandom", return_value=os.urandom(16)):144 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")145146 stream = encode(data={}, files=files)147 assert stream.can_replay()148149 assert stream.content_type == f"multipart/form-data; boundary={boundary}"150 assert b"".join(stream) == (151 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'152 "<file content>\r\n--{0}--\r\n"153 "".format(boundary).encode("ascii")154 )155156157@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)):170 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")171172 stream = encode(data={}, files=files)173 assert stream.can_replay()174175 assert stream.content_type == f"multipart/form-data; boundary={boundary}"176 assert b"".join(stream) == (177 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '178 f'filename="{file_name}"\r\nContent-Type: '179 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"180 "".encode("ascii")181 )182183184def test_multipart_encode_files_allows_str_content() -> None:185 files = {"file": ("test.txt", "<string content>", "text/plain")}186 with mock.patch("os.urandom", return_value=os.urandom(16)):187 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")188189 stream = encode(data={}, files=files)190 assert stream.can_replay()191192 assert stream.content_type == f"multipart/form-data; boundary={boundary}"193 content = (194 '--{0}\r\nContent-Disposition: form-data; name="file"; '195 'filename="test.txt"\r\n'196 "Content-Type: text/plain\r\n\r\n<string content>\r\n"197 "--{0}--\r\n"198 "".format(boundary).encode("ascii")199 )200 assert stream.get_headers()["Content-Length"] == str(len(content))201 assert b"".join(stream) == content202203204def test_multipart_encode_non_seekable_filelike() -> None:205 """206 Test that special readable but non-seekable filelike objects are supported,207 at the cost of reading them into memory at most once.208 """209210 class IteratorIO(io.IOBase):211 def __init__(self, iterator: typing.Iterator[bytes]) -> None:212 self._iterator = iterator213214 def seekable(self) -> bool:215 return False216217 def read(self, *args: typing.Any) -> bytes:218 return b"".join(self._iterator)219220 def data() -> typing.Iterator[bytes]:221 yield b"Hello"222 yield b"World"223224 fileobj = IteratorIO(data())225 files = {"file": fileobj}226 stream = encode(files=files, boundary=b"+++")227 assert not stream.can_replay()228229 content = (230 b"--+++\r\n"231 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'232 b"Content-Type: application/octet-stream\r\n"233 b"\r\n"234 b"HelloWorld\r\n"235 b"--+++--\r\n"236 )237 assert stream.get_headers() == {238 "Content-Type": "multipart/form-data; boundary=+++",239 "Content-Length": str(len(content)),240 }241 assert b"".join(stream) == content242243244class TestHeaderParamHTML5Formatting:245 def test_unicode(self):246 param = format_form_param("filename", "n\u00e4me")247 assert param == b'filename="n\xc3\xa4me"'248249 def test_ascii(self):250 param = format_form_param("filename", b"name")251 assert param == b'filename="name"'252253 def test_unicode_escape(self):254 param = format_form_param("filename", "hello\\world\u0022")255 assert param == b'filename="hello\\\\world%22"'256257 def test_unicode_with_control_character(self):258 param = format_form_param("filename", "hello\x1A\x1B\x1C")259 assert param == b'filename="hello%1A\x1B%1C"'