Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

469 lines · 16.7 KiB · Python

Last changed by

Use `__future__.annotations` (#3068)Kar Petrosyanbefore adoption371b6e9

History of this file

Take it

1from __future__ import annotations23import io4import tempfile5import typing67import pytest89import httpx101112def echo_request_content(request: httpx.Request) -> httpx.Response:13    return httpx.Response(200, content=request.content)141516@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))17def test_multipart(value, output):18    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))1920    # Test with a single-value 'data' argument, and a plain file 'files' argument.21    data = {"text": value}22    files = {"file": io.BytesIO(b"<file content>")}23    response = client.post("http://127.0.0.1:8000/", data=data, files=files)24    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]25    boundary_bytes = boundary.encode("ascii")2627    assert response.status_code == 20028    assert response.content == b"".join(29        [30            b"--" + boundary_bytes + b"\r\n",31            b'Content-Disposition: form-data; name="text"\r\n',32            b"\r\n",33            b"abc\r\n",34            b"--" + boundary_bytes + b"\r\n",35            b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',36            b"Content-Type: application/octet-stream\r\n",37            b"\r\n",38            b"<file content>\r\n",39            b"--" + boundary_bytes + b"--\r\n",40        ]41    )424344@pytest.mark.parametrize(45    "header",46    [47        "multipart/form-data; boundary=+++; charset=utf-8",48        "multipart/form-data; charset=utf-8; boundary=+++",49        "multipart/form-data; boundary=+++",50        "multipart/form-data; boundary=+++ ;",51        'multipart/form-data; boundary="+++"; charset=utf-8',52        'multipart/form-data; charset=utf-8; boundary="+++"',53        'multipart/form-data; boundary="+++"',54        'multipart/form-data; boundary="+++" ;',55    ],56)57def test_multipart_explicit_boundary(header: str) -> None:58    client = httpx.Client(transport=httpx.MockTransport(echo_request_content))5960    files = {"file": io.BytesIO(b"<file content>")}61    headers = {"content-type": header}62    response = client.post("http://127.0.0.1:8000/", files=files, headers=headers)63    boundary_bytes = b"+++"6465    assert response.status_code == 20066    assert response.request.headers["Content-Type"] == header67    assert response.content == b"".join(68        [69            b"--" + boundary_bytes + b"\r\n",70            b'Content-Disposition: form-data; name="file"; filename="upload"\r\n',71            b"Content-Type: application/octet-stream\r\n",72            b"\r\n",73            b"<file content>\r\n",74            b"--" + boundary_bytes + b"--\r\n",75        ]76    )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    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]133    boundary_bytes = boundary.encode("ascii")134135    assert response.status_code == 200136    assert response.content == b"".join(137        [138            b"--" + boundary_bytes + b"\r\n",139            b'Content-Disposition: form-data; name="text"\r\n',140            b"\r\n",141            b"abc\r\n",142            b"--" + boundary_bytes + b"\r\n",143            b'Content-Disposition: form-data; name="file"; filename="name.txt"\r\n',144            b"Content-Type: text/plain\r\n",145            b"\r\n",146            b"<file content>\r\n",147            b"--" + boundary_bytes + b"--\r\n",148        ]149    )150151152@pytest.mark.parametrize("file_content_type", [None, "text/plain"])153def test_multipart_file_tuple_headers(file_content_type: str | None) -> None:154    file_name = "test.txt"155    file_content = io.BytesIO(b"<file content>")156    file_headers = {"Expires": "0"}157158    url = "https://www.example.com/"159    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}160    files = {"file": (file_name, file_content, file_content_type, file_headers)}161162    request = httpx.Request("POST", url, headers=headers, files=files)163    request.read()164165    assert request.headers == {166        "Host": "www.example.com",167        "Content-Type": "multipart/form-data; boundary=BOUNDARY",168        "Content-Length": str(len(request.content)),169    }170    assert request.content == (171        f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '172        f'filename="{file_name}"\r\nExpires: 0\r\nContent-Type: '173        f"text/plain\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"174        "".encode("ascii")175    )176177178def test_multipart_headers_include_content_type() -> None:179    """180    Content-Type from 4th tuple parameter (headers) should181    override the 3rd parameter (content_type)182    """183    file_name = "test.txt"184    file_content = io.BytesIO(b"<file content>")185    file_content_type = "text/plain"186    file_headers = {"Content-Type": "image/png"}187188    url = "https://www.example.com/"189    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}190    files = {"file": (file_name, file_content, file_content_type, file_headers)}191192    request = httpx.Request("POST", url, headers=headers, files=files)193    request.read()194195    assert request.headers == {196        "Host": "www.example.com",197        "Content-Type": "multipart/form-data; boundary=BOUNDARY",198        "Content-Length": str(len(request.content)),199    }200    assert request.content == (201        f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '202        f'filename="{file_name}"\r\nContent-Type: '203        f"image/png\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"204        "".encode("ascii")205    )206207208def test_multipart_encode(tmp_path: typing.Any) -> None:209    path = str(tmp_path / "name.txt")210    with open(path, "wb") as f:211        f.write(b"<file content>")212213    url = "https://www.example.com/"214    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}215    data = {216        "a": "1",217        "b": b"C",218        "c": ["11", "22", "33"],219        "d": "",220        "e": True,221        "f": "",222    }223    with open(path, "rb") as input_file:224        files = {"file": ("name.txt", input_file)}225226        request = httpx.Request("POST", url, headers=headers, data=data, files=files)227        request.read()228229        assert request.headers == {230            "Host": "www.example.com",231            "Content-Type": "multipart/form-data; boundary=BOUNDARY",232            "Content-Length": str(len(request.content)),233        }234        assert request.content == (235            '--BOUNDARY\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'236            '--BOUNDARY\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'237            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'238            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'239            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'240            '--BOUNDARY\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'241            '--BOUNDARY\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'242            '--BOUNDARY\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'243            '--BOUNDARY\r\nContent-Disposition: form-data; name="file";'244            ' filename="name.txt"\r\n'245            "Content-Type: text/plain\r\n\r\n<file content>\r\n"246            "--BOUNDARY--\r\n"247            "".encode("ascii")248        )249250251def test_multipart_encode_unicode_file_contents() -> None:252    url = "https://www.example.com/"253    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}254    files = {"file": ("name.txt", b"<bytes content>")}255256    request = httpx.Request("POST", url, headers=headers, files=files)257    request.read()258259    assert request.headers == {260        "Host": "www.example.com",261        "Content-Type": "multipart/form-data; boundary=BOUNDARY",262        "Content-Length": str(len(request.content)),263    }264    assert request.content == (265        b'--BOUNDARY\r\nContent-Disposition: form-data; name="file";'266        b' filename="name.txt"\r\n'267        b"Content-Type: text/plain\r\n\r\n<bytes content>\r\n"268        b"--BOUNDARY--\r\n"269    )270271272def test_multipart_encode_files_allows_filenames_as_none() -> None:273    url = "https://www.example.com/"274    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}275    files = {"file": (None, io.BytesIO(b"<file content>"))}276277    request = httpx.Request("POST", url, headers=headers, data={}, files=files)278    request.read()279280    assert request.headers == {281        "Host": "www.example.com",282        "Content-Type": "multipart/form-data; boundary=BOUNDARY",283        "Content-Length": str(len(request.content)),284    }285    assert request.content == (286        '--BOUNDARY\r\nContent-Disposition: form-data; name="file"\r\n\r\n'287        "<file content>\r\n--BOUNDARY--\r\n"288        "".encode("ascii")289    )290291292@pytest.mark.parametrize(293    "file_name,expected_content_type",294    [295        ("example.json", "application/json"),296        ("example.txt", "text/plain"),297        ("no-extension", "application/octet-stream"),298    ],299)300def test_multipart_encode_files_guesses_correct_content_type(301    file_name: str, expected_content_type: str302) -> None:303    url = "https://www.example.com/"304    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}305    files = {"file": (file_name, io.BytesIO(b"<file content>"))}306307    request = httpx.Request("POST", url, headers=headers, data={}, files=files)308    request.read()309310    assert request.headers == {311        "Host": "www.example.com",312        "Content-Type": "multipart/form-data; boundary=BOUNDARY",313        "Content-Length": str(len(request.content)),314    }315    assert request.content == (316        f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '317        f'filename="{file_name}"\r\nContent-Type: '318        f"{expected_content_type}\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"319        "".encode("ascii")320    )321322323def test_multipart_encode_files_allows_bytes_content() -> None:324    url = "https://www.example.com/"325    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}326    files = {"file": ("test.txt", b"<bytes content>", "text/plain")}327328    request = httpx.Request("POST", url, headers=headers, data={}, files=files)329    request.read()330331    assert request.headers == {332        "Host": "www.example.com",333        "Content-Type": "multipart/form-data; boundary=BOUNDARY",334        "Content-Length": str(len(request.content)),335    }336    assert request.content == (337        '--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '338        'filename="test.txt"\r\n'339        "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"340        "--BOUNDARY--\r\n"341        "".encode("ascii")342    )343344345def test_multipart_encode_files_allows_str_content() -> None:346    url = "https://www.example.com/"347    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}348    files = {"file": ("test.txt", "<str content>", "text/plain")}349350    request = httpx.Request("POST", url, headers=headers, data={}, files=files)351    request.read()352353    assert request.headers == {354        "Host": "www.example.com",355        "Content-Type": "multipart/form-data; boundary=BOUNDARY",356        "Content-Length": str(len(request.content)),357    }358    assert request.content == (359        '--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '360        'filename="test.txt"\r\n'361        "Content-Type: text/plain\r\n\r\n<str content>\r\n"362        "--BOUNDARY--\r\n"363        "".encode("ascii")364    )365366367def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:368    url = "https://www.example.com"369    files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}370    with pytest.raises(TypeError):371        httpx.Request("POST", url, data={}, files=files)  # type: ignore372373374def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:375    url = "https://www.example.com"376    with tempfile.TemporaryFile(mode="w") as upload:377        files = {"file": ("test.txt", upload, "text/plain")}378        with pytest.raises(TypeError):379            httpx.Request("POST", url, data={}, files=files)  # type: ignore380381382def test_multipart_encode_non_seekable_filelike() -> None:383    """384    Test that special readable but non-seekable filelike objects are supported.385    In this case uploads with use 'Transfer-Encoding: chunked', instead of386    a 'Content-Length' header.387    """388389    class IteratorIO(io.IOBase):390        def __init__(self, iterator: typing.Iterator[bytes]) -> None:391            self._iterator = iterator392393        def read(self, *args: typing.Any) -> bytes:394            return b"".join(self._iterator)395396    def data() -> typing.Iterator[bytes]:397        yield b"Hello"398        yield b"World"399400    url = "https://www.example.com/"401    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}402    fileobj: typing.Any = IteratorIO(data())403    files = {"file": fileobj}404405    request = httpx.Request("POST", url, headers=headers, files=files)406    request.read()407408    assert request.headers == {409        "Host": "www.example.com",410        "Content-Type": "multipart/form-data; boundary=BOUNDARY",411        "Transfer-Encoding": "chunked",412    }413    assert request.content == (414        b"--BOUNDARY\r\n"415        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'416        b"Content-Type: application/octet-stream\r\n"417        b"\r\n"418        b"HelloWorld\r\n"419        b"--BOUNDARY--\r\n"420    )421422423def test_multipart_rewinds_files():424    with tempfile.TemporaryFile() as upload:425        upload.write(b"Hello, world!")426427        transport = httpx.MockTransport(echo_request_content)428        client = httpx.Client(transport=transport)429430        files = {"file": upload}431        response = client.post("http://127.0.0.1:8000/", files=files)432        assert response.status_code == 200433        assert b"\r\nHello, world!\r\n" in response.content434435        # POSTing the same file instance a second time should have the same content.436        files = {"file": upload}437        response = client.post("http://127.0.0.1:8000/", files=files)438        assert response.status_code == 200439        assert b"\r\nHello, world!\r\n" in response.content440441442class TestHeaderParamHTML5Formatting:443    def test_unicode(self):444        filename = "n\u00e4me"445        expected = b'filename="n\xc3\xa4me"'446        files = {"upload": (filename, b"<file content>")}447        request = httpx.Request("GET", "https://www.example.com", files=files)448        assert expected in request.read()449450    def test_ascii(self):451        filename = "name"452        expected = b'filename="name"'453        files = {"upload": (filename, b"<file content>")}454        request = httpx.Request("GET", "https://www.example.com", files=files)455        assert expected in request.read()456457    def test_unicode_escape(self):458        filename = "hello\\world\u0022"459        expected = b'filename="hello\\\\world%22"'460        files = {"upload": (filename, b"<file content>")}461        request = httpx.Request("GET", "https://www.example.com", files=files)462        assert expected in request.read()463464    def test_unicode_with_control_character(self):465        filename = "hello\x1A\x1B\x1C"466        expected = b'filename="hello%1A\x1B%1C"'467        files = {"upload": (filename, b"<file content>")}468        request = httpx.Request("GET", "https://www.example.com", files=files)469        assert expected in request.read()