Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

467 lines · 16.7 KiB · Python

Last changed by

Ruff linter: Use the default line-length (#2922)T-256before adoptionfd60b18

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    """178    Content-Type from 4th tuple parameter (headers) should179    override the 3rd parameter (content_type)180    """181    file_name = "test.txt"182    file_content = io.BytesIO(b"<file content>")183    file_content_type = "text/plain"184    file_headers = {"Content-Type": "image/png"}185186    url = "https://www.example.com/"187    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}188    files = {"file": (file_name, file_content, file_content_type, file_headers)}189190    request = httpx.Request("POST", url, headers=headers, files=files)191    request.read()192193    assert request.headers == {194        "Host": "www.example.com",195        "Content-Type": "multipart/form-data; boundary=BOUNDARY",196        "Content-Length": str(len(request.content)),197    }198    assert request.content == (199        f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '200        f'filename="{file_name}"\r\nContent-Type: '201        f"image/png\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"202        "".encode("ascii")203    )204205206def test_multipart_encode(tmp_path: typing.Any) -> None:207    path = str(tmp_path / "name.txt")208    with open(path, "wb") as f:209        f.write(b"<file content>")210211    url = "https://www.example.com/"212    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}213    data = {214        "a": "1",215        "b": b"C",216        "c": ["11", "22", "33"],217        "d": "",218        "e": True,219        "f": "",220    }221    with open(path, "rb") as input_file:222        files = {"file": ("name.txt", input_file)}223224        request = httpx.Request("POST", url, headers=headers, data=data, files=files)225        request.read()226227        assert request.headers == {228            "Host": "www.example.com",229            "Content-Type": "multipart/form-data; boundary=BOUNDARY",230            "Content-Length": str(len(request.content)),231        }232        assert request.content == (233            '--BOUNDARY\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'234            '--BOUNDARY\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'235            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'236            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'237            '--BOUNDARY\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'238            '--BOUNDARY\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'239            '--BOUNDARY\r\nContent-Disposition: form-data; name="e"\r\n\r\ntrue\r\n'240            '--BOUNDARY\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'241            '--BOUNDARY\r\nContent-Disposition: form-data; name="file";'242            ' filename="name.txt"\r\n'243            "Content-Type: text/plain\r\n\r\n<file content>\r\n"244            "--BOUNDARY--\r\n"245            "".encode("ascii")246        )247248249def test_multipart_encode_unicode_file_contents() -> None:250    url = "https://www.example.com/"251    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}252    files = {"file": ("name.txt", b"<bytes content>")}253254    request = httpx.Request("POST", url, headers=headers, files=files)255    request.read()256257    assert request.headers == {258        "Host": "www.example.com",259        "Content-Type": "multipart/form-data; boundary=BOUNDARY",260        "Content-Length": str(len(request.content)),261    }262    assert request.content == (263        b'--BOUNDARY\r\nContent-Disposition: form-data; name="file";'264        b' filename="name.txt"\r\n'265        b"Content-Type: text/plain\r\n\r\n<bytes content>\r\n"266        b"--BOUNDARY--\r\n"267    )268269270def test_multipart_encode_files_allows_filenames_as_none() -> None:271    url = "https://www.example.com/"272    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}273    files = {"file": (None, io.BytesIO(b"<file content>"))}274275    request = httpx.Request("POST", url, headers=headers, data={}, files=files)276    request.read()277278    assert request.headers == {279        "Host": "www.example.com",280        "Content-Type": "multipart/form-data; boundary=BOUNDARY",281        "Content-Length": str(len(request.content)),282    }283    assert request.content == (284        '--BOUNDARY\r\nContent-Disposition: form-data; name="file"\r\n\r\n'285        "<file content>\r\n--BOUNDARY--\r\n"286        "".encode("ascii")287    )288289290@pytest.mark.parametrize(291    "file_name,expected_content_type",292    [293        ("example.json", "application/json"),294        ("example.txt", "text/plain"),295        ("no-extension", "application/octet-stream"),296    ],297)298def test_multipart_encode_files_guesses_correct_content_type(299    file_name: str, expected_content_type: str300) -> None:301    url = "https://www.example.com/"302    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}303    files = {"file": (file_name, io.BytesIO(b"<file content>"))}304305    request = httpx.Request("POST", url, headers=headers, data={}, files=files)306    request.read()307308    assert request.headers == {309        "Host": "www.example.com",310        "Content-Type": "multipart/form-data; boundary=BOUNDARY",311        "Content-Length": str(len(request.content)),312    }313    assert request.content == (314        f'--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '315        f'filename="{file_name}"\r\nContent-Type: '316        f"{expected_content_type}\r\n\r\n<file content>\r\n--BOUNDARY--\r\n"317        "".encode("ascii")318    )319320321def test_multipart_encode_files_allows_bytes_content() -> None:322    url = "https://www.example.com/"323    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}324    files = {"file": ("test.txt", b"<bytes content>", "text/plain")}325326    request = httpx.Request("POST", url, headers=headers, data={}, files=files)327    request.read()328329    assert request.headers == {330        "Host": "www.example.com",331        "Content-Type": "multipart/form-data; boundary=BOUNDARY",332        "Content-Length": str(len(request.content)),333    }334    assert request.content == (335        '--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '336        'filename="test.txt"\r\n'337        "Content-Type: text/plain\r\n\r\n<bytes content>\r\n"338        "--BOUNDARY--\r\n"339        "".encode("ascii")340    )341342343def test_multipart_encode_files_allows_str_content() -> None:344    url = "https://www.example.com/"345    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}346    files = {"file": ("test.txt", "<str content>", "text/plain")}347348    request = httpx.Request("POST", url, headers=headers, data={}, files=files)349    request.read()350351    assert request.headers == {352        "Host": "www.example.com",353        "Content-Type": "multipart/form-data; boundary=BOUNDARY",354        "Content-Length": str(len(request.content)),355    }356    assert request.content == (357        '--BOUNDARY\r\nContent-Disposition: form-data; name="file"; '358        'filename="test.txt"\r\n'359        "Content-Type: text/plain\r\n\r\n<str content>\r\n"360        "--BOUNDARY--\r\n"361        "".encode("ascii")362    )363364365def test_multipart_encode_files_raises_exception_with_StringIO_content() -> None:366    url = "https://www.example.com"367    files = {"file": ("test.txt", io.StringIO("content"), "text/plain")}368    with pytest.raises(TypeError):369        httpx.Request("POST", url, data={}, files=files)  # type: ignore370371372def test_multipart_encode_files_raises_exception_with_text_mode_file() -> None:373    url = "https://www.example.com"374    with tempfile.TemporaryFile(mode="w") as upload:375        files = {"file": ("test.txt", upload, "text/plain")}376        with pytest.raises(TypeError):377            httpx.Request("POST", url, data={}, files=files)  # type: ignore378379380def test_multipart_encode_non_seekable_filelike() -> None:381    """382    Test that special readable but non-seekable filelike objects are supported.383    In this case uploads with use 'Transfer-Encoding: chunked', instead of384    a 'Content-Length' header.385    """386387    class IteratorIO(io.IOBase):388        def __init__(self, iterator: typing.Iterator[bytes]) -> None:389            self._iterator = iterator390391        def read(self, *args: typing.Any) -> bytes:392            return b"".join(self._iterator)393394    def data() -> typing.Iterator[bytes]:395        yield b"Hello"396        yield b"World"397398    url = "https://www.example.com/"399    headers = {"Content-Type": "multipart/form-data; boundary=BOUNDARY"}400    fileobj: typing.Any = IteratorIO(data())401    files = {"file": fileobj}402403    request = httpx.Request("POST", url, headers=headers, files=files)404    request.read()405406    assert request.headers == {407        "Host": "www.example.com",408        "Content-Type": "multipart/form-data; boundary=BOUNDARY",409        "Transfer-Encoding": "chunked",410    }411    assert request.content == (412        b"--BOUNDARY\r\n"413        b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'414        b"Content-Type: application/octet-stream\r\n"415        b"\r\n"416        b"HelloWorld\r\n"417        b"--BOUNDARY--\r\n"418    )419420421def test_multipart_rewinds_files():422    with tempfile.TemporaryFile() as upload:423        upload.write(b"Hello, world!")424425        transport = httpx.MockTransport(echo_request_content)426        client = httpx.Client(transport=transport)427428        files = {"file": upload}429        response = client.post("http://127.0.0.1:8000/", files=files)430        assert response.status_code == 200431        assert b"\r\nHello, world!\r\n" in response.content432433        # POSTing the same file instance a second time should have the same content.434        files = {"file": upload}435        response = client.post("http://127.0.0.1:8000/", files=files)436        assert response.status_code == 200437        assert b"\r\nHello, world!\r\n" in response.content438439440class TestHeaderParamHTML5Formatting:441    def test_unicode(self):442        filename = "n\u00e4me"443        expected = b'filename="n\xc3\xa4me"'444        files = {"upload": (filename, b"<file content>")}445        request = httpx.Request("GET", "https://www.example.com", files=files)446        assert expected in request.read()447448    def test_ascii(self):449        filename = "name"450        expected = b'filename="name"'451        files = {"upload": (filename, b"<file content>")}452        request = httpx.Request("GET", "https://www.example.com", files=files)453        assert expected in request.read()454455    def test_unicode_escape(self):456        filename = "hello\\world\u0022"457        expected = b'filename="hello\\\\world%22"'458        files = {"upload": (filename, b"<file content>")}459        request = httpx.Request("GET", "https://www.example.com", files=files)460        assert expected in request.read()461462    def test_unicode_with_control_character(self):463        filename = "hello\x1A\x1B\x1C"464        expected = b'filename="hello%1A\x1B%1C"'465        files = {"upload": (filename, b"<file content>")}466        request = httpx.Request("GET", "https://www.example.com", files=files)467        assert expected in request.read()