test_multipart.py
This file
Path
tests/test_multipart.py
198 lines · 7.7 KiB · Python
Last changed by
Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
History of this fileTake it
The walk stopped after 200 commits: lines older than 07586f9 point at it.
Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 1–8why, one step back1import binascii2import cgi3import io4import os5from unittest import mock67import pytest8Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
line 9why, one step back9import httpxSwitch to private module names (#785)Florimond Mancabefore adoption82dc6f3
lines 10–13why, one step back10from httpx._config import CertTypes, TimeoutTypes, VerifyTypes11from httpx._content_streams import encode12from httpx._dispatch.base import AsyncDispatcher13from httpx._utils import format_form_paramConvert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 14–15why, one step back1415Dispatcher -> AsyncDispatcher (#725)Tom Christiebefore adoptione19bd9b
line 16why, one step back16class MockDispatch(AsyncDispatcher):Drop sync (#544)Tom Christiebefore adoption206c537
line 17why, one step back17 async def send(Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 18why, one step back18 self,Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
line 19why, one step back19 request: httpx.Request,Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 20–22why, one step back20 verify: VerifyTypes = None,21 cert: CertTypes = None,22 timeout: TimeoutTypes = None,Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
line 23why, one step back23 ) -> httpx.Response:Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 24why, one step back24 content = b"".join([part async for part in request.stream])Make 'request' non-optional on responses (#666)Florimond Mancabefore adoption56c8eda
line 25why, one step back25 return httpx.Response(200, content=content, request=request)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 26–28why, one step back262728@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))Drop sync (#544)Tom Christiebefore adoption206c537
lines 29–30why, one step back29@pytest.mark.asyncio30async def test_multipart(value, output):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 31why, one step back31 client = httpx.AsyncClient(dispatch=MockDispatch())Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 32–35why, one step back3233 # Test with a single-value 'data' argument, and a plain file 'files' argument.34 data = {"text": value}35 files = {"file": io.BytesIO(b"<file content>")}Drop sync (#544)Tom Christiebefore adoption206c537
line 36why, one step back36 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 37–52why, one step back37 assert response.status_code == 2003839 # We're using the cgi module to verify the behavior here, which is a40 # bit grungy, but sufficient just for our testing purposes.41 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]42 content_length = response.request.headers["Content-Length"]43 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}44 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)4546 # Note that the expected return type for text fields47 # appears to differs from 3.6 to 3.7+48 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]49 assert multipart["file"] == [b"<file content>"]505152@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))Drop sync (#544)Tom Christiebefore adoption206c537
lines 53–54why, one step back53@pytest.mark.asyncio54async def test_multipart_invalid_key(key):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 55why, one step back55 client = httpx.AsyncClient(dispatch=MockDispatch())Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 56–58why, one step back56 data = {key: "abc"}57 files = {"file": io.BytesIO(b"<file content>")}58 with pytest.raises(TypeError) as e:Drop sync (#544)Tom Christiebefore adoption206c537
line 59why, one step back59 await client.post("http://127.0.0.1:8000/", data=data, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 60–63why, one step back60 assert "Invalid type for name" in str(e.value)616263@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))Drop sync (#544)Tom Christiebefore adoption206c537
lines 64–65why, one step back64@pytest.mark.asyncio65async def test_multipart_invalid_value(value):Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 66why, one step back66 client = httpx.AsyncClient(dispatch=MockDispatch())Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 67–69why, one step back67 data = {"text": value}68 files = {"file": io.BytesIO(b"<file content>")}69 with pytest.raises(TypeError) as e:Drop sync (#544)Tom Christiebefore adoption206c537
line 70why, one step back70 await client.post("http://127.0.0.1:8000/", data=data, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 71–73why, one step back71 assert "Invalid type for value" in str(e.value)7273Drop sync (#544)Tom Christiebefore adoption206c537
lines 74–75why, one step back74@pytest.mark.asyncio75async def test_multipart_file_tuple():Rename Client to AsyncClient (with compat synonym) (#680)Florimond Mancabefore adoptione284b84
line 76why, one step back76 client = httpx.AsyncClient(dispatch=MockDispatch())Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 77–80why, one step back7778 # Test with a list of values 'data' argument, and a tuple style 'files' argument.79 data = {"text": ["abc"]}80 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}Drop sync (#544)Tom Christiebefore adoption206c537
line 81why, one step back81 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 82–101why, one step back82 assert response.status_code == 2008384 # We're using the cgi module to verify the behavior here, which is a85 # bit grungy, but sufficient just for our testing purposes.86 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]87 content_length = response.request.headers["Content-Length"]88 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}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>"]959697def test_multipart_encode():98 data = {99 "a": "1",100 "b": b"C",101 "c": ["11", "22", "33"],Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 102why, one step back102 "d": "",Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 103–107why, one step back103 }104 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}105106 with mock.patch("os.urandom", return_value=os.urandom(16)):107 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
lines 108–110why, one step back108 stream = encode(data=data, files=files)109 assert stream.content_type == f"multipart/form-data; boundary={boundary}"110 assert stream.body == (Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 111–115why, one step back111 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'112 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'113 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'114 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'115 '--{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 116why, one step back116 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 117–129why, one step back117 '--{0}\r\nContent-Disposition: form-data; name="file";'118 ' filename="name.txt"\r\n'119 "Content-Type: text/plain\r\n\r\n<file content>\r\n"120 "--{0}--\r\n"121 "".format(boundary).encode("ascii")122 )123124125def test_multipart_encode_files_allows_filenames_as_none():126 files = {"file": (None, io.BytesIO(b"<file content>"))}127 with mock.patch("os.urandom", return_value=os.urandom(16)):128 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")129Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 130why, one step back130 stream = encode(data={}, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 131why, one step back131Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
lines 132–133why, one step back132 assert stream.content_type == f"multipart/form-data; boundary={boundary}"133 assert stream.body == (Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 134–135why, one step back134 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'135 "<file content>\r\n--{0}--\r\n"Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 136why, one step back136 "".format(boundary).encode("ascii")Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 137–141why, one step back137 )138139140@pytest.mark.parametrize(141 "file_name,expected_content_type",Minor test fixes (#583)Tom Christiebefore adoption12d00b2
lines 142–146why, one step back142 [143 ("example.json", "application/json"),144 ("example.txt", "text/plain"),145 ("no-extension", "application/octet-stream"),146 ],Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 147–154why, one step back147)148def test_multipart_encode_files_guesses_correct_content_type(149 file_name, expected_content_type150):151 files = {"file": (file_name, io.BytesIO(b"<file content>"))}152 with mock.patch("os.urandom", return_value=os.urandom(16)):153 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")154Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 155why, one step back155 stream = encode(data={}, files=files)Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
line 156why, one step back156Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
lines 157–158why, one step back157 assert stream.content_type == f"multipart/form-data; boundary={boundary}"158 assert stream.body == (Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950
lines 159–162why, one step back159 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '160 f'filename="{file_name}"\r\nContent-Type: '161 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"162 "".encode("ascii")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 163–170why, one step back163 )164165166def test_multipart_encode_files_allows_str_content():167 files = {"file": ("test.txt", "<string content>", "text/plain")}168 with mock.patch("os.urandom", return_value=os.urandom(16)):169 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")170Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 171why, one step back171 stream = encode(data={}, files=files)Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 172why, one step back172Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
lines 173–174why, one step back173 assert stream.content_type == f"multipart/form-data; boundary={boundary}"174 assert stream.body == (Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 175–184why, one step back175 '--{0}\r\nContent-Disposition: form-data; name="file"; '176 'filename="test.txt"\r\n'177 "Content-Type: text/plain\r\n\r\n<string content>\r\n"178 "--{0}--\r\n"179 "".format(boundary).encode("ascii")180 )181182183class TestHeaderParamHTML5Formatting:184 def test_unicode(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 185why, one step back185 param = format_form_param("filename", "n\u00e4me")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 186–188why, one step back186 assert param == b'filename="n\xc3\xa4me"'187188 def test_ascii(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 189why, one step back189 param = format_form_param("filename", b"name")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 190–192why, one step back190 assert param == b'filename="name"'191192 def test_unicode_escape(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 193why, one step back193 param = format_form_param("filename", "hello\\world\u0022")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
lines 194–196why, one step back194 assert param == b'filename="hello\\\\world%22"'195196 def test_unicode_with_control_character(self):Use Streams API for both requests and responses. (#648)Tom Christiebefore adoptioncee1fcc
line 197why, one step back197 param = format_form_param("filename", "hello\x1A\x1B\x1C")Convert debug logs to trace logs (#500)Florimond Mancabefore adoption07586f9
line 198why, one step back198 assert param == b'filename="hello%1A\x1B%1C"'