Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

206 lines · 7.8 KiB · Python

Last changed by

Better HTTP/2 defaults. (#584)Tom Christiebefore adoption30229f1

History of this file

Take it

1import binascii2import cgi3import io4import os5from unittest import mock67import pytest89from httpx import (10    CertTypes,11    Client,12    Dispatcher,13    Request,14    Response,15    TimeoutTypes,16    VerifyTypes,17    multipart,18)192021class MockDispatch(Dispatcher):22    async def send(23        self,24        request: Request,25        verify: VerifyTypes = None,26        cert: CertTypes = None,27        timeout: TimeoutTypes = None,28    ) -> Response:29        content = await request.read()30        return Response(200, content=content)313233@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))34@pytest.mark.asyncio35async def 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 = await 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))58@pytest.mark.asyncio59async def test_multipart_invalid_key(key):60    client = Client(dispatch=MockDispatch())61    data = {key: "abc"}62    files = {"file": io.BytesIO(b"<file content>")}63    with pytest.raises(TypeError) as e:64        await client.post("http://127.0.0.1:8000/", data=data, files=files)65    assert "Invalid type for name" in str(e.value)666768@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))69@pytest.mark.asyncio70async def test_multipart_invalid_value(value):71    client = Client(dispatch=MockDispatch())72    data = {"text": value}73    files = {"file": io.BytesIO(b"<file content>")}74    with pytest.raises(TypeError) as e:75        await client.post("http://127.0.0.1:8000/", data=data, files=files)76    assert "Invalid type for value" in str(e.value)777879@pytest.mark.asyncio80async def test_multipart_file_tuple():81    client = Client(dispatch=MockDispatch())8283    # Test with a list of values 'data' argument, and a tuple style 'files' argument.84    data = {"text": ["abc"]}85    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}86    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)87    assert response.status_code == 2008889    # We're using the cgi module to verify the behavior here, which is a90    # bit grungy, but sufficient just for our testing purposes.91    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]92    content_length = response.request.headers["Content-Length"]93    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}94    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9596    # Note that the expected return type for text fields97    # appears to differs from 3.6 to 3.7+98    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]99    assert multipart["file"] == [b"<file content>"]100101102def test_multipart_encode():103    data = {104        "a": "1",105        "b": b"C",106        "c": ["11", "22", "33"],107        "d": {"ff": ["1", b"2", "3"], "fff": ["11", b"22", "33"]},108        "f": "",109    }110    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}111112    with mock.patch("os.urandom", return_value=os.urandom(16)):113        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")114        body, content_type = multipart.multipart_encode(data=data, files=files)115        assert content_type == f"multipart/form-data; boundary={boundary}"116        assert body == (117            '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'118            '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'119            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'120            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'121            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'122            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nff\r\n'123            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nfff\r\n'124            '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'125            '--{0}\r\nContent-Disposition: form-data; name="file";'126            ' filename="name.txt"\r\n'127            "Content-Type: text/plain\r\n\r\n<file content>\r\n"128            "--{0}--\r\n"129            "".format(boundary).encode("ascii")130        )131132133def test_multipart_encode_files_allows_filenames_as_none():134    files = {"file": (None, io.BytesIO(b"<file content>"))}135    with mock.patch("os.urandom", return_value=os.urandom(16)):136        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")137138        body, content_type = multipart.multipart_encode(data={}, files=files)139140        assert content_type == f"multipart/form-data; boundary={boundary}"141        assert body == (142            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'143            "<file content>\r\n--{0}--\r\n"144            "".format(boundary).encode("ascii")145        )146147148@pytest.mark.parametrize(149    "file_name,expected_content_type",150    [151        ("example.json", "application/json"),152        ("example.txt", "text/plain"),153        ("no-extension", "application/octet-stream"),154    ],155)156def test_multipart_encode_files_guesses_correct_content_type(157    file_name, expected_content_type158):159    files = {"file": (file_name, io.BytesIO(b"<file content>"))}160    with mock.patch("os.urandom", return_value=os.urandom(16)):161        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")162163        body, content_type = multipart.multipart_encode(data={}, files=files)164165        assert content_type == f"multipart/form-data; boundary={boundary}"166        assert body == (167            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '168            f'filename="{file_name}"\r\nContent-Type: '169            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"170            "".encode("ascii")171        )172173174def test_multipart_encode_files_allows_str_content():175    files = {"file": ("test.txt", "<string content>", "text/plain")}176    with mock.patch("os.urandom", return_value=os.urandom(16)):177        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")178179        body, content_type = multipart.multipart_encode(data={}, files=files)180181        assert content_type == f"multipart/form-data; boundary={boundary}"182        assert body == (183            '--{0}\r\nContent-Disposition: form-data; name="file"; '184            'filename="test.txt"\r\n'185            "Content-Type: text/plain\r\n\r\n<string content>\r\n"186            "--{0}--\r\n"187            "".format(boundary).encode("ascii")188        )189190191class TestHeaderParamHTML5Formatting:192    def test_unicode(self):193        param = multipart._format_param("filename", "n\u00e4me")194        assert param == b'filename="n\xc3\xa4me"'195196    def test_ascii(self):197        param = multipart._format_param("filename", b"name")198        assert param == b'filename="name"'199200    def test_unicode_escape(self):201        param = multipart._format_param("filename", "hello\\world\u0022")202        assert param == b'filename="hello\\\\world%22"'203204    def test_unicode_with_control_character(self):205        param = multipart._format_param("filename", "hello\x1A\x1B\x1C")206        assert param == b'filename="hello%1A\x1B%1C"'