test_multipart.py
This file
Path
tests/test_multipart.py
275 lines · 9.9 KiB · Python
Last changed by
Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
History of this fileTake it
1import cgi2import io3import os4import typing5from unittest import mock67import httpcore8import pytest910import httpx11from httpx._content_streams import AsyncIteratorStream, MultipartStream, encode12from httpx._utils import format_form_param131415class MockTransport(httpcore.AsyncHTTPTransport):16 async def request(17 self,18 method: bytes,19 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],20 headers: typing.List[typing.Tuple[bytes, bytes]] = None,21 stream: httpcore.AsyncByteStream = None,22 timeout: typing.Mapping[str, typing.Optional[float]] = None,23 ) -> typing.Tuple[24 bytes,25 int,26 bytes,27 typing.List[typing.Tuple[bytes, bytes]],28 httpcore.AsyncByteStream,29 ]:30 assert stream is not None31 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(transport=MockTransport())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: dict = {51 "boundary": boundary.encode("ascii"),52 "CONTENT-LENGTH": content_length,53 }54 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5556 # Note that the expected return type for text fields57 # appears to differs from 3.6 to 3.7+58 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]59 assert multipart["file"] == [b"<file content>"]606162@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))63@pytest.mark.asyncio64async def test_multipart_invalid_key(key):65 client = httpx.AsyncClient(transport=MockTransport())66 data = {key: "abc"}67 files = {"file": io.BytesIO(b"<file content>")}68 with pytest.raises(TypeError) as e:69 await client.post("http://127.0.0.1:8000/", data=data, files=files)70 assert "Invalid type for name" in str(e.value)717273@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))74@pytest.mark.asyncio75async def test_multipart_invalid_value(value):76 client = httpx.AsyncClient(transport=MockTransport())77 data = {"text": value}78 files = {"file": io.BytesIO(b"<file content>")}79 with pytest.raises(TypeError) as e:80 await client.post("http://127.0.0.1:8000/", data=data, files=files)81 assert "Invalid type for value" in str(e.value)828384@pytest.mark.asyncio85async def test_multipart_file_tuple():86 client = httpx.AsyncClient(transport=MockTransport())8788 # Test with a list of values 'data' argument, and a tuple style 'files' argument.89 data = {"text": ["abc"]}90 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}91 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)92 assert response.status_code == 2009394 # We're using the cgi module to verify the behavior here, which is a95 # bit grungy, but sufficient just for our testing purposes.96 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]97 content_length = response.request.headers["Content-Length"]98 pdict: dict = {99 "boundary": boundary.encode("ascii"),100 "CONTENT-LENGTH": content_length,101 }102 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)103104 # Note that the expected return type for text fields105 # appears to differs from 3.6 to 3.7+106 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]107 assert multipart["file"] == [b"<file content>"]108109110def test_multipart_encode(tmp_path: typing.Any) -> None:111 path = str(tmp_path / "name.txt")112 with open(path, "wb") as f:113 f.write(b"<file content>")114115 data = {116 "a": "1",117 "b": b"C",118 "c": ["11", "22", "33"],119 "d": "",120 }121 files = {"file": ("name.txt", open(path, "rb"))}122123 with mock.patch("os.urandom", return_value=os.urandom(16)):124 boundary = os.urandom(16).hex()125126 stream = encode(data=data, files=files)127 assert isinstance(stream, MultipartStream)128 assert stream.can_replay()129130 assert stream.content_type == f"multipart/form-data; boundary={boundary}"131 content = (132 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'133 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'134 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'135 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'136 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'137 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'138 '--{0}\r\nContent-Disposition: form-data; name="file";'139 ' filename="name.txt"\r\n'140 "Content-Type: text/plain\r\n\r\n<file content>\r\n"141 "--{0}--\r\n"142 "".format(boundary).encode("ascii")143 )144 assert stream.get_headers()["Content-Length"] == str(len(content))145 assert b"".join(stream) == content146147148def test_multipart_encode_files_allows_filenames_as_none() -> None:149 files = {"file": (None, io.BytesIO(b"<file content>"))}150 with mock.patch("os.urandom", return_value=os.urandom(16)):151 boundary = os.urandom(16).hex()152153 stream = encode(data={}, files=files)154 assert isinstance(stream, MultipartStream)155 assert stream.can_replay()156157 assert stream.content_type == f"multipart/form-data; boundary={boundary}"158 assert b"".join(stream) == (159 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'160 "<file content>\r\n--{0}--\r\n"161 "".format(boundary).encode("ascii")162 )163164165@pytest.mark.parametrize(166 "file_name,expected_content_type",167 [168 ("example.json", "application/json"),169 ("example.txt", "text/plain"),170 ("no-extension", "application/octet-stream"),171 ],172)173def test_multipart_encode_files_guesses_correct_content_type(174 file_name: str, expected_content_type: str175) -> None:176 files = {"file": (file_name, io.BytesIO(b"<file content>"))}177 with mock.patch("os.urandom", return_value=os.urandom(16)):178 boundary = os.urandom(16).hex()179180 stream = encode(data={}, files=files)181 assert isinstance(stream, MultipartStream)182 assert stream.can_replay()183184 assert stream.content_type == f"multipart/form-data; boundary={boundary}"185 assert b"".join(stream) == (186 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '187 f'filename="{file_name}"\r\nContent-Type: '188 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"189 "".encode("ascii")190 )191192193@pytest.mark.parametrize(194 "value, output",195 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),196)197def test_multipart_encode_files_allows_bytes_or_str_content(198 value: typing.Union[str, bytes], output: str199) -> None:200 files = {"file": ("test.txt", value, "text/plain")}201 with mock.patch("os.urandom", return_value=os.urandom(16)):202 boundary = os.urandom(16).hex()203204 stream = encode(data={}, files=files)205 assert isinstance(stream, MultipartStream)206 assert stream.can_replay()207208 assert stream.content_type == f"multipart/form-data; boundary={boundary}"209 content = (210 '--{0}\r\nContent-Disposition: form-data; name="file"; '211 'filename="test.txt"\r\n'212 "Content-Type: text/plain\r\n\r\n{1}\r\n"213 "--{0}--\r\n"214 "".format(boundary, output).encode("ascii")215 )216 assert stream.get_headers()["Content-Length"] == str(len(content))217 assert b"".join(stream) == content218219220def test_multipart_encode_non_seekable_filelike() -> None:221 """222 Test that special readable but non-seekable filelike objects are supported,223 at the cost of reading them into memory at most once.224 """225226 class IteratorIO(io.IOBase):227 def __init__(self, iterator: typing.Iterator[bytes]) -> None:228 self._iterator = iterator229230 def seekable(self) -> bool:231 return False232233 def read(self, *args: typing.Any) -> bytes:234 return b"".join(self._iterator)235236 def data() -> typing.Iterator[bytes]:237 yield b"Hello"238 yield b"World"239240 fileobj: typing.Any = IteratorIO(data())241 files = {"file": fileobj}242 stream = encode(files=files, boundary=b"+++")243 assert not stream.can_replay()244245 content = (246 b"--+++\r\n"247 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'248 b"Content-Type: application/octet-stream\r\n"249 b"\r\n"250 b"HelloWorld\r\n"251 b"--+++--\r\n"252 )253 assert stream.get_headers() == {254 "Content-Type": "multipart/form-data; boundary=+++",255 "Content-Length": str(len(content)),256 }257 assert b"".join(stream) == content258259260class TestHeaderParamHTML5Formatting:261 def test_unicode(self):262 param = format_form_param("filename", "n\u00e4me")263 assert param == b'filename="n\xc3\xa4me"'264265 def test_ascii(self):266 param = format_form_param("filename", b"name")267 assert param == b'filename="name"'268269 def test_unicode_escape(self):270 param = format_form_param("filename", "hello\\world\u0022")271 assert param == b'filename="hello\\\\world%22"'272273 def test_unicode_with_control_character(self):274 param = format_form_param("filename", "hello\x1A\x1B\x1C")275 assert param == b'filename="hello%1A\x1B%1C"'