Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

178 lines · 6.8 KiB · Python

Last changed by

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

History of this file

Take 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    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        return Response(200, content=request.read())323334@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))35def test_multipart(value, output):36    client = Client(dispatch=MockDispatch())3738    # Test with a single-value 'data' argument, and a plain file 'files' argument.39    data = {"text": value}40    files = {"file": io.BytesIO(b"<file content>")}41    response = client.post("http://127.0.0.1:8000/", data=data, files=files)42    assert response.status_code == 2004344    # We're using the cgi module to verify the behavior here, which is a45    # bit grungy, but sufficient just for our testing purposes.46    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]47    content_length = response.request.headers["Content-Length"]48    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}49    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5051    # Note that the expected return type for text fields52    # appears to differs from 3.6 to 3.7+53    assert multipart["text"] == [output.decode()] or multipart["text"] == [output]54    assert multipart["file"] == [b"<file content>"]555657@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))58def test_multipart_invalid_key(key):59    client = Client(dispatch=MockDispatch())60    data = {key: "abc"}61    files = {"file": io.BytesIO(b"<file content>")}62    with pytest.raises(TypeError) as e:63        client.post("http://127.0.0.1:8000/", data=data, files=files)64    assert "Invalid type for name" in str(e.value)656667@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))68def test_multipart_invalid_value(value):69    client = Client(dispatch=MockDispatch())70    data = {"text": value}71    files = {"file": io.BytesIO(b"<file content>")}72    with pytest.raises(TypeError) as e:73        client.post("http://127.0.0.1:8000/", data=data, files=files)74    assert "Invalid type for value" in str(e.value)757677def test_multipart_file_tuple():78    client = Client(dispatch=MockDispatch())7980    # Test with a list of values 'data' argument, and a tuple style 'files' argument.81    data = {"text": ["abc"]}82    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}83    response = client.post("http://127.0.0.1:8000/", data=data, files=files)84    assert response.status_code == 2008586    # We're using the cgi module to verify the behavior here, which is a87    # bit grungy, but sufficient just for our testing purposes.88    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]89    content_length = response.request.headers["Content-Length"]90    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}91    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9293    # Note that the expected return type for text fields94    # appears to differs from 3.6 to 3.7+95    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]96    assert multipart["file"] == [b"<file content>"]979899def test_multipart_encode():100    data = {101        "a": "1",102        "b": b"C",103        "c": ["11", "22", "33"],104        "d": {"ff": ["1", b"2", "3"], "fff": ["11", b"22", "33"]},105        "f": "",106    }107    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}108109    with mock.patch("os.urandom", return_value=os.urandom(16)):110        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")111        body, content_type = multipart.multipart_encode(data=data, files=files)112        assert content_type == f"multipart/form-data; boundary={boundary}"113        assert body == (114            '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'115            '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'116            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'117            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'118            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'119            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nff\r\n'120            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nfff\r\n'121            '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'122            '--{0}\r\nContent-Disposition: form-data; name="file";'123            ' filename="name.txt"\r\n'124            "Content-Type: text/plain\r\n\r\n<file content>\r\n"125            "--{0}--\r\n"126            "".format(boundary).encode("ascii")127        )128129130def test_multipart_encode_files_allows_filenames_as_none():131    files = {"file": (None, io.BytesIO(b"<file content>"))}132    with mock.patch("os.urandom", return_value=os.urandom(16)):133        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")134135        body, content_type = multipart.multipart_encode(data={}, files=files)136137        assert content_type == f"multipart/form-data; boundary={boundary}"138        assert body == (139            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n'140            "Content-Type: application/octet-stream\r\n\r\n<file content>\r\n"141            "--{0}--\r\n"142            "".format(boundary).encode("ascii")143        )144145146def test_multipart_encode_files_allows_str_content():147    files = {"file": ("test.txt", "<string content>", "text/plain")}148    with mock.patch("os.urandom", return_value=os.urandom(16)):149        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")150151        body, content_type = multipart.multipart_encode(data={}, files=files)152153        assert content_type == f"multipart/form-data; boundary={boundary}"154        assert body == (155            '--{0}\r\nContent-Disposition: form-data; name="file"; '156            'filename="test.txt"\r\n'157            "Content-Type: text/plain\r\n\r\n<string content>\r\n"158            "--{0}--\r\n"159            "".format(boundary).encode("ascii")160        )161162163class TestHeaderParamHTML5Formatting:164    def test_unicode(self):165        param = multipart._format_param("filename", "n\u00e4me")166        assert param == b'filename="n\xc3\xa4me"'167168    def test_ascii(self):169        param = multipart._format_param("filename", b"name")170        assert param == b'filename="name"'171172    def test_unicode_escape(self):173        param = multipart._format_param("filename", "hello\\world\u0022")174        assert param == b'filename="hello\\\\world%22"'175176    def test_unicode_with_control_character(self):177        param = multipart._format_param("filename", "hello\x1A\x1B\x1C")178        assert param == b'filename="hello%1A\x1B%1C"'