Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

265 lines · 9.7 KiB · Python

Last changed by

Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100

History of this file

Take it

1import binascii2import cgi3import io4import os5import typing6from unittest import mock78import httpcore9import pytest1011import httpx12from httpx._content_streams import AsyncIteratorStream, encode13from httpx._utils import format_form_param141516class MockTransport(httpcore.AsyncHTTPTransport):17    async def request(18        self,19        method: bytes,20        url: typing.Tuple[bytes, bytes, int, bytes],21        headers: typing.List[typing.Tuple[bytes, bytes]] = None,22        stream: httpcore.AsyncByteStream = None,23        timeout: typing.Dict[str, typing.Optional[float]] = None,24    ) -> typing.Tuple[25        bytes,26        int,27        bytes,28        typing.List[typing.Tuple[bytes, bytes]],29        httpcore.AsyncByteStream,30    ]:31        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    client = httpx.AsyncClient(transport=MockTransport())3940    # Test with a single-value 'data' argument, and a plain file 'files' argument.41    data = {"text": value}42    files = {"file": io.BytesIO(b"<file content>")}43    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)44    assert response.status_code == 2004546    # We're using the cgi module to verify the behavior here, which is a47    # bit grungy, but sufficient just for our testing purposes.48    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]49    content_length = response.request.headers["Content-Length"]50    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}51    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5253    # Note that the expected return type for text fields54    # appears to differs from 3.6 to 3.7+55    assert multipart["text"] == [output.decode()] or multipart["text"] == [output]56    assert multipart["file"] == [b"<file content>"]575859@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))60@pytest.mark.asyncio61async def test_multipart_invalid_key(key):62    client = httpx.AsyncClient(transport=MockTransport())63    data = {key: "abc"}64    files = {"file": io.BytesIO(b"<file content>")}65    with pytest.raises(TypeError) as e:66        await client.post("http://127.0.0.1:8000/", data=data, files=files)67    assert "Invalid type for name" in str(e.value)686970@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))71@pytest.mark.asyncio72async def test_multipart_invalid_value(value):73    client = httpx.AsyncClient(transport=MockTransport())74    data = {"text": value}75    files = {"file": io.BytesIO(b"<file content>")}76    with pytest.raises(TypeError) as e:77        await client.post("http://127.0.0.1:8000/", data=data, files=files)78    assert "Invalid type for value" in str(e.value)798081@pytest.mark.asyncio82async def test_multipart_file_tuple():83    client = httpx.AsyncClient(transport=MockTransport())8485    # Test with a list of values 'data' argument, and a tuple style 'files' argument.86    data = {"text": ["abc"]}87    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}88    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)89    assert response.status_code == 2009091    # We're using the cgi module to verify the behavior here, which is a92    # bit grungy, but sufficient just for our testing purposes.93    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]94    content_length = response.request.headers["Content-Length"]95    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}96    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9798    # Note that the expected return type for text fields99    # appears to differs from 3.6 to 3.7+100    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]101    assert multipart["file"] == [b"<file content>"]102103104def test_multipart_encode(tmp_path: typing.Any) -> None:105    path = str(tmp_path / "name.txt")106    with open(path, "wb") as f:107        f.write(b"<file content>")108109    data = {110        "a": "1",111        "b": b"C",112        "c": ["11", "22", "33"],113        "d": "",114    }115    files = {"file": ("name.txt", open(path, "rb"))}116117    with mock.patch("os.urandom", return_value=os.urandom(16)):118        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")119120        stream = encode(data=data, files=files)121        assert stream.can_replay()122123        assert stream.content_type == f"multipart/form-data; boundary={boundary}"124        content = (125            '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'126            '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'127            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'128            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'129            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'130            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'131            '--{0}\r\nContent-Disposition: form-data; name="file";'132            ' filename="name.txt"\r\n'133            "Content-Type: text/plain\r\n\r\n<file content>\r\n"134            "--{0}--\r\n"135            "".format(boundary).encode("ascii")136        )137        assert stream.get_headers()["Content-Length"] == str(len(content))138        assert b"".join(stream) == content139140141def test_multipart_encode_files_allows_filenames_as_none() -> None:142    files = {"file": (None, io.BytesIO(b"<file content>"))}143    with mock.patch("os.urandom", return_value=os.urandom(16)):144        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")145146        stream = encode(data={}, files=files)147        assert stream.can_replay()148149        assert stream.content_type == f"multipart/form-data; boundary={boundary}"150        assert b"".join(stream) == (151            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'152            "<file content>\r\n--{0}--\r\n"153            "".format(boundary).encode("ascii")154        )155156157@pytest.mark.parametrize(158    "file_name,expected_content_type",159    [160        ("example.json", "application/json"),161        ("example.txt", "text/plain"),162        ("no-extension", "application/octet-stream"),163    ],164)165def test_multipart_encode_files_guesses_correct_content_type(166    file_name: str, expected_content_type: str167) -> None:168    files = {"file": (file_name, io.BytesIO(b"<file content>"))}169    with mock.patch("os.urandom", return_value=os.urandom(16)):170        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")171172        stream = encode(data={}, files=files)173        assert stream.can_replay()174175        assert stream.content_type == f"multipart/form-data; boundary={boundary}"176        assert b"".join(stream) == (177            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '178            f'filename="{file_name}"\r\nContent-Type: '179            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"180            "".encode("ascii")181        )182183184@pytest.mark.parametrize(185    "value, output",186    ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),187)188def test_multipart_encode_files_allows_bytes_or_str_content(189    value: typing.Union[str, bytes], output: str190) -> None:191    files = {"file": ("test.txt", value, "text/plain")}192    with mock.patch("os.urandom", return_value=os.urandom(16)):193        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")194195        stream = encode(data={}, files=files)196        assert stream.can_replay()197198        assert stream.content_type == f"multipart/form-data; boundary={boundary}"199        content = (200            '--{0}\r\nContent-Disposition: form-data; name="file"; '201            'filename="test.txt"\r\n'202            "Content-Type: text/plain\r\n\r\n{1}\r\n"203            "--{0}--\r\n"204            "".format(boundary, output).encode("ascii")205        )206        assert stream.get_headers()["Content-Length"] == str(len(content))207        assert b"".join(stream) == content208209210def test_multipart_encode_non_seekable_filelike() -> None:211    """212    Test that special readable but non-seekable filelike objects are supported,213    at the cost of reading them into memory at most once.214    """215216    class IteratorIO(io.IOBase):217        def __init__(self, iterator: typing.Iterator[bytes]) -> None:218            self._iterator = iterator219220        def seekable(self) -> bool:221            return False222223        def read(self, *args: typing.Any) -> bytes:224            return b"".join(self._iterator)225226    def data() -> typing.Iterator[bytes]:227        yield b"Hello"228        yield b"World"229230    fileobj = IteratorIO(data())231    files = {"file": fileobj}232    stream = encode(files=files, boundary=b"+++")233    assert not stream.can_replay()234235    content = (236        b"--+++\r\n"237        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'238        b"Content-Type: application/octet-stream\r\n"239        b"\r\n"240        b"HelloWorld\r\n"241        b"--+++--\r\n"242    )243    assert stream.get_headers() == {244        "Content-Type": "multipart/form-data; boundary=+++",245        "Content-Length": str(len(content)),246    }247    assert b"".join(stream) == content248249250class TestHeaderParamHTML5Formatting:251    def test_unicode(self):252        param = format_form_param("filename", "n\u00e4me")253        assert param == b'filename="n\xc3\xa4me"'254255    def test_ascii(self):256        param = format_form_param("filename", b"name")257        assert param == b'filename="name"'258259    def test_unicode_escape(self):260        param = format_form_param("filename", "hello\\world\u0022")261        assert param == b'filename="hello\\\\world%22"'262263    def test_unicode_with_control_character(self):264        param = format_form_param("filename", "hello\x1A\x1B\x1C")265        assert param == b'filename="hello%1A\x1B%1C"'