Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

377 lines · 13.8 KiB · Python

Last changed by

Always rewind files on multipart uploads. (#2065)Tom Christiebefore adoption0088253

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(("key"), (b"abc", 1, 2.3, None))46def test_multipart_invalid_key(key):47    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))4849    data = {key: "abc"}50    files = {"file": io.BytesIO(b"<file content>")}51    with pytest.raises(TypeError) as e:52        client.post(53            "http://127.0.0.1:8000/",54            data=data,55            files=files,56        )57    assert "Invalid type for name" in str(e.value)58    assert repr(key) in str(e.value)596061@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))62def test_multipart_invalid_value(value):63    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))6465    data = {"text": value}66    files = {"file": io.BytesIO(b"<file content>")}67    with pytest.raises(TypeError) as e:68        client.post("http://127.0.0.1:8000/", data=data, files=files)69    assert "Invalid type for value" in str(e.value)707172def test_multipart_file_tuple():73    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))7475    # Test with a list of values 'data' argument,76    #     and a tuple style 'files' argument.77    data = {"text": ["abc"]}78    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}79    response = client.post("http://127.0.0.1:8000/", data=data, files=files)80    assert response.status_code == 2008182    # We're using the cgi module to verify the behavior here, which is a83    # bit grungy, but sufficient just for our testing purposes.84    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]85    content_length = response.request.headers["Content-Length"]86    pdict: dict = {87        "boundary": boundary.encode("ascii"),88        "CONTENT-LENGTH": content_length,89    }90    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9192    # Note that the expected return type for text fields93    # appears to differs from 3.6 to 3.7+94    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]95    assert multipart["file"] == [b"<file content>"]969798@pytest.mark.parametrize("content_type", [None, "text/plain"])99def test_multipart_file_tuple_headers(content_type: typing.Optional[str]):100    file_name = "test.txt"101    expected_content_type = "text/plain"102    headers = {"Expires": "0"}103104    files = {"file": (file_name, io.BytesIO(b"<file content>"), content_type, headers)}105    with mock.patch("os.urandom", return_value=os.urandom(16)):106        boundary = os.urandom(16).hex()107108        headers, stream = encode_request(data={}, files=files)109        assert isinstance(stream, typing.Iterable)110111        content = (112            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '113            f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '114            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"115            "".encode("ascii")116        )117        assert headers == {118            "Content-Type": f"multipart/form-data; boundary={boundary}",119            "Content-Length": str(len(content)),120        }121        assert content == b"".join(stream)122123124def test_multipart_headers_include_content_type() -> None:125    """Content-Type from 4th tuple parameter (headers) should override the 3rd parameter (content_type)"""126    file_name = "test.txt"127    expected_content_type = "image/png"128    headers = {"Content-Type": "image/png"}129130    files = {"file": (file_name, io.BytesIO(b"<file content>"), "text_plain", headers)}131    with mock.patch("os.urandom", return_value=os.urandom(16)):132        boundary = os.urandom(16).hex()133134        headers, stream = encode_request(data={}, files=files)135        assert isinstance(stream, typing.Iterable)136137        content = (138            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '139            f'filename="{file_name}"\r\nContent-Type: '140            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"141            "".encode("ascii")142        )143        assert headers == {144            "Content-Type": f"multipart/form-data; boundary={boundary}",145            "Content-Length": str(len(content)),146        }147        assert content == b"".join(stream)148149150def test_multipart_encode(tmp_path: typing.Any) -> None:151    path = str(tmp_path / "name.txt")152    with open(path, "wb") as f:153        f.write(b"<file content>")154155    data = {156        "a": "1",157        "b": b"C",158        "c": ["11", "22", "33"],159        "d": "",160        "e": True,161        "f": "",162    }163    with open(path, "rb") as input_file:164        files = {"file": ("name.txt", input_file)}165166        with mock.patch("os.urandom", return_value=os.urandom(16)):167            boundary = os.urandom(16).hex()168169            headers, stream = encode_request(data=data, files=files)170            assert isinstance(stream, typing.Iterable)171172            content = (173                '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'174                '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'175                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'176                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'177                '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'178                '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'179                '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'180                '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'181                '--{0}\r\nContent-Disposition: form-data; name="file";'182                ' filename="name.txt"\r\n'183                "Content-Type: text/plain\r\n\r\n<file content>\r\n"184                "--{0}--\r\n"185                "".format(boundary).encode("ascii")186            )187            assert headers == {188                "Content-Type": f"multipart/form-data; boundary={boundary}",189                "Content-Length": str(len(content)),190            }191            assert content == b"".join(stream)192193194def test_multipart_encode_unicode_file_contents() -> None:195    files = {"file": ("name.txt", b"<bytes content>")}196197    with mock.patch("os.urandom", return_value=os.urandom(16)):198        boundary = os.urandom(16).hex()199200        headers, stream = encode_request(files=files)201        assert isinstance(stream, typing.Iterable)202203        content = (204            '--{0}\r\nContent-Disposition: form-data; name="file";'205            ' filename="name.txt"\r\n'206            "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"207            "--{0}--\r\n"208            "".format(boundary).encode("utf-8")209        )210        assert headers == {211            "Content-Type": f"multipart/form-data; boundary={boundary}",212            "Content-Length": str(len(content)),213        }214        assert content == b"".join(stream)215216217def test_multipart_encode_files_allows_filenames_as_none() -> None:218    files = {"file": (None, io.BytesIO(b"<file content>"))}219    with mock.patch("os.urandom", return_value=os.urandom(16)):220        boundary = os.urandom(16).hex()221222        headers, stream = encode_request(data={}, files=files)223        assert isinstance(stream, typing.Iterable)224225        content = (226            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'227            "<file content>\r\n--{0}--\r\n"228            "".format(boundary).encode("ascii")229        )230        assert headers == {231            "Content-Type": f"multipart/form-data; boundary={boundary}",232            "Content-Length": str(len(content)),233        }234        assert content == b"".join(stream)235236237@pytest.mark.parametrize(238    "file_name,expected_content_type",239    [240        ("example.json", "application/json"),241        ("example.txt", "text/plain"),242        ("no-extension", "application/octet-stream"),243    ],244)245def test_multipart_encode_files_guesses_correct_content_type(246    file_name: str, expected_content_type: str247) -> None:248    files = {"file": (file_name, io.BytesIO(b"<file content>"))}249    with mock.patch("os.urandom", return_value=os.urandom(16)):250        boundary = os.urandom(16).hex()251252        headers, stream = encode_request(data={}, files=files)253        assert isinstance(stream, typing.Iterable)254255        content = (256            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '257            f'filename="{file_name}"\r\nContent-Type: '258            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"259            "".encode("ascii")260        )261        assert headers == {262            "Content-Type": f"multipart/form-data; boundary={boundary}",263            "Content-Length": str(len(content)),264        }265        assert content == b"".join(stream)266267268def test_multipart_encode_files_allows_bytes_content() -> None:269    files = {"file": ("test.txt", b"<bytes content>", "text/plain")}270    with mock.patch("os.urandom", return_value=os.urandom(16)):271        boundary = os.urandom(16).hex()272273        headers, stream = encode_request(data={}, files=files)274        assert isinstance(stream, typing.Iterable)275276        content = (277            '--{0}\r\nContent-Disposition: form-data; name="file"; '278            'filename="test.txt"\r\n'279            "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"280            "--{0}--\r\n"281            "".format(boundary).encode("ascii")282        )283        assert headers == {284            "Content-Type": f"multipart/form-data; boundary={boundary}",285            "Content-Length": str(len(content)),286        }287        assert content == b"".join(stream)288289290def test_multipart_encode_files_raises_exception_with_str_content() -> None:291    files = {"file": ("test.txt", "<bytes content>", "text/plain")}292    with mock.patch("os.urandom", return_value=os.urandom(16)):293294        with pytest.raises(TypeError):295            encode_request(data={}, files=files)  # type: ignore296297298def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:299    files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}300    with mock.patch("os.urandom", return_value=os.urandom(16)):301302        with pytest.raises(TypeError):303            encode_request(data={}, files=files)  # type: ignore304305306def test_multipart_encode_non_seekable_filelike() -> None:307    """308    Test that special readable but non-seekable filelike objects are supported,309    at the cost of reading them into memory at most once.310    """311312    class IteratorIO(io.IOBase):313        def __init__(self, iterator: typing.Iterator[bytes]) -> None:314            self._iterator = iterator315316        def read(self, *args: typing.Any) -> bytes:317            return b"".join(self._iterator)318319    def data() -> typing.Iterator[bytes]:320        yield b"Hello"321        yield b"World"322323    fileobj: typing.Any = IteratorIO(data())324    files = {"file": fileobj}325    headers, stream = encode_request(files=files, boundary=b"+++")326    assert isinstance(stream, typing.Iterable)327328    content = (329        b"--+++\r\n"330        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'331        b"Content-Type: application/octet-stream\r\n"332        b"\r\n"333        b"HelloWorld\r\n"334        b"--+++--\r\n"335    )336    assert headers == {337        "Content-Type": "multipart/form-data; boundary=+++",338        "Content-Length": str(len(content)),339    }340    assert content == b"".join(stream)341342343def test_multipart_rewinds_files():344    with tempfile.TemporaryFile() as upload:345        upload.write(b"Hello, world!")346347        transport = httpx.MockTransport(echo_request_content)348        client = httpx.Client(transport=transport)349350        files = {"file": upload}351        response = client.post("http://127.0.0.1:8000/", files=files)352        assert response.status_code == 200353        assert b"\r\nHello, world!\r\n" in response.content354355        # POSTing the same file instance a second time should have the same content.356        files = {"file": upload}357        response = client.post("http://127.0.0.1:8000/", files=files)358        assert response.status_code == 200359        assert b"\r\nHello, world!\r\n" in response.content360361362class TestHeaderParamHTML5Formatting:363    def test_unicode(self):364        param = format_form_param("filename", "n\u00e4me")365        assert param == b'filename="n\xc3\xa4me"'366367    def test_ascii(self):368        param = format_form_param("filename", b"name")369        assert param == b'filename="name"'370371    def test_unicode_escape(self):372        param = format_form_param("filename", "hello\\world\u0022")373        assert param == b'filename="hello\\\\world%22"'374375    def test_unicode_with_control_character(self):376        param = format_form_param("filename", "hello\x1A\x1B\x1C")377        assert param == b'filename="hello%1A\x1B%1C"'