Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

198 lines · 7.7 KiB · Python

Last changed by

Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152

History of this file

Take it

1import binascii2import cgi3import io4import os5from unittest import mock67import pytest89import httpx10from httpx._config import CertTypes, TimeoutTypes, VerifyTypes11from httpx._content_streams import encode12from httpx._dispatch.base import AsyncDispatcher13from httpx._utils import format_form_param141516class MockDispatch(AsyncDispatcher):17    async def send(18        self,19        request: httpx.Request,20        verify: VerifyTypes = None,21        cert: CertTypes = None,22        timeout: TimeoutTypes = None,23    ) -> httpx.Response:24        content = b"".join([part async for part in request.stream])25        return httpx.Response(200, content=content, request=request)262728@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))29@pytest.mark.asyncio30async def test_multipart(value, output):31    client = httpx.AsyncClient(dispatch=MockDispatch())3233    # Test with a single-value 'data' argument, and a plain file 'files' argument.34    data = {"text": value}35    files = {"file": io.BytesIO(b"<file content>")}36    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)37    assert response.status_code == 2003839    # We're using the cgi module to verify the behavior here, which is a40    # bit grungy, but sufficient just for our testing purposes.41    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]42    content_length = response.request.headers["Content-Length"]43    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}44    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)4546    # Note that the expected return type for text fields47    # appears to differs from 3.6 to 3.7+48    assert multipart["text"] == [output.decode()] or multipart["text"] == [output]49    assert multipart["file"] == [b"<file content>"]505152@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))53@pytest.mark.asyncio54async def test_multipart_invalid_key(key):55    client = httpx.AsyncClient(dispatch=MockDispatch())56    data = {key: "abc"}57    files = {"file": io.BytesIO(b"<file content>")}58    with pytest.raises(TypeError) as e:59        await client.post("http://127.0.0.1:8000/", data=data, files=files)60    assert "Invalid type for name" in str(e.value)616263@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))64@pytest.mark.asyncio65async def test_multipart_invalid_value(value):66    client = httpx.AsyncClient(dispatch=MockDispatch())67    data = {"text": value}68    files = {"file": io.BytesIO(b"<file content>")}69    with pytest.raises(TypeError) as e:70        await client.post("http://127.0.0.1:8000/", data=data, files=files)71    assert "Invalid type for value" in str(e.value)727374@pytest.mark.asyncio75async def test_multipart_file_tuple():76    client = httpx.AsyncClient(dispatch=MockDispatch())7778    # Test with a list of values 'data' argument, and a tuple style 'files' argument.79    data = {"text": ["abc"]}80    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}81    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)82    assert response.status_code == 2008384    # We're using the cgi module to verify the behavior here, which is a85    # bit grungy, but sufficient just for our testing purposes.86    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]87    content_length = response.request.headers["Content-Length"]88    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}89    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9091    # 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": "",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        stream = encode(data=data, files=files)109        assert stream.content_type == f"multipart/form-data; boundary={boundary}"110        assert stream.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\n\r\n'117            '--{0}\r\nContent-Disposition: form-data; name="file";'118            ' filename="name.txt"\r\n'119            "Content-Type: text/plain\r\n\r\n<file content>\r\n"120            "--{0}--\r\n"121            "".format(boundary).encode("ascii")122        )123124125def test_multipart_encode_files_allows_filenames_as_none():126    files = {"file": (None, io.BytesIO(b"<file content>"))}127    with mock.patch("os.urandom", return_value=os.urandom(16)):128        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")129130        stream = encode(data={}, files=files)131132        assert stream.content_type == f"multipart/form-data; boundary={boundary}"133        assert stream.body == (134            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'135            "<file content>\r\n--{0}--\r\n"136            "".format(boundary).encode("ascii")137        )138139140@pytest.mark.parametrize(141    "file_name,expected_content_type",142    [143        ("example.json", "application/json"),144        ("example.txt", "text/plain"),145        ("no-extension", "application/octet-stream"),146    ],147)148def test_multipart_encode_files_guesses_correct_content_type(149    file_name, expected_content_type150):151    files = {"file": (file_name, io.BytesIO(b"<file content>"))}152    with mock.patch("os.urandom", return_value=os.urandom(16)):153        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")154155        stream = encode(data={}, files=files)156157        assert stream.content_type == f"multipart/form-data; boundary={boundary}"158        assert stream.body == (159            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '160            f'filename="{file_name}"\r\nContent-Type: '161            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"162            "".encode("ascii")163        )164165166def test_multipart_encode_files_allows_str_content():167    files = {"file": ("test.txt", "<string content>", "text/plain")}168    with mock.patch("os.urandom", return_value=os.urandom(16)):169        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")170171        stream = encode(data={}, files=files)172173        assert stream.content_type == f"multipart/form-data; boundary={boundary}"174        assert stream.body == (175            '--{0}\r\nContent-Disposition: form-data; name="file"; '176            'filename="test.txt"\r\n'177            "Content-Type: text/plain\r\n\r\n<string content>\r\n"178            "--{0}--\r\n"179            "".format(boundary).encode("ascii")180        )181182183class TestHeaderParamHTML5Formatting:184    def test_unicode(self):185        param = format_form_param("filename", "n\u00e4me")186        assert param == b'filename="n\xc3\xa4me"'187188    def test_ascii(self):189        param = format_form_param("filename", b"name")190        assert param == b'filename="name"'191192    def test_unicode_escape(self):193        param = format_form_param("filename", "hello\\world\u0022")194        assert param == b'filename="hello\\\\world%22"'195196    def test_unicode_with_control_character(self):197        param = format_form_param("filename", "hello\x1A\x1B\x1C")198        assert param == b'filename="hello%1A\x1B%1C"'