test_multipart.py
This file
Path
tests/test_multipart.py
265 lines · 9.7 KiB · Python
Last changed by
Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
History of this fileTake it
The walk stopped after 200 commits: lines older than bb6e52f point at it.
Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 1–4why, one step back1import binascii2import cgi3import io4import osHttpcore interface (#804)Tom Christiebefore adoption3046e92
line 5why, one step back5import typingRename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 6–7why, one step back6from unittest import mock7Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 8why, one step back8import httpcoreRename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 9–10why, one step back9import pytest10Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
line 11why, one step back11import httpxHttpcore interface (#804)Tom Christiebefore adoption3046e92
line 12why, one step back12from httpx._content_streams import AsyncIteratorStream, encodeSwitch to private module names (#785)Florimond Mancabefore adoption82dc6f3
line 13why, one step back13from httpx._utils import format_form_paramRename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 14–15why, one step back1415Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 16why, one step back16class MockTransport(httpcore.AsyncHTTPTransport):Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 17why, one step back17 async def request(Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
line 18why, one step back18 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 19–32why, one step back19 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", [], contentRename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
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())Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 39–61why, 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"]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):Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 62why, one step back62 client = httpx.AsyncClient(transport=MockTransport())Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 63–72why, one step back63 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):Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 73why, one step back73 client = httpx.AsyncClient(transport=MockTransport())Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 74–82why, one step back74 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():Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 83why, one step back83 client = httpx.AsyncClient(transport=MockTransport())Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 84–103why, one step back8485 # 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>"]102103Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 104–108why, one step back104def 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>")108Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 109–112why, one step back109 data = {110 "a": "1",111 "b": b"C",112 "c": ["11", "22", "33"],Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 113why, one step back113 "d": "",Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
line 114why, one step back114 }Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 115why, one step back115 files = {"file": ("name.txt", open(path, "rb"))}Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 116–118why, one step back116117 with mock.patch("os.urandom", return_value=os.urandom(16)):118 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 119why, one step back119Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 120why, one step back120 stream = encode(data=data, files=files)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 121–122why, one step back121 assert stream.can_replay()122Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 123why, one step back123 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 124why, one step back124 content = (Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 125–129why, one step back125 '--{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'Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 130why, one step back130 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 131–136why, one step back131 '--{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 )Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 137–138why, one step back137 assert stream.get_headers()["Content-Length"] == str(len(content))138 assert b"".join(stream) == contentRename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 139–140why, one step back139140Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 141why, one step back141def test_multipart_encode_files_allows_filenames_as_none() -> None:Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 142–145why, one step back142 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")145Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 146why, one step back146 stream = encode(data={}, files=files)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 147why, one step back147 assert stream.can_replay()Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
line 148why, one step back148Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 149why, one step back149 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 150why, one step back150 assert b"".join(stream) == (Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 151–165why, one step back151 '--{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(Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 166–167why, one step back166 file_name: str, expected_content_type: str167) -> None:Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 168–171why, one step back168 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")171Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 172why, one step back172 stream = encode(data={}, files=files)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 173why, one step back173 assert stream.can_replay()Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
line 174why, one step back174Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 175why, one step back175 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 176why, one step back176 assert b"".join(stream) == (Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 177–183why, one step back177 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 )182183Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
lines 184–191why, one step back184@pytest.mark.parametrize(185 "value, output",186 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),187)188def test_multipart_encode_files_allows_bytes_or_str_content(189 value: typing.Union[str, bytes], output: str190) -> None:191 files = {"file": ("test.txt", value, "text/plain")}Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 192–194why, one step back192 with mock.patch("os.urandom", return_value=os.urandom(16)):193 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")194Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 195why, one step back195 stream = encode(data={}, files=files)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 196why, one step back196 assert stream.can_replay()Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
line 197why, one step back197Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 198why, one step back198 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 199why, one step back199 content = (Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 200–201why, one step back200 '--{0}\r\nContent-Disposition: form-data; name="file"; '201 'filename="test.txt"\r\n'Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
line 202why, one step back202 "Content-Type: text/plain\r\n\r\n{1}\r\n"Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
line 203why, one step back203 "--{0}--\r\n"Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
line 204why, one step back204 "".format(boundary, output).encode("ascii")Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
line 205why, one step back205 )Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 206–247why, one step back206 assert stream.get_headers()["Content-Length"] == str(len(content))207 assert b"".join(stream) == content208209210def test_multipart_encode_non_seekable_filelike() -> None:211 """212 Test that special readable but non-seekable filelike objects are supported,213 at the cost of reading them into memory at most once.214 """215216 class IteratorIO(io.IOBase):217 def __init__(self, iterator: typing.Iterator[bytes]) -> None:218 self._iterator = iterator219220 def seekable(self) -> bool:221 return False222223 def read(self, *args: typing.Any) -> bytes:224 return b"".join(self._iterator)225226 def data() -> typing.Iterator[bytes]:227 yield b"Hello"228 yield b"World"229230 fileobj = IteratorIO(data())231 files = {"file": fileobj}232 stream = encode(files=files, boundary=b"+++")233 assert not stream.can_replay()234235 content = (236 b"--+++\r\n"237 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'238 b"Content-Type: application/octet-stream\r\n"239 b"\r\n"240 b"HelloWorld\r\n"241 b"--+++--\r\n"242 )243 assert stream.get_headers() == {244 "Content-Type": "multipart/form-data; boundary=+++",245 "Content-Length": str(len(content)),246 }247 assert b"".join(stream) == contentRename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 248–251why, one step back248249250class TestHeaderParamHTML5Formatting:251 def test_unicode(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 252why, one step back252 param = format_form_param("filename", "n\u00e4me")Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 253–255why, one step back253 assert param == b'filename="n\xc3\xa4me"'254255 def test_ascii(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 256why, one step back256 param = format_form_param("filename", b"name")Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 257–259why, one step back257 assert param == b'filename="name"'258259 def test_unicode_escape(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 260why, one step back260 param = format_form_param("filename", "hello\\world\u0022")Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
lines 261–263why, one step back261 assert param == b'filename="hello\\\\world%22"'262263 def test_unicode_with_control_character(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 264why, one step back264 param = format_form_param("filename", "hello\x1A\x1B\x1C")Rename BaseSocketStream cases from connection.stream to connection.socket (#601)Tom Christiebefore adoptionbb6e52f
line 265why, one step back265 assert param == b'filename="hello%1A\x1B%1C"'