Multipart data values encoding (#121)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* multipart data values encoding (#119) * Update test_multipart.py
authored by ambrozic · committed by Tom Christie · parent c1044ca · Browse files · 2 files·+69 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+69 added−6 removed
- tests:+60 added−3 removed
- other:+9 added−3 removed
Provenance
- Commit
0e8dae4- Tree
5b00516- Author
ambrozic <ambrozic@users.noreply.github.com>- Committer
Tom Christie <tom@tomchristie.com>- Parent
c1044ca
2 files changed+69 added−6 removed
modified:http3/multipart.py+9 added-3 removed
13 unmodified lines14 raise NotImplementedError() # pragma: nocover15 16 17 class DataField(Field):18- def __init__(self, name: str, value: str) -> None:18+ def __init__(self, name: str, value: typing.Union[str, bytes]) -> None:19+ if not isinstance(name, str):20+ raise TypeError("Invalid type for name. Expected str.")21+ if not isinstance(value, (str, bytes)):22+ raise TypeError("Invalid type for value. Expected str or bytes.")23 self.name = name24 self.value = value25 26 def render_headers(self) -> bytes:2 unmodified lines29 [b'Content-Disposition: form-data; name="', name, b'"\r\n' b"\r\n"]30 )31 32 def render_data(self) -> bytes:29- return self.value.encode("utf-8")33+ return (34+ self.value if isinstance(self.value, bytes) else self.value.encode("utf-8")35+ )36 37 38 class FileField(Field):39 def __init__(38 unmodified lines78 79 80 def iter_fields(data: dict, files: dict) -> typing.Iterator[Field]:81 for name, value in data.items():76- if isinstance(value, list):82+ if isinstance(value, (list, dict)):83 for item in value:84 yield DataField(name=name, value=item)85 else:86 yield DataField(name=name, value=value)20 unmodified linesmodified:tests/test_multipart.py+60 added-3 removed
1+import binascii2 import cgi3 import io4+import os5+from unittest import mock6 7+import pytest8+9 from http3 import (10 CertTypes,11 Client,12 Dispatcher,13+ multipart,14 Request,15 Response,16 TimeoutTypes,17 VerifyTypes,10 unmodified lines28 ) -> Response:29 return Response(200, content=request.read())30 31 32+@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))26-def test_multipart():33+def test_multipart(value, output):34 client = Client(dispatch=MockDispatch())35 36 # Test with a single-value 'data' argument, and a plain file 'files' argument.30- data = {"text": "abc"}37+ data = {"text": value}38 files = {"file": io.BytesIO(b"<file content>")}39 response = client.post("http://127.0.0.1:8000/", data=data, files=files)40 assert response.status_code == 20041 5 unmodified lines47 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)48 49 # Note that the expected return type for text fields50 # appears to differs from 3.6 to 3.7+44- assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]51+ assert multipart["text"] == [output.decode()] or multipart["text"] == [output]52 assert multipart["file"] == [b"<file content>"]53 54 55+@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))56+def test_multipart_invalid_key(key):57+ client = Client(dispatch=MockDispatch())58+ data = {key: "abc"}59+ files = {"file": io.BytesIO(b"<file content>")}60+ with pytest.raises(TypeError) as e:61+ client.post("http://127.0.0.1:8000/", data=data, files=files)62+ assert "Invalid type for name" in str(e.value)63+64+65+@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))66+def test_multipart_invalid_value(value):67+ client = Client(dispatch=MockDispatch())68+ data = {"text": value}69+ files = {"file": io.BytesIO(b"<file content>")}70+ with pytest.raises(TypeError) as e:71+ client.post("http://127.0.0.1:8000/", data=data, files=files)72+ assert "Invalid type for value" in str(e.value)73+74+75 def test_multipart_file_tuple():76 client = Client(dispatch=MockDispatch())77 78 # Test with a list of values 'data' argument, and a tuple style 'files' argument.12 unmodified lines91 # 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>"]95+96+97+def test_multipart_encode():98+ data = {99+ "a": "1",100+ "b": b"C",101+ "c": ["11", "22", "33"],102+ "d": {"ff": ["1", b"2", "3"], "fff": ["11", b"22", "33"]},103+ "f": "",104+ }105+ files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}106+107+ with mock.patch("os.urandom", return_value=os.urandom(16)):108+ boundary = binascii.hexlify(os.urandom(16)).decode("ascii")109+ body, content_type = multipart.multipart_encode(data=data, files=files)110+ assert content_type == f"multipart/form-data; boundary={boundary}"111+ assert body == (112+ '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'113+ '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'114+ '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'115+ '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'116+ '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'117+ '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nff\r\n'118+ '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nfff\r\n'119+ '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'120+ '--{0}\r\nContent-Disposition: form-data; name="file"; filename="name.txt"\r\n'121+ "Content-Type: text/plain\r\n\r\n<file content>\r\n"122+ "--{0}--\r\n"123+ "".format(boundary).encode("ascii")124+ )