Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

201 lines · 7.9 KiB · Python

Last changed by

Make 'request' non-optional on responses (#666)Florimond Mancabefore adoption56c8eda

History of this file

Take it

1import binascii2import cgi3import io4import os5from unittest import mock67import pytest89import httpx10from httpx.config import CertTypes, TimeoutTypes, VerifyTypes11from httpx.content_streams import encode12from httpx.dispatch.base import Dispatcher13from httpx.utils import format_form_param141516class MockDispatch(Dispatcher):17    async def send(18        self,19        request: httpx.Request,20        verify: VerifyTypes = None,21        cert: CertTypes = None,22        timeout: TimeoutTypes = None,23    ) -> httpx.Response:24        content = b"".join([part async for part in request.stream])25        return httpx.Response(200, content=content, request=request)262728@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))29@pytest.mark.asyncio30async def test_multipart(value, output):31    client = httpx.Client(dispatch=MockDispatch())3233    # Test with a single-value 'data' argument, and a plain file 'files' argument.34    data = {"text": value}35    files = {"file": io.BytesIO(b"<file content>")}36    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)37    assert response.status_code == 2003839    # We're using the cgi module to verify the behavior here, which is a40    # bit grungy, but sufficient just for our testing purposes.41    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]42    content_length = response.request.headers["Content-Length"]43    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}44    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)4546    # Note that the expected return type for text fields47    # appears to differs from 3.6 to 3.7+48    assert multipart["text"] == [output.decode()] or multipart["text"] == [output]49    assert multipart["file"] == [b"<file content>"]505152@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))53@pytest.mark.asyncio54async def test_multipart_invalid_key(key):55    client = httpx.Client(dispatch=MockDispatch())56    data = {key: "abc"}57    files = {"file": io.BytesIO(b"<file content>")}58    with pytest.raises(TypeError) as e:59        await client.post("http://127.0.0.1:8000/", data=data, files=files)60    assert "Invalid type for name" in str(e.value)616263@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))64@pytest.mark.asyncio65async def test_multipart_invalid_value(value):66    client = httpx.Client(dispatch=MockDispatch())67    data = {"text": value}68    files = {"file": io.BytesIO(b"<file content>")}69    with pytest.raises(TypeError) as e:70        await client.post("http://127.0.0.1:8000/", data=data, files=files)71    assert "Invalid type for value" in str(e.value)727374@pytest.mark.asyncio75async def test_multipart_file_tuple():76    client = httpx.Client(dispatch=MockDispatch())7778    # Test with a list of values 'data' argument, and a tuple style 'files' argument.79    data = {"text": ["abc"]}80    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}81    response = await client.post("http://127.0.0.1:8000/", data=data, files=files)82    assert response.status_code == 2008384    # We're using the cgi module to verify the behavior here, which is a85    # bit grungy, but sufficient just for our testing purposes.86    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]87    content_length = response.request.headers["Content-Length"]88    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}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():98    data = {99        "a": "1",100        "b": b"C",101        "c": ["11", "22", "33"],102        "d": {"ff": ["1", b"2", "3"], "fff": ["11", b"22", "33"]},103        "f": "",104    }105    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}106107    with mock.patch("os.urandom", return_value=os.urandom(16)):108        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")109        stream = encode(data=data, files=files)110        assert stream.content_type == f"multipart/form-data; boundary={boundary}"111        assert stream.body == (112            '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'113            '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'114            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'115            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'116            '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'117            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nff\r\n'118            '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nfff\r\n'119            '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'120            '--{0}\r\nContent-Disposition: form-data; name="file";'121            ' filename="name.txt"\r\n'122            "Content-Type: text/plain\r\n\r\n<file content>\r\n"123            "--{0}--\r\n"124            "".format(boundary).encode("ascii")125        )126127128def test_multipart_encode_files_allows_filenames_as_none():129    files = {"file": (None, io.BytesIO(b"<file content>"))}130    with mock.patch("os.urandom", return_value=os.urandom(16)):131        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")132133        stream = encode(data={}, files=files)134135        assert stream.content_type == f"multipart/form-data; boundary={boundary}"136        assert stream.body == (137            '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'138            "<file content>\r\n--{0}--\r\n"139            "".format(boundary).encode("ascii")140        )141142143@pytest.mark.parametrize(144    "file_name,expected_content_type",145    [146        ("example.json", "application/json"),147        ("example.txt", "text/plain"),148        ("no-extension", "application/octet-stream"),149    ],150)151def test_multipart_encode_files_guesses_correct_content_type(152    file_name, expected_content_type153):154    files = {"file": (file_name, io.BytesIO(b"<file content>"))}155    with mock.patch("os.urandom", return_value=os.urandom(16)):156        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")157158        stream = encode(data={}, files=files)159160        assert stream.content_type == f"multipart/form-data; boundary={boundary}"161        assert stream.body == (162            f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '163            f'filename="{file_name}"\r\nContent-Type: '164            f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"165            "".encode("ascii")166        )167168169def test_multipart_encode_files_allows_str_content():170    files = {"file": ("test.txt", "<string content>", "text/plain")}171    with mock.patch("os.urandom", return_value=os.urandom(16)):172        boundary = binascii.hexlify(os.urandom(16)).decode("ascii")173174        stream = encode(data={}, files=files)175176        assert stream.content_type == f"multipart/form-data; boundary={boundary}"177        assert stream.body == (178            '--{0}\r\nContent-Disposition: form-data; name="file"; '179            'filename="test.txt"\r\n'180            "Content-Type: text/plain\r\n\r\n<string content>\r\n"181            "--{0}--\r\n"182            "".format(boundary).encode("ascii")183        )184185186class TestHeaderParamHTML5Formatting:187    def test_unicode(self):188        param = format_form_param("filename", "n\u00e4me")189        assert param == b'filename="n\xc3\xa4me"'190191    def test_ascii(self):192        param = format_form_param("filename", b"name")193        assert param == b'filename="name"'194195    def test_unicode_escape(self):196        param = format_form_param("filename", "hello\\world\u0022")197        assert param == b'filename="hello\\\\world%22"'198199    def test_unicode_with_control_character(self):200        param = format_form_param("filename", "hello\x1A\x1B\x1C")201        assert param == b'filename="hello%1A\x1B%1C"'