Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

278 lines · 10.2 KiB · Python

Last changed by

Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b

History of this file

Take it

1import cgi2import io3import os4import typing5from unittest import mock67import httpcore8import pytest910import httpx11from httpx._content_streams import AsyncIteratorStream, MultipartStream, encode12from httpx._utils import format_form_param131415class MockTransport(httpcore.AsyncHTTPTransport):16    async def request(17        self,18        method: bytes,19        url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],20        headers: typing.List[typing.Tuple[bytes, bytes]] = None,21        stream: httpcore.AsyncByteStream = None,22        timeout: typing.Mapping[str, typing.Optional[float]] = None,23    ) -> typing.Tuple[24        bytes,25        int,26        bytes,27        typing.List[typing.Tuple[bytes, bytes]],28        httpcore.AsyncByteStream,29    ]:30        assert stream is not None31        content = AsyncIteratorStream(aiterator=(part async for part in stream))32        return b"HTTP/1.1", 200, b"OK", [], content333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio37async def test_multipart(value, output):38    async with httpx.AsyncClient(transport=MockTransport()) as client:39        # Test with a single-value 'data' argument, and a plain file 'files' argument.40        data = {"text": value}41        files = {"file": io.BytesIO(b"<file content>")}42        response = await client.post("http://127.0.0.1:8000/", data=data, files=files)43        assert response.status_code == 2004445        # We're using the cgi module to verify the behavior here, which is a46        # bit grungy, but sufficient just for our testing purposes.47        boundary = response.request.headers["Content-Type"].split("boundary=")[-1]48        content_length = response.request.headers["Content-Length"]49        pdict: dict = {50            "boundary": boundary.encode("ascii"),51            "CONTENT-LENGTH": content_length,52        }53        multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5455        # Note that the expected return type for text fields56        # appears to differs from 3.6 to 3.7+57        assert multipart["text"] == [output.decode()] or multipart["text"] == [output]58        assert multipart["file"] == [b"<file content>"]596061@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))62@pytest.mark.asyncio63async def test_multipart_invalid_key(key):64    async with httpx.AsyncClient(transport=MockTransport()) as client:65        data = {key: "abc"}66        files = {"file": io.BytesIO(b"<file content>")}67        with pytest.raises(TypeError) as e:68            await client.post(69                "http://127.0.0.1:8000/",70                data=data,71                files=files,72            )73        assert "Invalid type for name" in str(e.value)747576@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))77@pytest.mark.asyncio78async def test_multipart_invalid_value(value):79    async with httpx.AsyncClient(transport=MockTransport()) as client:80        data = {"text": value}81        files = {"file": io.BytesIO(b"<file content>")}82        with pytest.raises(TypeError) as e:83            await client.post("http://127.0.0.1:8000/", data=data, files=files)84        assert "Invalid type for value" in str(e.value)858687@pytest.mark.asyncio88async def test_multipart_file_tuple():89    async with httpx.AsyncClient(transport=MockTransport()) as client:90        # Test with a list of values 'data' argument,91        #     and a tuple style 'files' argument.92        data = {"text": ["abc"]}93        files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}94        response = await client.post("http://127.0.0.1:8000/", data=data, files=files)95        assert response.status_code == 2009697        # We're using the cgi module to verify the behavior here, which is a98        # bit grungy, but sufficient just for our testing purposes.99        boundary = response.request.headers["Content-Type"].split("boundary=")[-1]100        content_length = response.request.headers["Content-Length"]101        pdict: dict = {102            "boundary": boundary.encode("ascii"),103            "CONTENT-LENGTH": content_length,104        }105        multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)106107        # Note that the expected return type for text fields108        # appears to differs from 3.6 to 3.7+109        assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]110        assert multipart["file"] == [b"<file content>"]111112113def test_multipart_encode(tmp_path: typing.Any) -> None:114    path = str(tmp_path / "name.txt")115    with open(path, "wb") as f:116        f.write(b"<file content>")117118    data = {119        "a": "1",120        "b": b"C",121        "c": ["11", "22", "33"],122        "d": "",123    }124    files = {"file": ("name.txt", open(path, "rb"))}125126    with mock.patch("os.urandom", return_value=os.urandom(16)):127        boundary = os.urandom(16).hex()128129        stream = encode(data=data, files=files)130        assert isinstance(stream, MultipartStream)131        assert stream.can_replay()132133        assert stream.content_type == f"multipart/form-data; boundary={boundary}"134        content = (135            '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'136            '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'137            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'138            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'139            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'140            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'141            '--{0}\r\nContent-Disposition: form-data; name="file";'142            ' filename="name.txt"\r\n'143            "Content-Type: text/plain\r\n\r\n<file content>\r\n"144            "--{0}--\r\n"145            "".format(boundary).encode("ascii")146        )147        assert stream.get_headers()["Content-Length"] == str(len(content))148        assert b"".join(stream) == content149150151def test_multipart_encode_files_allows_filenames_as_none() -> None:152    files = {"file": (None, io.BytesIO(b"<file content>"))}153    with mock.patch("os.urandom", return_value=os.urandom(16)):154        boundary = os.urandom(16).hex()155156        stream = encode(data={}, files=files)157        assert isinstance(stream, MultipartStream)158        assert stream.can_replay()159160        assert stream.content_type == f"multipart/form-data; boundary={boundary}"161        assert b"".join(stream) == (162            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'163            "<file content>\r\n--{0}--\r\n"164            "".format(boundary).encode("ascii")165        )166167168@pytest.mark.parametrize(169    "file_name,expected_content_type",170    [171        ("example.json", "application/json"),172        ("example.txt", "text/plain"),173        ("no-extension", "application/octet-stream"),174    ],175)176def test_multipart_encode_files_guesses_correct_content_type(177    file_name: str, expected_content_type: str178) -> None:179    files = {"file": (file_name, io.BytesIO(b"<file content>"))}180    with mock.patch("os.urandom", return_value=os.urandom(16)):181        boundary = os.urandom(16).hex()182183        stream = encode(data={}, files=files)184        assert isinstance(stream, MultipartStream)185        assert stream.can_replay()186187        assert stream.content_type == f"multipart/form-data; boundary={boundary}"188        assert b"".join(stream) == (189            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '190            f'filename="{file_name}"\r\nContent-Type: '191            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"192            "".encode("ascii")193        )194195196@pytest.mark.parametrize(197    "value, output",198    ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),199)200def test_multipart_encode_files_allows_bytes_or_str_content(201    value: typing.Union[str, bytes], output: str202) -> None:203    files = {"file": ("test.txt", value, "text/plain")}204    with mock.patch("os.urandom", return_value=os.urandom(16)):205        boundary = os.urandom(16).hex()206207        stream = encode(data={}, files=files)208        assert isinstance(stream, MultipartStream)209        assert stream.can_replay()210211        assert stream.content_type == f"multipart/form-data; boundary={boundary}"212        content = (213            '--{0}\r\nContent-Disposition: form-data; name="file"; '214            'filename="test.txt"\r\n'215            "Content-Type: text/plain\r\n\r\n{1}\r\n"216            "--{0}--\r\n"217            "".format(boundary, output).encode("ascii")218        )219        assert stream.get_headers()["Content-Length"] == str(len(content))220        assert b"".join(stream) == content221222223def test_multipart_encode_non_seekable_filelike() -> None:224    """225    Test that special readable but non-seekable filelike objects are supported,226    at the cost of reading them into memory at most once.227    """228229    class IteratorIO(io.IOBase):230        def __init__(self, iterator: typing.Iterator[bytes]) -> None:231            self._iterator = iterator232233        def seekable(self) -> bool:234            return False235236        def read(self, *args: typing.Any) -> bytes:237            return b"".join(self._iterator)238239    def data() -> typing.Iterator[bytes]:240        yield b"Hello"241        yield b"World"242243    fileobj: typing.Any = IteratorIO(data())244    files = {"file": fileobj}245    stream = encode(files=files, boundary=b"+++")246    assert not stream.can_replay()247248    content = (249        b"--+++\r\n"250        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'251        b"Content-Type: application/octet-stream\r\n"252        b"\r\n"253        b"HelloWorld\r\n"254        b"--+++--\r\n"255    )256    assert stream.get_headers() == {257        "Content-Type": "multipart/form-data; boundary=+++",258        "Content-Length": str(len(content)),259    }260    assert b"".join(stream) == content261262263class TestHeaderParamHTML5Formatting:264    def test_unicode(self):265        param = format_form_param("filename", "n\u00e4me")266        assert param == b'filename="n\xc3\xa4me"'267268    def test_ascii(self):269        param = format_form_param("filename", b"name")270        assert param == b'filename="name"'271272    def test_unicode_escape(self):273        param = format_form_param("filename", "hello\\world\u0022")274        assert param == b'filename="hello\\\\world%22"'275276    def test_unicode_with_control_character(self):277        param = format_form_param("filename", "hello\x1A\x1B\x1C")278        assert param == b'filename="hello%1A\x1B%1C"'