Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

464 lines · 16.8 KiB · Python

Last changed by

Drop private import of 'format_form_param' from tests (#2500)Tom Christiebefore adoptionb82fbe2

History of this file

Take it

1import io2import os3import tempfile4import typing5from unittest import mock67import pytest89import httpx10from httpx._content import encode_request111213def echo_request_content(request: httpx.Request) -> httpx.Response:14    return httpx.Response(200, content=request.content)151617@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))18def test_multipart(value, output):19    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))2021    # Test with a single-value 'data' argument, and a plain file 'files' argument.22    data = {"text": value}23    files = {"file": io.BytesIO(b"<file content>")}24    response = client.post("http://127.0.0.1:8000/", data=data, files=files)25    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]26    boundary_bytes = boundary.encode("ascii")2728    assert response.status_code == 20029    assert response.content == b"".join(30        [31            b"--" + boundary_bytes + b"\r\n",32            b'Content-Disposition: form-data; name="text"\r\n',33            b"\r\n",34            b"abc\r\n",35            b"--" + boundary_bytes + b"\r\n",36            b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',37            b"Content-Type: application/octet-stream\r\n",38            b"\r\n",39            b"<file content>\r\n",40            b"--" + boundary_bytes + b"--\r\n",41        ]42    )434445@pytest.mark.parametrize(46    "header",47    [48        "multipart/form-data; boundary=+++; charset=utf-8",49        "multipart/form-data; charset=utf-8; boundary=+++",50        "multipart/form-data; boundary=+++",51        "multipart/form-data; boundary=+++ ;",52        'multipart/form-data; boundary="+++"; charset=utf-8',53        'multipart/form-data; charset=utf-8; boundary="+++"',54        'multipart/form-data; boundary="+++"',55        'multipart/form-data; boundary="+++" ;',56    ],57)58def test_multipart_explicit_boundary(header: str) -> None:59    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))6061    files = {"file": io.BytesIO(b"<file content>")}62    headers = {"content-type": header}63    response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)64    boundary_bytes = b"+++"6566    assert response.status_code == 20067    assert response.request.headers["Content-Type"] == header68    assert response.content == b"".join(69        [70            b"--" + boundary_bytes + b"\r\n",71            b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',72            b"Content-Type: application/octet-stream\r\n",73            b"\r\n",74            b"<file content>\r\n",75            b"--" + boundary_bytes + b"--\r\n",76        ]77    )787980@pytest.mark.parametrize(81    "header",82    [83        "multipart/form-data; charset=utf-8",84        "multipart/form-data; charset=utf-8; ",85    ],86)87def test_multipart_header_without_boundary(header: str) -> None:88    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))8990    files = {"file": io.BytesIO(b"<file content>")}91    headers = {"content-type": header}92    response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)9394    assert response.status_code == 20095    assert response.request.headers["Content-Type"] == header969798@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))99def test_multipart_invalid_key(key):100    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))101102    data = {key: "abc"}103    files = {"file": io.BytesIO(b"<file content>")}104    with pytest.raises(TypeError) as e:105        client.post(106            "http://127.0.0.1:8000/",107            data=data,108            files=files,109        )110    assert "Invalid type for name" in str(e.value)111    assert repr(key) in str(e.value)112113114@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))115def test_multipart_invalid_value(value):116    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))117118    data = {"text": value}119    files = {"file": io.BytesIO(b"<file content>")}120    with pytest.raises(TypeError) as e:121        client.post("http://127.0.0.1:8000/", data=data, files=files)122    assert "Invalid type for value" in str(e.value)123124125def test_multipart_file_tuple():126    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))127128    # Test with a list of values 'data' argument,129    #     and a tuple style 'files' argument.130    data = {"text": ["abc"]}131    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}132    response = client.post("http://127.0.0.1:8000/", data=data, files=files)133    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]134    boundary_bytes = boundary.encode("ascii")135136    assert response.status_code == 200137    assert response.content == b"".join(138        [139            b"--" + boundary_bytes + b"\r\n",140            b'Content-Disposition: form-data; name="text"\r\n',141            b"\r\n",142            b"abc\r\n",143            b"--" + boundary_bytes + b"\r\n",144            b'Content-Disposition: form-data; name="file"; filename="name.txt"\r\n',145            b"Content-Type: text/plain\r\n",146            b"\r\n",147            b"<file content>\r\n",148            b"--" + boundary_bytes + b"--\r\n",149        ]150    )151152153@pytest.mark.parametrize("content_type", [None, "text/plain"])154def test_multipart_file_tuple_headers(content_type: typing.Optional[str]) -> None:155    file_name = "test.txt"156    expected_content_type = "text/plain"157    headers = {"Expires": "0"}158159    files = {"file": (file_name, io.BytesIO(b"<file content>"), content_type, headers)}160    with mock.patch("os.urandom", return_value=os.urandom(16)):161        boundary = os.urandom(16).hex()162163        headers, stream = encode_request(data={}, files=files)164        assert isinstance(stream, typing.Iterable)165166        content = (167            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '168            f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '169            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"170            "".encode("ascii")171        )172        assert headers == {173            "Content-Type": f"multipart/form-data; boundary={boundary}",174            "Content-Length": str(len(content)),175        }176        assert content == b"".join(stream)177178179def test_multipart_headers_include_content_type() -> None:180    """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""181    file_name = "test.txt"182    expected_content_type = "image/png"183    headers = {"Content-Type": "image/png"}184185    files = {"file": (file_name, io.BytesIO(b"<file content>"), "text_plain", headers)}186    with mock.patch("os.urandom", return_value=os.urandom(16)):187        boundary = os.urandom(16).hex()188189        headers, stream = encode_request(data={}, files=files)190        assert isinstance(stream, typing.Iterable)191192        content = (193            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '194            f'filename="{file_name}"\r\nContent-Type: '195            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"196            "".encode("ascii")197        )198        assert headers == {199            "Content-Type": f"multipart/form-data; boundary={boundary}",200            "Content-Length": str(len(content)),201        }202        assert content == b"".join(stream)203204205def test_multipart_encode(tmp_path: typing.Any) -> None:206    path = str(tmp_path / "name.txt")207    with open(path, "wb") as f:208        f.write(b"<file content>")209210    data = {211        "a": "1",212        "b": b"C",213        "c": ["11", "22", "33"],214        "d": "",215        "e": True,216        "f": "",217    }218    with open(path, "rb") as input_file:219        files = {"file": ("name.txt", input_file)}220221        with mock.patch("os.urandom", return_value=os.urandom(16)):222            boundary = os.urandom(16).hex()223224            headers, stream = encode_request(data=data, files=files)225            assert isinstance(stream, typing.Iterable)226227            content = (228                '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'229                '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'230                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'231                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'232                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'233                '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'234                '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'235                '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'236                '--{0}\r\nContent-Disposition: form-data; name="file";'237                ' filename="name.txt"\r\n'238                "Content-Type: text/plain\r\n\r\n<file content>\r\n"239                "--{0}--\r\n"240                "".format(boundary).encode("ascii")241            )242            assert headers == {243                "Content-Type": f"multipart/form-data; boundary={boundary}",244                "Content-Length": str(len(content)),245            }246            assert content == b"".join(stream)247248249def test_multipart_encode_unicode_file_contents() -> None:250    files = {"file": ("name.txt", b"<bytes content>")}251252    with mock.patch("os.urandom", return_value=os.urandom(16)):253        boundary = os.urandom(16).hex()254255        headers, stream = encode_request(files=files)256        assert isinstance(stream, typing.Iterable)257258        content = (259            '--{0}\r\nContent-Disposition: form-data; name="file";'260            ' filename="name.txt"\r\n'261            "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"262            "--{0}--\r\n"263            "".format(boundary).encode("utf-8")264        )265        assert headers == {266            "Content-Type": f"multipart/form-data; boundary={boundary}",267            "Content-Length": str(len(content)),268        }269        assert content == b"".join(stream)270271272def test_multipart_encode_files_allows_filenames_as_none() -> None:273    files = {"file": (None, io.BytesIO(b"<file content>"))}274    with mock.patch("os.urandom", return_value=os.urandom(16)):275        boundary = os.urandom(16).hex()276277        headers, stream = encode_request(data={}, files=files)278        assert isinstance(stream, typing.Iterable)279280        content = (281            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'282            "<file content>\r\n--{0}--\r\n"283            "".format(boundary).encode("ascii")284        )285        assert headers == {286            "Content-Type": f"multipart/form-data; boundary={boundary}",287            "Content-Length": str(len(content)),288        }289        assert content == b"".join(stream)290291292@pytest.mark.parametrize(293    "file_name,expected_content_type",294    [295        ("example.json", "application/json"),296        ("example.txt", "text/plain"),297        ("no-extension", "application/octet-stream"),298    ],299)300def test_multipart_encode_files_guesses_correct_content_type(301    file_name: str, expected_content_type: str302) -> None:303    files = {"file": (file_name, io.BytesIO(b"<file content>"))}304    with mock.patch("os.urandom", return_value=os.urandom(16)):305        boundary = os.urandom(16).hex()306307        headers, stream = encode_request(data={}, files=files)308        assert isinstance(stream, typing.Iterable)309310        content = (311            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '312            f'filename="{file_name}"\r\nContent-Type: '313            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"314            "".encode("ascii")315        )316        assert headers == {317            "Content-Type": f"multipart/form-data; boundary={boundary}",318            "Content-Length": str(len(content)),319        }320        assert content == b"".join(stream)321322323def test_multipart_encode_files_allows_bytes_content() -> None:324    files = {"file": ("test.txt", b"<bytes content>", "text/plain")}325    with mock.patch("os.urandom", return_value=os.urandom(16)):326        boundary = os.urandom(16).hex()327328        headers, stream = encode_request(data={}, files=files)329        assert isinstance(stream, typing.Iterable)330331        content = (332            '--{0}\r\nContent-Disposition: form-data; name="file"; '333            'filename="test.txt"\r\n'334            "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"335            "--{0}--\r\n"336            "".format(boundary).encode("ascii")337        )338        assert headers == {339            "Content-Type": f"multipart/form-data; boundary={boundary}",340            "Content-Length": str(len(content)),341        }342        assert content == b"".join(stream)343344345def test_multipart_encode_files_allows_str_content() -> None:346    files = {"file": ("test.txt", "<str content>", "text/plain")}347    with mock.patch("os.urandom", return_value=os.urandom(16)):348        boundary = os.urandom(16).hex()349350        headers, stream = encode_request(data={}, files=files)351        assert isinstance(stream, typing.Iterable)352353        content = (354            '--{0}\r\nContent-Disposition: form-data; name="file"; '355            'filename="test.txt"\r\n'356            "Content-Type: text/plain\r\n\r\n<str content>\r\n"357            "--{0}--\r\n"358            "".format(boundary).encode("ascii")359        )360        assert headers == {361            "Content-Type": f"multipart/form-data; boundary={boundary}",362            "Content-Length": str(len(content)),363        }364        assert content == b"".join(stream)365366367def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:368    files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}369    with pytest.raises(TypeError):370        encode_request(data={}, files=files)  # type: ignore371372373def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:374    with tempfile.TemporaryFile(mode="w") as upload:375        files = {"file": ("test.txt", upload, "text/plain")}376        with pytest.raises(TypeError):377            encode_request(data={}, files=files)  # type: ignore378379380def test_multipart_encode_non_seekable_filelike() -> None:381    """382    Test that special readable but non-seekable filelike objects are supported.383    In this case uploads with use 'Transfer-Encoding: chunked', instead of384    a 'Content-Length' header.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        "Transfer-Encoding": "chunked",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        filename = "n\u00e4me"440        expected = b'filename="n\xc3\xa4me"'441        files = {"upload": (filename, b"<file content>")}442        request = httpx.Request("GET", "https://www.example.com", files=files)443        assert expected in request.read()444445    def test_ascii(self):446        filename = "name"447        expected = b'filename="name"'448        files = {"upload": (filename, b"<file content>")}449        request = httpx.Request("GET", "https://www.example.com", files=files)450        assert expected in request.read()451452    def test_unicode_escape(self):453        filename = "hello\\world\u0022"454        expected = b'filename="hello\\\\world%22"'455        files = {"upload": (filename, b"<file content>")}456        request = httpx.Request("GET", "https://www.example.com", files=files)457        assert expected in request.read()458459    def test_unicode_with_control_character(self):460        filename = "hello\x1A\x1B\x1C"461        expected = b'filename="hello%1A\x1B%1C"'462        files = {"upload": (filename, b"<file content>")}463        request = httpx.Request("GET", "https://www.example.com", files=files)464        assert expected in request.read()