Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

125 lines · 4.8 KiB · Python

Last changed by

Add additional flake8 plugins (#157)Can Sarıgölbefore adoption7e9110b

History of this file

Take it

1import binascii2import cgi3import io4import os5from unittest import mock67import pytest89from httpx import (10    CertTypes,11    Client,12    Dispatcher,13    Request,14    Response,15    TimeoutTypes,16    VerifyTypes,17    multipart,18)192021class MockDispatch(Dispatcher):22    def send(23        self,24        request: Request,25        verify: VerifyTypes = None,26        cert: CertTypes = None,27        timeout: TimeoutTypes = None,28    ) -> Response:29        return Response(200, content=request.read())303132@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))33def test_multipart(value, output):34    client = Client(dispatch=MockDispatch())3536    # Test with a single-value 'data' argument, and a plain file 'files' argument.37    data = {"text": value}38    files = {"file": io.BytesIO(b"<file content>")}39    response = client.post("http://127.0.0.1:8000/", data=data, files=files)40    assert response.status_code == 2004142    # We're using the cgi module to verify the behavior here, which is a43    # bit grungy, but sufficient just for our testing purposes.44    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]45    content_length = response.request.headers["Content-Length"]46    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}47    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)4849    # Note that the expected return type for text fields50    # appears to differs from 3.6 to 3.7+51    assert multipart["text"] == [output.decode()] or multipart["text"] == [output]52    assert multipart["file"] == [b"<file content>"]535455@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))56def test_multipart_invalid_key(key):57    client = Client(dispatch=MockDispatch())58    data = {key: "abc"}59    files = {"file": io.BytesIO(b"<file content>")}60    with pytest.raises(TypeError) as e:61        client.post("http://127.0.0.1:8000/", data=data, files=files)62    assert "Invalid type for name" in str(e.value)636465@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))66def test_multipart_invalid_value(value):67    client = Client(dispatch=MockDispatch())68    data = {"text": value}69    files = {"file": io.BytesIO(b"<file content>")}70    with pytest.raises(TypeError) as e:71        client.post("http://127.0.0.1:8000/", data=data, files=files)72    assert "Invalid type for value" in str(e.value)737475def test_multipart_file_tuple():76    client = 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 = 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        body, content_type = multipart.multipart_encode(data=data, files=files)110        assert content_type == f"multipart/form-data; boundary={boundary}"111        assert 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        )