Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

200 lines · 7.8 KiB · Python

Last changed by

Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b

History of this file

Take it

1import binascii2import cgi3import io4import os5from unittest import mock67import pytest89import httpx10from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11from httpx.dispatch.base import Dispatcher12from httpx.multipart import _format_param, multipart_encode131415class MockDispatch(Dispatcher):16    async def send(17        self,18        request: httpx.Request,19        verify: VerifyTypes = None,20        cert: CertTypes = None,21        timeout: TimeoutTypes = None,22    ) -> httpx.Response:23        content = await request.read()24        return httpx.Response(200, content=content)252627@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))28@pytest.mark.asyncio29async def test_multipart(value, output):30    client = httpx.Client(dispatch=MockDispatch())3132    # Test with a single-value 'data' argument, and a plain file 'files' argument.33    data = {"text": value}34    files = {"file": io.BytesIO(b"<file content>")}35    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)36    assert response.status_code == 2003738    # We're using the cgi module to verify the behavior here, which is a39    # bit grungy, but sufficient just for our testing purposes.40    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]41    content_length = response.request.headers["Content-Length"]42    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}43    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)4445    # Note that the expected return type for text fields46    # appears to differs from 3.6 to 3.7+47    assert multipart["text"] == [output.decode()] or multipart["text"] == [output]48    assert multipart["file"] == [b"<file content>"]495051@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))52@pytest.mark.asyncio53async def test_multipart_invalid_key(key):54    client = httpx.Client(dispatch=MockDispatch())55    data = {key: "abc"}56    files = {"file": io.BytesIO(b"<file content>")}57    with pytest.raises(TypeError) as e:58        await client.post("http://127.0.0.1:8000/", data=data, files=files)59    assert "Invalid type for name" in str(e.value)606162@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))63@pytest.mark.asyncio64async def test_multipart_invalid_value(value):65    client = httpx.Client(dispatch=MockDispatch())66    data = {"text": value}67    files = {"file": io.BytesIO(b"<file content>")}68    with pytest.raises(TypeError) as e:69        await client.post("http://127.0.0.1:8000/", data=data, files=files)70    assert "Invalid type for value" in str(e.value)717273@pytest.mark.asyncio74async def test_multipart_file_tuple():75    client = httpx.Client(dispatch=MockDispatch())7677    # Test with a list of values 'data' argument, and a tuple style 'files' argument.78    data = {"text": ["abc"]}79    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}80    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)81    assert response.status_code == 2008283    # We're using the cgi module to verify the behavior here, which is a84    # bit grungy, but sufficient just for our testing purposes.85    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]86    content_length = response.request.headers["Content-Length"]87    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}88    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)8990    # Note that the expected return type for text fields91    # appears to differs from 3.6 to 3.7+92    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]93    assert multipart["file"] == [b"<file content>"]949596def test_multipart_encode():97    data = {98        "a": "1",99        "b": b"C",100        "c": ["11", "22", "33"],101        "d": {"ff": ["1", b"2", "3"], "fff": ["11", b"22", "33"]},102        "f": "",103    }104    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}105106    with mock.patch("os.urandom", return_value=os.urandom(16)):107        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")108        body, content_type = multipart_encode(data=data, files=files)109        assert content_type == f"multipart/form-data; boundary={boundary}"110        assert body == (111            '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'112            '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'113            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'114            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'115            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'116            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nff\r\n'117            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nfff\r\n'118            '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'119            '--{0}\r\nContent-Disposition: form-data; name="file";'120            ' 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        )125126127def test_multipart_encode_files_allows_filenames_as_none():128    files = {"file": (None, io.BytesIO(b"<file content>"))}129    with mock.patch("os.urandom", return_value=os.urandom(16)):130        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")131132        body, content_type = multipart_encode(data={}, files=files)133134        assert content_type == f"multipart/form-data; boundary={boundary}"135        assert body == (136            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'137            "<file content>\r\n--{0}--\r\n"138            "".format(boundary).encode("ascii")139        )140141142@pytest.mark.parametrize(143    "file_name,expected_content_type",144    [145        ("example.json", "application/json"),146        ("example.txt", "text/plain"),147        ("no-extension", "application/octet-stream"),148    ],149)150def test_multipart_encode_files_guesses_correct_content_type(151    file_name, expected_content_type152):153    files = {"file": (file_name, io.BytesIO(b"<file content>"))}154    with mock.patch("os.urandom", return_value=os.urandom(16)):155        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")156157        body, content_type = multipart_encode(data={}, files=files)158159        assert content_type == f"multipart/form-data; boundary={boundary}"160        assert body == (161            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '162            f'filename="{file_name}"\r\nContent-Type: '163            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"164            "".encode("ascii")165        )166167168def test_multipart_encode_files_allows_str_content():169    files = {"file": ("test.txt", "<string content>", "text/plain")}170    with mock.patch("os.urandom", return_value=os.urandom(16)):171        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")172173        body, content_type = multipart_encode(data={}, files=files)174175        assert content_type == f"multipart/form-data; boundary={boundary}"176        assert body == (177            '--{0}\r\nContent-Disposition: form-data; name="file"; '178            'filename="test.txt"\r\n'179            "Content-Type: text/plain\r\n\r\n<string content>\r\n"180            "--{0}--\r\n"181            "".format(boundary).encode("ascii")182        )183184185class TestHeaderParamHTML5Formatting:186    def test_unicode(self):187        param = _format_param("filename", "n\u00e4me")188        assert param == b'filename="n\xc3\xa4me"'189190    def test_ascii(self):191        param = _format_param("filename", b"name")192        assert param == b'filename="name"'193194    def test_unicode_escape(self):195        param = _format_param("filename", "hello\\world\u0022")196        assert param == b'filename="hello\\\\world%22"'197198    def test_unicode_with_control_character(self):199        param = _format_param("filename", "hello\x1A\x1B\x1C")200        assert param == b'filename="hello%1A\x1B%1C"'