Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

452 lines · 16.2 KiB · Python

Last changed by

Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5

History of this file

Take it

1import io2import os3import tempfile4import typing5from unittest import mock67import pytest89import httpx10from httpx._content import encode_request11from httpx._utils import format_form_param121314def echo_request_content(request: httpx.Request) -> httpx.Response:15    return httpx.Response(200, content=request.content)161718@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))19def test_multipart(value, output):20    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))2122    # Test with a single-value 'data' argument, and a plain file 'files' argument.23    data = {"text": value}24    files = {"file": io.BytesIO(b"<file content>")}25    response = client.post("http://127.0.0.1:8000/", data=data, files=files)26    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]27    boundary_bytes = boundary.encode("ascii")2829    assert response.status_code == 20030    assert response.content == b"".join(31        [32            b"--" + boundary_bytes + b"\r\n",33            b'Content-Disposition: form-data; name="text"\r\n',34            b"\r\n",35            b"abc\r\n",36            b"--" + boundary_bytes + b"\r\n",37            b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',38            b"Content-Type: application/octet-stream\r\n",39            b"\r\n",40            b"<file content>\r\n",41            b"--" + boundary_bytes + b"--\r\n",42        ]43    )444546@pytest.mark.parametrize(47    "header",48    [49        "multipart/form-data; boundary=+++; charset=utf-8",50        "multipart/form-data; charset=utf-8; boundary=+++",51        "multipart/form-data; boundary=+++",52        "multipart/form-data; boundary=+++ ;",53        'multipart/form-data; boundary="+++"; charset=utf-8',54        'multipart/form-data; charset=utf-8; boundary="+++"',55        'multipart/form-data; boundary="+++"',56        'multipart/form-data; boundary="+++" ;',57    ],58)59def test_multipart_explicit_boundary(header: str) -> None:60    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))6162    files = {"file": io.BytesIO(b"<file content>")}63    headers = {"content-type": header}64    response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)65    boundary_bytes = b"+++"6667    assert response.status_code == 20068    assert response.request.headers["Content-Type"] == header69    assert response.content == b"".join(70        [71            b"--" + boundary_bytes + b"\r\n",72            b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',73            b"Content-Type: application/octet-stream\r\n",74            b"\r\n",75            b"<file content>\r\n",76            b"--" + boundary_bytes + b"--\r\n",77        ]78    )798081@pytest.mark.parametrize(82    "header",83    [84        "multipart/form-data; charset=utf-8",85        "multipart/form-data; charset=utf-8; ",86    ],87)88def test_multipart_header_without_boundary(header: str) -> None:89    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))9091    files = {"file": io.BytesIO(b"<file content>")}92    headers = {"content-type": header}93    response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)9495    assert response.status_code == 20096    assert response.request.headers["Content-Type"] == header979899@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))100def test_multipart_invalid_key(key):101    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))102103    data = {key: "abc"}104    files = {"file": io.BytesIO(b"<file content>")}105    with pytest.raises(TypeError) as e:106        client.post(107            "http://127.0.0.1:8000/",108            data=data,109            files=files,110        )111    assert "Invalid type for name" in str(e.value)112    assert repr(key) in str(e.value)113114115@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))116def test_multipart_invalid_value(value):117    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))118119    data = {"text": value}120    files = {"file": io.BytesIO(b"<file content>")}121    with pytest.raises(TypeError) as e:122        client.post("http://127.0.0.1:8000/", data=data, files=files)123    assert "Invalid type for value" in str(e.value)124125126def test_multipart_file_tuple():127    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))128129    # Test with a list of values 'data' argument,130    #     and a tuple style 'files' argument.131    data = {"text": ["abc"]}132    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}133    response = client.post("http://127.0.0.1:8000/", data=data, files=files)134    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]135    boundary_bytes = boundary.encode("ascii")136137    assert response.status_code == 200138    assert response.content == b"".join(139        [140            b"--" + boundary_bytes + b"\r\n",141            b'Content-Disposition: form-data; name="text"\r\n',142            b"\r\n",143            b"abc\r\n",144            b"--" + boundary_bytes + b"\r\n",145            b'Content-Disposition: form-data; name="file"; filename="name.txt"\r\n',146            b"Content-Type: text/plain\r\n",147            b"\r\n",148            b"<file content>\r\n",149            b"--" + boundary_bytes + b"--\r\n",150        ]151    )152153154@pytest.mark.parametrize("content_type", [None, "text/plain"])155def test_multipart_file_tuple_headers(content_type: typing.Optional[str]) -> None:156    file_name = "test.txt"157    expected_content_type = "text/plain"158    headers = {"Expires": "0"}159160    files = {"file": (file_name, io.BytesIO(b"<file content>"), content_type, headers)}161    with mock.patch("os.urandom", return_value=os.urandom(16)):162        boundary = os.urandom(16).hex()163164        headers, stream = encode_request(data={}, files=files)165        assert isinstance(stream, typing.Iterable)166167        content = (168            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '169            f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '170            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"171            "".encode("ascii")172        )173        assert headers == {174            "Content-Type": f"multipart/form-data; boundary={boundary}",175            "Content-Length": str(len(content)),176        }177        assert content == b"".join(stream)178179180def test_multipart_headers_include_content_type() -> None:181    """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""182    file_name = "test.txt"183    expected_content_type = "image/png"184    headers = {"Content-Type": "image/png"}185186    files = {"file": (file_name, io.BytesIO(b"<file content>"), "text_plain", headers)}187    with mock.patch("os.urandom", return_value=os.urandom(16)):188        boundary = os.urandom(16).hex()189190        headers, stream = encode_request(data={}, files=files)191        assert isinstance(stream, typing.Iterable)192193        content = (194            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '195            f'filename="{file_name}"\r\nContent-Type: '196            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"197            "".encode("ascii")198        )199        assert headers == {200            "Content-Type": f"multipart/form-data; boundary={boundary}",201            "Content-Length": str(len(content)),202        }203        assert content == b"".join(stream)204205206def test_multipart_encode(tmp_path: typing.Any) -> None:207    path = str(tmp_path / "name.txt")208    with open(path, "wb") as f:209        f.write(b"<file content>")210211    data = {212        "a": "1",213        "b": b"C",214        "c": ["11", "22", "33"],215        "d": "",216        "e": True,217        "f": "",218    }219    with open(path, "rb") as input_file:220        files = {"file": ("name.txt", input_file)}221222        with mock.patch("os.urandom", return_value=os.urandom(16)):223            boundary = os.urandom(16).hex()224225            headers, stream = encode_request(data=data, files=files)226            assert isinstance(stream, typing.Iterable)227228            content = (229                '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'230                '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'231                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'232                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'233                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'234                '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'235                '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'236                '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'237                '--{0}\r\nContent-Disposition: form-data; name="file";'238                ' filename="name.txt"\r\n'239                "Content-Type: text/plain\r\n\r\n<file content>\r\n"240                "--{0}--\r\n"241                "".format(boundary).encode("ascii")242            )243            assert headers == {244                "Content-Type": f"multipart/form-data; boundary={boundary}",245                "Content-Length": str(len(content)),246            }247            assert content == b"".join(stream)248249250def test_multipart_encode_unicode_file_contents() -> None:251    files = {"file": ("name.txt", b"<bytes content>")}252253    with mock.patch("os.urandom", return_value=os.urandom(16)):254        boundary = os.urandom(16).hex()255256        headers, stream = encode_request(files=files)257        assert isinstance(stream, typing.Iterable)258259        content = (260            '--{0}\r\nContent-Disposition: form-data; name="file";'261            ' filename="name.txt"\r\n'262            "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"263            "--{0}--\r\n"264            "".format(boundary).encode("utf-8")265        )266        assert headers == {267            "Content-Type": f"multipart/form-data; boundary={boundary}",268            "Content-Length": str(len(content)),269        }270        assert content == b"".join(stream)271272273def test_multipart_encode_files_allows_filenames_as_none() -> None:274    files = {"file": (None, io.BytesIO(b"<file content>"))}275    with mock.patch("os.urandom", return_value=os.urandom(16)):276        boundary = os.urandom(16).hex()277278        headers, stream = encode_request(data={}, files=files)279        assert isinstance(stream, typing.Iterable)280281        content = (282            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'283            "<file content>\r\n--{0}--\r\n"284            "".format(boundary).encode("ascii")285        )286        assert headers == {287            "Content-Type": f"multipart/form-data; boundary={boundary}",288            "Content-Length": str(len(content)),289        }290        assert content == b"".join(stream)291292293@pytest.mark.parametrize(294    "file_name,expected_content_type",295    [296        ("example.json", "application/json"),297        ("example.txt", "text/plain"),298        ("no-extension", "application/octet-stream"),299    ],300)301def test_multipart_encode_files_guesses_correct_content_type(302    file_name: str, expected_content_type: str303) -> None:304    files = {"file": (file_name, io.BytesIO(b"<file content>"))}305    with mock.patch("os.urandom", return_value=os.urandom(16)):306        boundary = os.urandom(16).hex()307308        headers, stream = encode_request(data={}, files=files)309        assert isinstance(stream, typing.Iterable)310311        content = (312            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '313            f'filename="{file_name}"\r\nContent-Type: '314            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"315            "".encode("ascii")316        )317        assert headers == {318            "Content-Type": f"multipart/form-data; boundary={boundary}",319            "Content-Length": str(len(content)),320        }321        assert content == b"".join(stream)322323324def test_multipart_encode_files_allows_bytes_content() -> None:325    files = {"file": ("test.txt", b"<bytes content>", "text/plain")}326    with mock.patch("os.urandom", return_value=os.urandom(16)):327        boundary = os.urandom(16).hex()328329        headers, stream = encode_request(data={}, files=files)330        assert isinstance(stream, typing.Iterable)331332        content = (333            '--{0}\r\nContent-Disposition: form-data; name="file"; '334            'filename="test.txt"\r\n'335            "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"336            "--{0}--\r\n"337            "".format(boundary).encode("ascii")338        )339        assert headers == {340            "Content-Type": f"multipart/form-data; boundary={boundary}",341            "Content-Length": str(len(content)),342        }343        assert content == b"".join(stream)344345346def test_multipart_encode_files_allows_str_content() -> None:347    files = {"file": ("test.txt", "<str content>", "text/plain")}348    with mock.patch("os.urandom", return_value=os.urandom(16)):349        boundary = os.urandom(16).hex()350351        headers, stream = encode_request(data={}, files=files)352        assert isinstance(stream, typing.Iterable)353354        content = (355            '--{0}\r\nContent-Disposition: form-data; name="file"; '356            'filename="test.txt"\r\n'357            "Content-Type: text/plain\r\n\r\n<str content>\r\n"358            "--{0}--\r\n"359            "".format(boundary).encode("ascii")360        )361        assert headers == {362            "Content-Type": f"multipart/form-data; boundary={boundary}",363            "Content-Length": str(len(content)),364        }365        assert content == b"".join(stream)366367368def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:369    files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}370    with pytest.raises(TypeError):371        encode_request(data={}, files=files)  # type: ignore372373374def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:375    with tempfile.TemporaryFile(mode="w") as upload:376        files = {"file": ("test.txt", upload, "text/plain")}377        with pytest.raises(TypeError):378            encode_request(data={}, files=files)  # type: ignore379380381def test_multipart_encode_non_seekable_filelike() -> None:382    """383    Test that special readable but non-seekable filelike objects are supported,384    at the cost of reading them into memory at most once.385    """386387    class IteratorIO(io.IOBase):388        def __init__(self, iterator: typing.Iterator[bytes]) -> None:389            self._iterator = iterator390391        def read(self, *args: typing.Any) -> bytes:392            return b"".join(self._iterator)393394    def data() -> typing.Iterator[bytes]:395        yield b"Hello"396        yield b"World"397398    fileobj: typing.Any = IteratorIO(data())399    files = {"file": fileobj}400    headers, stream = encode_request(files=files, boundary=b"+++")401    assert isinstance(stream, typing.Iterable)402403    content = (404        b"--+++\r\n"405        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'406        b"Content-Type: application/octet-stream\r\n"407        b"\r\n"408        b"HelloWorld\r\n"409        b"--+++--\r\n"410    )411    assert headers == {412        "Content-Type": "multipart/form-data; boundary=+++",413        "Content-Length": str(len(content)),414    }415    assert content == b"".join(stream)416417418def test_multipart_rewinds_files():419    with tempfile.TemporaryFile() as upload:420        upload.write(b"Hello, world!")421422        transport = httpx.MockTransport(echo_request_content)423        client = httpx.Client(transport=transport)424425        files = {"file": upload}426        response = client.post("http://127.0.0.1:8000/", files=files)427        assert response.status_code == 200428        assert b"\r\nHello, world!\r\n" in response.content429430        # POSTing the same file instance a second time should have the same content.431        files = {"file": upload}432        response = client.post("http://127.0.0.1:8000/", files=files)433        assert response.status_code == 200434        assert b"\r\nHello, world!\r\n" in response.content435436437class TestHeaderParamHTML5Formatting:438    def test_unicode(self):439        param = format_form_param("filename", "n\u00e4me")440        assert param == b'filename="n\xc3\xa4me"'441442    def test_ascii(self):443        param = format_form_param("filename", b"name")444        assert param == b'filename="name"'445446    def test_unicode_escape(self):447        param = format_form_param("filename", "hello\\world\u0022")448        assert param == b'filename="hello\\\\world%22"'449450    def test_unicode_with_control_character(self):451        param = format_form_param("filename", "hello\x1A\x1B\x1C")452        assert param == b'filename="hello%1A\x1B%1C"'