Skip to content
Myr

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

2 files+69 added−6 removed

modified:http3/multipart.py+9 added-3 removed
13 unmodified lines
14 raise NotImplementedError() # pragma: nocover151617class 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 = value2526 def render_headers(self) -> bytes:
2 unmodified lines
29 [b'Content-Disposition: form-data; name="', name, b'"\r\n' b"\r\n"]30 )3132 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 )363738class FileField(Field):39 def __init__(
38 unmodified lines
787980def 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 lines
modified:tests/test_multipart.py+60 added-3 removed
1import binascii2import cgi3import io4import os5from unittest import mock67import pytest89from http3 import (10 CertTypes,11 Client,12 Dispatcher,13 multipart,14 Request,15 Response,16 TimeoutTypes,17 VerifyTypes,
10 unmodified lines
28 ) -> Response:29 return Response(200, content=request.read())303132@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))26def test_multipart():33def test_multipart(value, output):34 client = Client(dispatch=MockDispatch())3536 # 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 lines
47 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)4849 # 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>"]535455@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))56def 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)636465@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))66def 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)737475def test_multipart_file_tuple():76 client = Client(dispatch=MockDispatch())7778 # Test with a list of values 'data' argument, and a tuple style 'files' argument.
12 unmodified lines
91 # 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"],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>"))}106107 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 )