Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

294 lines · 10.4 KiB · Python

Last changed by

Handle `data={"key": [None|int|float|bool]}` cases. (#1539)Tom Christiebefore adoptionc26425a

History of this file

Take it

1import cgi2import io3import os4import 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    assert response.status_code == 2002728    # We're using the cgi module to verify the behavior here, which is a29    # bit grungy, but sufficient just for our testing purposes.30    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]31    content_length = response.request.headers["Content-Length"]32    pdict: dict = {33        "boundary": boundary.encode("ascii"),34        "CONTENT-LENGTH": content_length,35    }36    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)3738    # Note that the expected return type for text fields39    # appears to differs from 3.6 to 3.7+40    assert multipart["text"] == [output.decode()] or multipart["text"] == [output]41    assert multipart["file"] == [b"<file content>"]424344@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))45def test_multipart_invalid_key(key):46    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))4748    data = {key: "abc"}49    files = {"file": io.BytesIO(b"<file content>")}50    with pytest.raises(TypeError) as e:51        client.post(52            "http://127.0.0.1:8000/",53            data=data,54            files=files,55        )56    assert "Invalid type for name" in str(e.value)57    assert repr(key) in str(e.value)585960@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))61def test_multipart_invalid_value(value):62    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))6364    data = {"text": value}65    files = {"file": io.BytesIO(b"<file content>")}66    with pytest.raises(TypeError) as e:67        client.post("http://127.0.0.1:8000/", data=data, files=files)68    assert "Invalid type for value" in str(e.value)697071def test_multipart_file_tuple():72    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))7374    # Test with a list of values 'data' argument,75    #     and a tuple style 'files' argument.76    data = {"text": ["abc"]}77    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}78    response = client.post("http://127.0.0.1:8000/", data=data, files=files)79    assert response.status_code == 2008081    # We're using the cgi module to verify the behavior here, which is a82    # bit grungy, but sufficient just for our testing purposes.83    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]84    content_length = response.request.headers["Content-Length"]85    pdict: dict = {86        "boundary": boundary.encode("ascii"),87        "CONTENT-LENGTH": content_length,88    }89    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9091    # Note that the expected return type for text fields92    # appears to differs from 3.6 to 3.7+93    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]94    assert multipart["file"] == [b"<file content>"]959697def test_multipart_encode(tmp_path: typing.Any) -> None:98    path = str(tmp_path / "name.txt")99    with open(path, "wb") as f:100        f.write(b"<file content>")101102    data = {103        "a": "1",104        "b": b"C",105        "c": ["11", "22", "33"],106        "d": "",107        "e": True,108        "f": "",109    }110    files = {"file": ("name.txt", open(path, "rb"))}111112    with mock.patch("os.urandom", return_value=os.urandom(16)):113        boundary = os.urandom(16).hex()114115        headers, stream = encode_request(data=data, files=files)116        assert isinstance(stream, typing.Iterable)117118        content = (119            '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'120            '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'121            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'122            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'123            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'124            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'125            '--{0}\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'126            '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'127            '--{0}\r\nContent-Disposition: form-data; name="file";'128            ' filename="name.txt"\r\n'129            "Content-Type: text/plain\r\n\r\n<file content>\r\n"130            "--{0}--\r\n"131            "".format(boundary).encode("ascii")132        )133        assert headers == {134            "Content-Type": f"multipart/form-data; boundary={boundary}",135            "Content-Length": str(len(content)),136        }137        assert content == b"".join(stream)138139140def test_multipart_encode_unicode_file_contents() -> None:141    files = {"file": ("name.txt", "<únicode string>")}142143    with mock.patch("os.urandom", return_value=os.urandom(16)):144        boundary = os.urandom(16).hex()145146        headers, stream = encode_request(files=files)147        assert isinstance(stream, typing.Iterable)148149        content = (150            '--{0}\r\nContent-Disposition: form-data; name="file";'151            ' filename="name.txt"\r\n'152            "Content-Type: text/plain\r\n\r\n<únicode string>\r\n"153            "--{0}--\r\n"154            "".format(boundary).encode("utf-8")155        )156        assert headers == {157            "Content-Type": f"multipart/form-data; boundary={boundary}",158            "Content-Length": str(len(content)),159        }160        assert content == b"".join(stream)161162163def test_multipart_encode_files_allows_filenames_as_none() -> None:164    files = {"file": (None, io.BytesIO(b"<file content>"))}165    with mock.patch("os.urandom", return_value=os.urandom(16)):166        boundary = os.urandom(16).hex()167168        headers, stream = encode_request(data={}, files=files)169        assert isinstance(stream, typing.Iterable)170171        content = (172            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'173            "<file content>\r\n--{0}--\r\n"174            "".format(boundary).encode("ascii")175        )176        assert headers == {177            "Content-Type": f"multipart/form-data; boundary={boundary}",178            "Content-Length": str(len(content)),179        }180        assert content == b"".join(stream)181182183@pytest.mark.parametrize(184    "file_name,expected_content_type",185    [186        ("example.json", "application/json"),187        ("example.txt", "text/plain"),188        ("no-extension", "application/octet-stream"),189    ],190)191def test_multipart_encode_files_guesses_correct_content_type(192    file_name: str, expected_content_type: str193) -> None:194    files = {"file": (file_name, io.BytesIO(b"<file content>"))}195    with mock.patch("os.urandom", return_value=os.urandom(16)):196        boundary = os.urandom(16).hex()197198        headers, stream = encode_request(data={}, files=files)199        assert isinstance(stream, typing.Iterable)200201        content = (202            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '203            f'filename="{file_name}"\r\nContent-Type: '204            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"205            "".encode("ascii")206        )207        assert headers == {208            "Content-Type": f"multipart/form-data; boundary={boundary}",209            "Content-Length": str(len(content)),210        }211        assert content == b"".join(stream)212213214@pytest.mark.parametrize(215    "value, output",216    ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),217)218def test_multipart_encode_files_allows_bytes_or_str_content(219    value: typing.Union[str, bytes], output: str220) -> None:221    files = {"file": ("test.txt", value, "text/plain")}222    with mock.patch("os.urandom", return_value=os.urandom(16)):223        boundary = os.urandom(16).hex()224225        headers, stream = encode_request(data={}, files=files)226        assert isinstance(stream, typing.Iterable)227228        content = (229            '--{0}\r\nContent-Disposition: form-data; name="file"; '230            'filename="test.txt"\r\n'231            "Content-Type: text/plain\r\n\r\n{1}\r\n"232            "--{0}--\r\n"233            "".format(boundary, output).encode("ascii")234        )235        assert headers == {236            "Content-Type": f"multipart/form-data; boundary={boundary}",237            "Content-Length": str(len(content)),238        }239        assert content == b"".join(stream)240241242def test_multipart_encode_non_seekable_filelike() -> None:243    """244    Test that special readable but non-seekable filelike objects are supported,245    at the cost of reading them into memory at most once.246    """247248    class IteratorIO(io.IOBase):249        def __init__(self, iterator: typing.Iterator[bytes]) -> None:250            self._iterator = iterator251252        def read(self, *args: typing.Any) -> bytes:253            return b"".join(self._iterator)254255    def data() -> typing.Iterator[bytes]:256        yield b"Hello"257        yield b"World"258259    fileobj: typing.Any = IteratorIO(data())260    files = {"file": fileobj}261    headers, stream = encode_request(files=files, boundary=b"+++")262    assert isinstance(stream, typing.Iterable)263264    content = (265        b"--+++\r\n"266        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'267        b"Content-Type: application/octet-stream\r\n"268        b"\r\n"269        b"HelloWorld\r\n"270        b"--+++--\r\n"271    )272    assert headers == {273        "Content-Type": "multipart/form-data; boundary=+++",274        "Content-Length": str(len(content)),275    }276    assert content == b"".join(stream)277278279class TestHeaderParamHTML5Formatting:280    def test_unicode(self):281        param = format_form_param("filename", "n\u00e4me")282        assert param == b'filename="n\xc3\xa4me"'283284    def test_ascii(self):285        param = format_form_param("filename", b"name")286        assert param == b'filename="name"'287288    def test_unicode_escape(self):289        param = format_form_param("filename", "hello\\world\u0022")290        assert param == b'filename="hello\\\\world%22"'291292    def test_unicode_with_control_character(self):293        param = format_form_param("filename", "hello\x1A\x1B\x1C")294        assert param == b'filename="hello%1A\x1B%1C"'