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
The walk stopped after 200 commits: lines older than 79a9748 point at it.
Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 1–3why, one step back1import cgi2import io3import osHttpcore interface (#804)Tom Christiebefore adoption3046e92
line 4why, one step back4import typingLoad SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 5–6why, one step back5from unittest import mock6Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 7why, one step back7import httpcoreLoad SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 8–10why, one step back8import pytest910import httpxType check tests (#1054)Florimond Mancabefore adoption0296c2b
line 11why, one step back11from httpx._content_streams import AsyncIteratorStream, MultipartStream, encodeSwitch to private module names (#785)Florimond Mancabefore adoption82dc6f3
line 12why, one step back12from httpx._utils import format_form_paramLoad SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 13–14why, one step back1314Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 15why, one step back15class MockTransport(httpcore.AsyncHTTPTransport):Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 16why, one step back16 async def request(Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
line 17why, one step back17 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 18why, one step back18 method: bytes,Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 19why, one step back19 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 20–21why, one step back20 headers: typing.List[typing.Tuple[bytes, bytes]] = None,21 stream: httpcore.AsyncByteStream = None,Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 22why, one step back22 timeout: typing.Mapping[str, typing.Optional[float]] = None,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 23–29why, one step back23 ) -> typing.Tuple[24 bytes,25 int,26 bytes,27 typing.List[typing.Tuple[bytes, bytes]],28 httpcore.AsyncByteStream,29 ]:Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 30why, one step back30 assert stream is not NoneHttpcore interface (#804)Tom Christiebefore adoption3046e92
lines 31–32why, one step back31 content = AsyncIteratorStream(aiterator=(part async for part in stream))32 return b"HTTP/1.1", 200, b"OK", [], contentLoad SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 33–37why, one step back333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio37async def test_multipart(value, output):Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 38why, one step back38 client = httpx.AsyncClient(transport=MockTransport())Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 39–49why, one step back3940 # 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"]Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 50–53why, one step back50 pdict: dict = {51 "boundary": boundary.encode("ascii"),52 "CONTENT-LENGTH": content_length,53 }Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 54–64why, one step back54 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):Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 65why, one step back65 client = httpx.AsyncClient(transport=MockTransport())Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 66–75why, one step back66 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):Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 76why, one step back76 client = httpx.AsyncClient(transport=MockTransport())Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 77–85why, one step back77 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():Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 86why, one step back86 client = httpx.AsyncClient(transport=MockTransport())Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 87–97why, one step back8788 # 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"]Type check tests (#1054)Florimond Mancabefore adoption0296c2b
lines 98–101why, one step back98 pdict: dict = {99 "boundary": boundary.encode("ascii"),100 "CONTENT-LENGTH": content_length,101 }Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 102–109why, one step back102 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>"]108109Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 110–114why, one step back110def 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>")114Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 115–118why, one step back115 data = {116 "a": "1",117 "b": b"C",118 "c": ["11", "22", "33"],Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 119why, one step back119 "d": "",Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
line 120why, one step back120 }Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 121why, one step back121 files = {"file": ("name.txt", open(path, "rb"))}Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 122–123why, one step back122123 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 124why, one step back124 boundary = os.urandom(16).hex()Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 125why, one step back125Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
line 126why, one step back126 stream = encode(data=data, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 127why, one step back127 assert isinstance(stream, MultipartStream)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 128–129why, one step back128 assert stream.can_replay()129Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
line 130why, one step back130 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 131why, one step back131 content = (Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 132–136why, one step back132 '--{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'Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 137why, one step back137 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 138–143why, one step back138 '--{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 )Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 144–145why, one step back144 assert stream.get_headers()["Content-Length"] == str(len(content))145 assert b"".join(stream) == contentLoad SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 146–147why, one step back146147Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 148why, one step back148def test_multipart_encode_files_allows_filenames_as_none() -> None:Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 149–150why, one step back149 files = {"file": (None, io.BytesIO(b"<file content>"))}150 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 151why, one step back151 boundary = os.urandom(16).hex()Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 152–153why, one step back152153 stream = encode(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 154why, one step back154 assert isinstance(stream, MultipartStream)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 155why, one step back155 assert stream.can_replay()Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 156–157why, one step back156157 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 158why, one step back158 assert b"".join(stream) == (Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 159–173why, one step back159 '--{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(Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 174–175why, one step back174 file_name: str, expected_content_type: str175) -> None:Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 176–177why, one step back176 files = {"file": (file_name, io.BytesIO(b"<file content>"))}177 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 178why, one step back178 boundary = os.urandom(16).hex()Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 179–180why, one step back179180 stream = encode(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 181why, one step back181 assert isinstance(stream, MultipartStream)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 182why, one step back182 assert stream.can_replay()Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 183–184why, one step back183184 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 185why, one step back185 assert b"".join(stream) == (Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 186–192why, one step back186 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 )191192Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
lines 193–200why, one step back193@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")}Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
line 201why, one step back201 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 202why, one step back202 boundary = os.urandom(16).hex()Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 203–204why, one step back203204 stream = encode(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 205why, one step back205 assert isinstance(stream, MultipartStream)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 206why, one step back206 assert stream.can_replay()Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 207–208why, one step back207208 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 209why, one step back209 content = (Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 210–211why, one step back210 '--{0}\r\nContent-Disposition: form-data; name="file"; '211 'filename="test.txt"\r\n'Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
line 212why, one step back212 "Content-Type: text/plain\r\n\r\n{1}\r\n"Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
line 213why, one step back213 "--{0}--\r\n"Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
line 214why, one step back214 "".format(boundary, output).encode("ascii")Load SSL Context on init (#709)Tom Christiebefore adoption79a9748
line 215why, one step back215 )Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 216–239why, one step back216 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"239Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 240why, one step back240 fileobj: typing.Any = IteratorIO(data())Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 241–257why, one step back241 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) == contentLoad SSL Context on init (#709)Tom Christiebefore adoption79a9748
lines 258–275why, one step back258259260class 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"'