Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

464 lines · 16.6 KiB · Python

Last changed by

Drop private import of 'encode_request' in test_multipart (#2525)Tom Christiebefore adoption7947b56

History of this file

Take it

1import io2import tempfile3import typing45import pytest67import httpx8910def echo_request_content(request: httpx.Request) -> httpx.Response:11    return httpx.Response(200, content=request.content)121314@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))15def test_multipart(value, output):16    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))1718    # Test with a single-value 'data' argument, and a plain file 'files' argument.19    data = {"text": value}20    files = {"file": io.BytesIO(b"<file content>")}21    response = client.post("http://127.0.0.1:8000/", data=data, files=files)22    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]23    boundary_bytes = boundary.encode("ascii")2425    assert response.status_code == 20026    assert response.content == b"".join(27        [28            b"--" + boundary_bytes + b"\r\n",29            b'Content-Disposition: form-data; name="text"\r\n',30            b"\r\n",31            b"abc\r\n",32            b"--" + boundary_bytes + b"\r\n",33            b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',34            b"Content-Type: application/octet-stream\r\n",35            b"\r\n",36            b"<file content>\r\n",37            b"--" + boundary_bytes + b"--\r\n",38        ]39    )404142@pytest.mark.parametrize(43    "header",44    [45        "multipart/form-data; boundary=+++; charset=utf-8",46        "multipart/form-data; charset=utf-8; boundary=+++",47        "multipart/form-data; boundary=+++",48        "multipart/form-data; boundary=+++ ;",49        'multipart/form-data; boundary="+++"; charset=utf-8',50        'multipart/form-data; charset=utf-8; boundary="+++"',51        'multipart/form-data; boundary="+++"',52        'multipart/form-data; boundary="+++" ;',53    ],54)55def test_multipart_explicit_boundary(header: str) -> None:56    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))5758    files = {"file": io.BytesIO(b"<file content>")}59    headers = {"content-type": header}60    response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)61    boundary_bytes = b"+++"6263    assert response.status_code == 20064    assert response.request.headers["Content-Type"] == header65    assert response.content == b"".join(66        [67            b"--" + boundary_bytes + b"\r\n",68            b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',69            b"Content-Type: application/octet-stream\r\n",70            b"\r\n",71            b"<file content>\r\n",72            b"--" + boundary_bytes + b"--\r\n",73        ]74    )757677@pytest.mark.parametrize(78    "header",79    [80        "multipart/form-data; charset=utf-8",81        "multipart/form-data; charset=utf-8; ",82    ],83)84def test_multipart_header_without_boundary(header: str) -> None:85    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))8687    files = {"file": io.BytesIO(b"<file content>")}88    headers = {"content-type": header}89    response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)9091    assert response.status_code == 20092    assert response.request.headers["Content-Type"] == header939495@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))96def test_multipart_invalid_key(key):97    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))9899    data = {key: "abc"}100    files = {"file": io.BytesIO(b"<file content>")}101    with pytest.raises(TypeError) as e:102        client.post(103            "http://127.0.0.1:8000/",104            data=data,105            files=files,106        )107    assert "Invalid type for name" in str(e.value)108    assert repr(key) in str(e.value)109110111@pytest.mark.parametrize(("value"), (object(), {"key": "value"}))112def test_multipart_invalid_value(value):113    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))114115    data = {"text": value}116    files = {"file": io.BytesIO(b"<file content>")}117    with pytest.raises(TypeError) as e:118        client.post("http://127.0.0.1:8000/", data=data, files=files)119    assert "Invalid type for value" in str(e.value)120121122def test_multipart_file_tuple():123    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))124125    # Test with a list of values 'data' argument,126    #     and a tuple style 'files' argument.127    data = {"text": ["abc"]}128    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}129    response = client.post("http://127.0.0.1:8000/", data=data, files=files)130    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]131    boundary_bytes = boundary.encode("ascii")132133    assert response.status_code == 200134    assert response.content == b"".join(135        [136            b"--" + boundary_bytes + b"\r\n",137            b'Content-Disposition: form-data; name="text"\r\n',138            b"\r\n",139            b"abc\r\n",140            b"--" + boundary_bytes + b"\r\n",141            b'Content-Disposition: form-data; name="file"; filename="name.txt"\r\n',142            b"Content-Type: text/plain\r\n",143            b"\r\n",144            b"<file content>\r\n",145            b"--" + boundary_bytes + b"--\r\n",146        ]147    )148149150@pytest.mark.parametrize("file_content_type", [None, "text/plain"])151def test_multipart_file_tuple_headers(file_content_type: typing.Optional[str]) -> None:152    file_name = "test.txt"153    file_content = io.BytesIO(b"<file content>")154    file_headers = {"Expires": "0"}155156    url = "https://www.example.com/"157    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}158    files = {"file": (file_name, file_content, file_content_type, file_headers)}159160    request = httpx.Request("POST", url, headers=headers, files=files)161    request.read()162163    assert request.headers == {164        "Host": "www.example.com",165        "Content-Type": "multipart/form-data; boundary=BOUNDARY",166        "Content-Length": str(len(request.content)),167    }168    assert request.content == (169        f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '170        f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '171        f"text/plain\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"172        "".encode("ascii")173    )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    file_content = io.BytesIO(b"<file content>")180    file_content_type = "text/plain"181    file_headers = {"Content-Type": "image/png"}182183    url = "https://www.example.com/"184    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}185    files = {"file": (file_name, file_content, file_content_type, file_headers)}186187    request = httpx.Request("POST", url, headers=headers, files=files)188    request.read()189190    assert request.headers == {191        "Host": "www.example.com",192        "Content-Type": "multipart/form-data; boundary=BOUNDARY",193        "Content-Length": str(len(request.content)),194    }195    assert request.content == (196        f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '197        f'filename="{file_name}"\r\nContent-Type: '198        f"image/png\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"199        "".encode("ascii")200    )201202203def test_multipart_encode(tmp_path: typing.Any) -> None:204    path = str(tmp_path / "name.txt")205    with open(path, "wb") as f:206        f.write(b"<file content>")207208    url = "https://www.example.com/"209    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}210    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        request = httpx.Request("POST", url, headers=headers, data=data, files=files)222        request.read()223224        assert request.headers == {225            "Host": "www.example.com",226            "Content-Type": "multipart/form-data; boundary=BOUNDARY",227            "Content-Length": str(len(request.content)),228        }229        assert request.content == (230            '--BOUNDARY\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'231            '--BOUNDARY\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'232            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'233            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'234            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'235            '--BOUNDARY\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'236            '--BOUNDARY\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'237            '--BOUNDARY\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'238            '--BOUNDARY\r\nContent-Disposition: form-data; name="file";'239            ' filename="name.txt"\r\n'240            "Content-Type: text/plain\r\n\r\n<file content>\r\n"241            "--BOUNDARY--\r\n"242            "".encode("ascii")243        )244245246def test_multipart_encode_unicode_file_contents() -> None:247    url = "https://www.example.com/"248    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}249    files = {"file": ("name.txt", b"<bytes content>")}250251    request = httpx.Request("POST", url, headers=headers, files=files)252    request.read()253254    assert request.headers == {255        "Host": "www.example.com",256        "Content-Type": "multipart/form-data; boundary=BOUNDARY",257        "Content-Length": str(len(request.content)),258    }259    assert request.content == (260        b'--BOUNDARY\r\nContent-Disposition: form-data; name="file";'261        b' filename="name.txt"\r\n'262        b"Content-Type: text/plain\r\n\r\n<bytes content>\r\n"263        b"--BOUNDARY--\r\n"264    )265266267def test_multipart_encode_files_allows_filenames_as_none() -> None:268    url = "https://www.example.com/"269    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}270    files = {"file": (None, io.BytesIO(b"<file content>"))}271272    request = httpx.Request("POST", url, headers=headers, data={}, files=files)273    request.read()274275    assert request.headers == {276        "Host": "www.example.com",277        "Content-Type": "multipart/form-data; boundary=BOUNDARY",278        "Content-Length": str(len(request.content)),279    }280    assert request.content == (281        '--BOUNDARY\r\nContent-Disposition: form-data; name="file"\r\n\r\n'282        "<file content>\r\n--BOUNDARY--\r\n"283        "".encode("ascii")284    )285286287@pytest.mark.parametrize(288    "file_name,expected_content_type",289    [290        ("example.json", "application/json"),291        ("example.txt", "text/plain"),292        ("no-extension", "application/octet-stream"),293    ],294)295def test_multipart_encode_files_guesses_correct_content_type(296    file_name: str, expected_content_type: str297) -> None:298    url = "https://www.example.com/"299    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}300    files = {"file": (file_name, io.BytesIO(b"<file content>"))}301302    request = httpx.Request("POST", url, headers=headers, data={}, files=files)303    request.read()304305    assert request.headers == {306        "Host": "www.example.com",307        "Content-Type": "multipart/form-data; boundary=BOUNDARY",308        "Content-Length": str(len(request.content)),309    }310    assert request.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    )316317318def test_multipart_encode_files_allows_bytes_content() -> None:319    url = "https://www.example.com/"320    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}321    files = {"file": ("test.txt", b"<bytes content>", "text/plain")}322323    request = httpx.Request("POST", url, headers=headers, data={}, files=files)324    request.read()325326    assert request.headers == {327        "Host": "www.example.com",328        "Content-Type": "multipart/form-data; boundary=BOUNDARY",329        "Content-Length": str(len(request.content)),330    }331    assert request.content == (332        '--BOUNDARY\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        "--BOUNDARY--\r\n"336        "".encode("ascii")337    )338339340def test_multipart_encode_files_allows_str_content() -> None:341    url = "https://www.example.com/"342    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}343    files = {"file": ("test.txt", "<str content>", "text/plain")}344345    request = httpx.Request("POST", url, headers=headers, data={}, files=files)346    request.read()347348    assert request.headers == {349        "Host": "www.example.com",350        "Content-Type": "multipart/form-data; boundary=BOUNDARY",351        "Content-Length": str(len(request.content)),352    }353    assert request.content == (354        '--BOUNDARY\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        "--BOUNDARY--\r\n"358        "".encode("ascii")359    )360361362def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:363    url = "https://www.example.com"364    files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}365    with pytest.raises(TypeError):366        httpx.Request("POST", url, data={}, files=files)  # type: ignore367368369def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:370    url = "https://www.example.com"371    with tempfile.TemporaryFile(mode="w") as upload:372        files = {"file": ("test.txt", upload, "text/plain")}373        with pytest.raises(TypeError):374            httpx.Request("POST", url, 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    In this case uploads with use 'Transfer-Encoding: chunked', instead of381    a 'Content-Length' header.382    """383384    class IteratorIO(io.IOBase):385        def __init__(self, iterator: typing.Iterator[bytes]) -> None:386            self._iterator = iterator387388        def read(self, *args: typing.Any) -> bytes:389            return b"".join(self._iterator)390391    def data() -> typing.Iterator[bytes]:392        yield b"Hello"393        yield b"World"394395    url = "https://www.example.com/"396    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}397    fileobj: typing.Any = IteratorIO(data())398    files = {"file": fileobj}399400    request = httpx.Request("POST", url, headers=headers, files=files)401    request.read()402403    assert request.headers == {404        "Host": "www.example.com",405        "Content-Type": "multipart/form-data; boundary=BOUNDARY",406        "Transfer-Encoding": "chunked",407    }408    assert request.content == (409        b"--BOUNDARY\r\n"410        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'411        b"Content-Type: application/octet-stream\r\n"412        b"\r\n"413        b"HelloWorld\r\n"414        b"--BOUNDARY--\r\n"415    )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()