Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

67 lines · 2.4 KiB · Python

Last changed by

Multipart support (#90)Tom Christiebefore adoption6a44b05

History of this file

Take it

1import cgi2import io34import pytest56from http3 import (7    CertTypes,8    Client,9    Dispatcher,10    Request,11    Response,12    TimeoutTypes,13    VerifyTypes,14)151617class MockDispatch(Dispatcher):18    def send(19        self,20        request: Request,21        verify: VerifyTypes = None,22        cert: CertTypes = None,23        timeout: TimeoutTypes = None,24    ) -> Response:25        return Response(200, content=request.read())262728def test_multipart():29    client = Client(dispatch=MockDispatch())3031    # Test with a single-value 'data' argument, and a plain file 'files' argument.32    data = {"text": "abc"}33    files = {"file": io.BytesIO(b"<file content>")}34    response = client.post("http://127.0.0.1:8000/", data=data, files=files)35    assert response.status_code == 2003637    # We're using the cgi module to verify the behavior here, which is a38    # bit grungy, but sufficient just for our testing purposes.39    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]40    content_length = response.request.headers["Content-Length"]41    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}42    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)4344    # Note that the expected return type for text fields appears to differs from 3.6 to 3.7+45    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]46    assert multipart["file"] == [b"<file content>"]474849def test_multipart_file_tuple():50    client = Client(dispatch=MockDispatch())5152    # Test with a list of values 'data' argument, and a tuple style 'files' argument.53    data = {"text": ["abc"]}54    files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}55    response = client.post("http://127.0.0.1:8000/", data=data, files=files)56    assert response.status_code == 2005758    # We're using the cgi module to verify the behavior here, which is a59    # bit grungy, but sufficient just for our testing purposes.60    boundary = response.request.headers["Content-Type"].split("boundary=")[-1]61    content_length = response.request.headers["Content-Length"]62    pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}63    multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)6465    # Note that the expected return type for text fields appears to differs from 3.6 to 3.7+66    assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]67    assert multipart["file"] == [b"<file content>"]