test_multipart.py
This file
Path
tests/test_multipart.py
183 lines · 7.0 KiB · Python
Last changed by
Drop sync (#544)Tom Christiebefore adoption206c537
History of this fileTake it
1import binascii2import cgi3import io4import os5from unittest import mock67import pytest89from httpx import (10 CertTypes,11 Client,12 Dispatcher,13 HTTPVersionTypes,14 Request,15 Response,16 TimeoutTypes,17 VerifyTypes,18 multipart,19)202122class MockDispatch(Dispatcher):23 async def send(24 self,25 request: Request,26 verify: VerifyTypes = None,27 cert: CertTypes = None,28 timeout: TimeoutTypes = None,29 http_versions: HTTPVersionTypes = None,30 ) -> Response:31 content = await request.read()32 return Response(200, content=content)333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio37async def test_multipart(value, output):38 client = Client(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 = Client(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 = Client(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 = Client(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():105 data = {106 "a": "1",107 "b": b"C",108 "c": ["11", "22", "33"],109 "d": {"ff": ["1", b"2", "3"], "fff": ["11", b"22", "33"]},110 "f": "",111 }112 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}113114 with mock.patch("os.urandom", return_value=os.urandom(16)):115 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")116 body, content_type = multipart.multipart_encode(data=data, files=files)117 assert content_type == f"multipart/form-data; boundary={boundary}"118 assert body == (119 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'120 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'121 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'122 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'123 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'124 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nff\r\n'125 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nfff\r\n'126 '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="file";'128 ' filename="name.txt"\r\n'129 "Content-Type: text/plain\r\n\r\n<file content>\r\n"130 "--{0}--\r\n"131 "".format(boundary).encode("ascii")132 )133134135def test_multipart_encode_files_allows_filenames_as_none():136 files = {"file": (None, io.BytesIO(b"<file content>"))}137 with mock.patch("os.urandom", return_value=os.urandom(16)):138 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")139140 body, content_type = multipart.multipart_encode(data={}, files=files)141142 assert content_type == f"multipart/form-data; boundary={boundary}"143 assert body == (144 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n'145 "Content-Type: application/octet-stream\r\n\r\n<file content>\r\n"146 "--{0}--\r\n"147 "".format(boundary).encode("ascii")148 )149150151def test_multipart_encode_files_allows_str_content():152 files = {"file": ("test.txt", "<string content>", "text/plain")}153 with mock.patch("os.urandom", return_value=os.urandom(16)):154 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")155156 body, content_type = multipart.multipart_encode(data={}, files=files)157158 assert content_type == f"multipart/form-data; boundary={boundary}"159 assert body == (160 '--{0}\r\nContent-Disposition: form-data; name="file"; '161 'filename="test.txt"\r\n'162 "Content-Type: text/plain\r\n\r\n<string content>\r\n"163 "--{0}--\r\n"164 "".format(boundary).encode("ascii")165 )166167168class TestHeaderParamHTML5Formatting:169 def test_unicode(self):170 param = multipart._format_param("filename", "n\u00e4me")171 assert param == b'filename="n\xc3\xa4me"'172173 def test_ascii(self):174 param = multipart._format_param("filename", b"name")175 assert param == b'filename="name"'176177 def test_unicode_escape(self):178 param = multipart._format_param("filename", "hello\\world\u0022")179 assert param == b'filename="hello\\\\world%22"'180181 def test_unicode_with_control_character(self):182 param = multipart._format_param("filename", "hello\x1A\x1B\x1C")183 assert param == b'filename="hello%1A\x1B%1C"'