Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

448 lines · 16.4 KiB · Python

Last changed by

Allow str content for multipart upload files (#2400)Tom Christiebefore adoption0ebe925

History of this file

Take it

1import cgi2import io3import os4import tempfile5import typing6from unittest import mock78import pytest910import httpx11from httpx._content import encode_request12from httpx._utils import format_form_param131415def echo_request_content(request: httpx.Request) -> httpx.Response:16    return httpx.Response(200, content=request.content)171819@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))20def test_multipart(value, output):21    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))2223    # Test with a single-value 'data' argument, and a plain file 'files' argument.24    data = {"text": value}25    files = {"file": io.BytesIO(b"<file content>")}26    response = client.post("http://127.0.0.1:8000/", data=data, files=files)27    assert response.status_code == 2002829    # We're using the cgi module to verify the behavior here, which is a30    # bit grungy, but sufficient just for our testing purposes.31    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]32    content_length = response.request.headers["Content-Length"]33    pdict: dict = {34        "boundary": boundary.encode("ascii"),35        "CONTENT-LENGTH": content_length,36    }37    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)3839    # Note that the expected return type for text fields40    # appears to differs from 3.6 to 3.7+41    assert multipart["text"] == [output.decode()] or multipart["text"] == [output]42    assert multipart["file"] == [b"<file content>"]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    assert response.status_code == 2006566    # We're using the cgi module to verify the behavior here, which is a67    # bit grungy, but sufficient just for our testing purposes.68    assert response.request.headers["Content-Type"] == header69    content_length = response.request.headers["Content-Length"]70    pdict: dict = {71        "boundary": b"+++",72        "CONTENT-LENGTH": content_length,73    }74    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)7576    assert multipart["file"] == [b"<file content>"]777879@pytest.mark.parametrize(80    "header",81    [82        "multipart/form-data; charset=utf-8",83        "multipart/form-data; charset=utf-8; ",84    ],85)86def test_multipart_header_without_boundary(header: str) -> None:87    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))8889    files = {"file": io.BytesIO(b"<file content>")}90    headers = {"content-type": header}91    response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)9293    assert response.status_code == 20094    assert response.request.headers["Content-Type"] == header959697@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))98def test_multipart_invalid_key(key):99    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))100101    data = {key: "abc"}102    files = {"file": io.BytesIO(b"<file content>")}103    with pytest.raises(TypeError) as e:104        client.post(105            "http://127.0.0.1:8000/",106            data=data,107            files=files,108        )109    assert "Invalid type for name" in str(e.value)110    assert repr(key) in str(e.value)111112113@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))114def test_multipart_invalid_value(value):115    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))116117    data = {"text": value}118    files = {"file": io.BytesIO(b"<file content>")}119    with pytest.raises(TypeError) as e:120        client.post("http://127.0.0.1:8000/", data=data, files=files)121    assert "Invalid type for value" in str(e.value)122123124def test_multipart_file_tuple():125    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))126127    # Test with a list of values 'data' argument,128    #     and a tuple style 'files' argument.129    data = {"text": ["abc"]}130    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}131    response = client.post("http://127.0.0.1:8000/", data=data, files=files)132    assert response.status_code == 200133134    # We're using the cgi module to verify the behavior here, which is a135    # bit grungy, but sufficient just for our testing purposes.136    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]137    content_length = response.request.headers["Content-Length"]138    pdict: dict = {139        "boundary": boundary.encode("ascii"),140        "CONTENT-LENGTH": content_length,141    }142    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)143144    # Note that the expected return type for text fields145    # appears to differs from 3.6 to 3.7+146    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]147    assert multipart["file"] == [b"<file content>"]148149150@pytest.mark.parametrize("content_type", [None, "text/plain"])151def test_multipart_file_tuple_headers(content_type: typing.Optional[str]):152    file_name = "test.txt"153    expected_content_type = "text/plain"154    headers = {"Expires": "0"}155156    files = {"file": (file_name, io.BytesIO(b"<file content>"), content_type, headers)}157    with mock.patch("os.urandom", return_value=os.urandom(16)):158        boundary = os.urandom(16).hex()159160        headers, stream = encode_request(data={}, files=files)161        assert isinstance(stream, typing.Iterable)162163        content = (164            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '165            f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '166            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"167            "".encode("ascii")168        )169        assert headers == {170            "Content-Type": f"multipart/form-data; boundary={boundary}",171            "Content-Length": str(len(content)),172        }173        assert content == b"".join(stream)174175176def test_multipart_headers_include_content_type() -> None:177    """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""178    file_name = "test.txt"179    expected_content_type = "image/png"180    headers = {"Content-Type": "image/png"}181182    files = {"file": (file_name, io.BytesIO(b"<file content>"), "text_plain", headers)}183    with mock.patch("os.urandom", return_value=os.urandom(16)):184        boundary = os.urandom(16).hex()185186        headers, stream = encode_request(data={}, files=files)187        assert isinstance(stream, typing.Iterable)188189        content = (190            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '191            f'filename="{file_name}"\r\nContent-Type: '192            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"193            "".encode("ascii")194        )195        assert headers == {196            "Content-Type": f"multipart/form-data; boundary={boundary}",197            "Content-Length": str(len(content)),198        }199        assert content == b"".join(stream)200201202def test_multipart_encode(tmp_path: typing.Any) -> None:203    path = str(tmp_path / "name.txt")204    with open(path, "wb") as f:205        f.write(b"<file content>")206207    data = {208        "a": "1",209        "b": b"C",210        "c": ["11", "22", "33"],211        "d": "",212        "e": True,213        "f": "",214    }215    with open(path, "rb") as input_file:216        files = {"file": ("name.txt", input_file)}217218        with mock.patch("os.urandom", return_value=os.urandom(16)):219            boundary = os.urandom(16).hex()220221            headers, stream = encode_request(data=data, files=files)222            assert isinstance(stream, typing.Iterable)223224            content = (225                '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'226                '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'227                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'228                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'229                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'230                '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'231                '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'232                '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'233                '--{0}\r\nContent-Disposition: form-data; name="file";'234                ' filename="name.txt"\r\n'235                "Content-Type: text/plain\r\n\r\n<file content>\r\n"236                "--{0}--\r\n"237                "".format(boundary).encode("ascii")238            )239            assert headers == {240                "Content-Type": f"multipart/form-data; boundary={boundary}",241                "Content-Length": str(len(content)),242            }243            assert content == b"".join(stream)244245246def test_multipart_encode_unicode_file_contents() -> None:247    files = {"file": ("name.txt", b"<bytes content>")}248249    with mock.patch("os.urandom", return_value=os.urandom(16)):250        boundary = os.urandom(16).hex()251252        headers, stream = encode_request(files=files)253        assert isinstance(stream, typing.Iterable)254255        content = (256            '--{0}\r\nContent-Disposition: form-data; name="file";'257            ' filename="name.txt"\r\n'258            "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"259            "--{0}--\r\n"260            "".format(boundary).encode("utf-8")261        )262        assert headers == {263            "Content-Type": f"multipart/form-data; boundary={boundary}",264            "Content-Length": str(len(content)),265        }266        assert content == b"".join(stream)267268269def test_multipart_encode_files_allows_filenames_as_none() -> None:270    files = {"file": (None, io.BytesIO(b"<file content>"))}271    with mock.patch("os.urandom", return_value=os.urandom(16)):272        boundary = os.urandom(16).hex()273274        headers, stream = encode_request(data={}, files=files)275        assert isinstance(stream, typing.Iterable)276277        content = (278            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'279            "<file content>\r\n--{0}--\r\n"280            "".format(boundary).encode("ascii")281        )282        assert headers == {283            "Content-Type": f"multipart/form-data; boundary={boundary}",284            "Content-Length": str(len(content)),285        }286        assert content == b"".join(stream)287288289@pytest.mark.parametrize(290    "file_name,expected_content_type",291    [292        ("example.json", "application/json"),293        ("example.txt", "text/plain"),294        ("no-extension", "application/octet-stream"),295    ],296)297def test_multipart_encode_files_guesses_correct_content_type(298    file_name: str, expected_content_type: str299) -> None:300    files = {"file": (file_name, io.BytesIO(b"<file content>"))}301    with mock.patch("os.urandom", return_value=os.urandom(16)):302        boundary = os.urandom(16).hex()303304        headers, stream = encode_request(data={}, files=files)305        assert isinstance(stream, typing.Iterable)306307        content = (308            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '309            f'filename="{file_name}"\r\nContent-Type: '310            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"311            "".encode("ascii")312        )313        assert headers == {314            "Content-Type": f"multipart/form-data; boundary={boundary}",315            "Content-Length": str(len(content)),316        }317        assert content == b"".join(stream)318319320def test_multipart_encode_files_allows_bytes_content() -> None:321    files = {"file": ("test.txt", b"<bytes content>", "text/plain")}322    with mock.patch("os.urandom", return_value=os.urandom(16)):323        boundary = os.urandom(16).hex()324325        headers, stream = encode_request(data={}, files=files)326        assert isinstance(stream, typing.Iterable)327328        content = (329            '--{0}\r\nContent-Disposition: form-data; name="file"; '330            'filename="test.txt"\r\n'331            "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"332            "--{0}--\r\n"333            "".format(boundary).encode("ascii")334        )335        assert headers == {336            "Content-Type": f"multipart/form-data; boundary={boundary}",337            "Content-Length": str(len(content)),338        }339        assert content == b"".join(stream)340341342def test_multipart_encode_files_allows_str_content() -> None:343    files = {"file": ("test.txt", "<str content>", "text/plain")}344    with mock.patch("os.urandom", return_value=os.urandom(16)):345        boundary = os.urandom(16).hex()346347        headers, stream = encode_request(data={}, files=files)348        assert isinstance(stream, typing.Iterable)349350        content = (351            '--{0}\r\nContent-Disposition: form-data; name="file"; '352            'filename="test.txt"\r\n'353            "Content-Type: text/plain\r\n\r\n<str content>\r\n"354            "--{0}--\r\n"355            "".format(boundary).encode("ascii")356        )357        assert headers == {358            "Content-Type": f"multipart/form-data; boundary={boundary}",359            "Content-Length": str(len(content)),360        }361        assert content == b"".join(stream)362363364def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:365    files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}366    with pytest.raises(TypeError):367        encode_request(data={}, files=files)  # type: ignore368369370def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:371    with tempfile.TemporaryFile(mode="w") as upload:372        files = {"file": ("test.txt", upload, "text/plain")}373        with pytest.raises(TypeError):374            encode_request(data={}, files=files)  # type: ignore375376377def test_multipart_encode_non_seekable_filelike() -> None:378    """379    Test that special readable but non-seekable filelike objects are supported,380    at the cost of reading them into memory at most once.381    """382383    class IteratorIO(io.IOBase):384        def __init__(self, iterator: typing.Iterator[bytes]) -> None:385            self._iterator = iterator386387        def read(self, *args: typing.Any) -> bytes:388            return b"".join(self._iterator)389390    def data() -> typing.Iterator[bytes]:391        yield b"Hello"392        yield b"World"393394    fileobj: typing.Any = IteratorIO(data())395    files = {"file": fileobj}396    headers, stream = encode_request(files=files, boundary=b"+++")397    assert isinstance(stream, typing.Iterable)398399    content = (400        b"--+++\r\n"401        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'402        b"Content-Type: application/octet-stream\r\n"403        b"\r\n"404        b"HelloWorld\r\n"405        b"--+++--\r\n"406    )407    assert headers == {408        "Content-Type": "multipart/form-data; boundary=+++",409        "Content-Length": str(len(content)),410    }411    assert content == b"".join(stream)412413414def test_multipart_rewinds_files():415    with tempfile.TemporaryFile() as upload:416        upload.write(b"Hello, world!")417418        transport = httpx.MockTransport(echo_request_content)419        client = httpx.Client(transport=transport)420421        files = {"file": upload}422        response = client.post("http://127.0.0.1:8000/", files=files)423        assert response.status_code == 200424        assert b"\r\nHello, world!\r\n" in response.content425426        # POSTing the same file instance a second time should have the same content.427        files = {"file": upload}428        response = client.post("http://127.0.0.1:8000/", files=files)429        assert response.status_code == 200430        assert b"\r\nHello, world!\r\n" in response.content431432433class TestHeaderParamHTML5Formatting:434    def test_unicode(self):435        param = format_form_param("filename", "n\u00e4me")436        assert param == b'filename="n\xc3\xa4me"'437438    def test_ascii(self):439        param = format_form_param("filename", b"name")440        assert param == b'filename="name"'441442    def test_unicode_escape(self):443        param = format_form_param("filename", "hello\\world\u0022")444        assert param == b'filename="hello\\\\world%22"'445446    def test_unicode_with_control_character(self):447        param = format_form_param("filename", "hello\x1A\x1B\x1C")448        assert param == b'filename="hello%1A\x1B%1C"'