Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

204 lines · 7.8 KiB · Python

Last changed by

Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950

History of this file

Take it

The walk stopped after 200 commits: lines older than 7e9110b point at it.

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

lines 1–12why, one step back
1import binascii
2import cgi3import io4import os5from unittest import mock67import pytest89from httpx import (10 CertTypes,11 Client,12 Dispatcher,

Merge pull request #241 from encode/protocol-supportTom Christiebefore adoptione0b523d

line 13why, one step back
13 HTTPVersionTypes,

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

lines 14–22why, one step back
14 Request,
15 Response,16 TimeoutTypes,17 VerifyTypes,18 multipart,19)202122class MockDispatch(Dispatcher):

Drop sync (#544)Tom Christiebefore adoption206c537

line 23why, one step back
23 async def send(

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

lines 24–28why, one step back
24 self,
25 request: Request,26 verify: VerifyTypes = None,27 cert: CertTypes = None,28 timeout: TimeoutTypes = None,

Merge pull request #241 from encode/protocol-supportTom Christiebefore adoptione0b523d

line 29why, one step back
29 http_versions: HTTPVersionTypes = None,

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

line 30why, one step back
30 ) -> Response:

Drop sync (#544)Tom Christiebefore adoption206c537

lines 31–32why, one step back
31 content = await request.read()
32 return Response(200, content=content)

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

lines 33–35why, one step back
33
3435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))

Drop sync (#544)Tom Christiebefore adoption206c537

lines 36–37why, one step back
36@pytest.mark.asyncio
37async def test_multipart(value, output):

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

lines 38–42why, one step back
38 client = Client(dispatch=MockDispatch())
3940 # Test with a single-value 'data' argument, and a plain file 'files' argument.41 data = {"text": value}42 files = {"file": io.BytesIO(b"<file content>")}

Drop sync (#544)Tom Christiebefore adoption206c537

line 43why, one step back
43 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)

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

lines 44–59why, one step back
44 assert response.status_code == 200
4546 # We're using the cgi module to verify the behavior here, which is a47 # bit grungy, but sufficient just for our testing purposes.48 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]49 content_length = response.request.headers["Content-Length"]50 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}51 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)5253 # Note that the expected return type for text fields54 # appears to differs from 3.6 to 3.7+55 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]56 assert multipart["file"] == [b"<file content>"]575859@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))

Drop sync (#544)Tom Christiebefore adoption206c537

lines 60–61why, one step back
60@pytest.mark.asyncio
61async def test_multipart_invalid_key(key):

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

lines 62–65why, one step back
62 client = Client(dispatch=MockDispatch())
63 data = {key: "abc"}64 files = {"file": io.BytesIO(b"<file content>")}65 with pytest.raises(TypeError) as e:

Drop sync (#544)Tom Christiebefore adoption206c537

line 66why, one step back
66 await client.post("http://127.0.0.1:8000/", data=data, files=files)

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

lines 67–70why, one step back
67 assert "Invalid type for name" in str(e.value)
686970@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))

Drop sync (#544)Tom Christiebefore adoption206c537

lines 71–72why, one step back
71@pytest.mark.asyncio
72async def test_multipart_invalid_value(value):

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

lines 73–76why, one step back
73 client = Client(dispatch=MockDispatch())
74 data = {"text": value}75 files = {"file": io.BytesIO(b"<file content>")}76 with pytest.raises(TypeError) as e:

Drop sync (#544)Tom Christiebefore adoption206c537

line 77why, one step back
77 await client.post("http://127.0.0.1:8000/", data=data, files=files)

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

lines 78–80why, one step back
78 assert "Invalid type for value" in str(e.value)
7980

Drop sync (#544)Tom Christiebefore adoption206c537

lines 81–82why, one step back
81@pytest.mark.asyncio
82async def test_multipart_file_tuple():

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

lines 83–87why, one step back
83 client = Client(dispatch=MockDispatch())
8485 # Test with a list of values 'data' argument, and a tuple style 'files' argument.86 data = {"text": ["abc"]}87 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}

Drop sync (#544)Tom Christiebefore adoption206c537

line 88why, one step back
88 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)

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

lines 89–132why, one step back
89 assert response.status_code == 200
9091 # We're using the cgi module to verify the behavior here, which is a92 # bit grungy, but sufficient just for our testing purposes.93 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]94 content_length = response.request.headers["Content-Length"]95 pdict = {"boundary": boundary.encode("ascii"), "CONTENT-LENGTH": content_length}96 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9798 # Note that the expected return type for text fields99 # appears to differs from 3.6 to 3.7+100 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]101 assert multipart["file"] == [b"<file content>"]102103104def test_multipart_encode():105 data = {106 "a": "1",107 "b": b"C",108 "c": ["11", "22", "33"],109 "d": {"ff": ["1", b"2", "3"], "fff": ["11", b"22", "33"]},110 "f": "",111 }112 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}113114 with mock.patch("os.urandom", return_value=os.urandom(16)):115 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")116 body, content_type = multipart.multipart_encode(data=data, files=files)117 assert content_type == f"multipart/form-data; boundary={boundary}"118 assert body == (119 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'120 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'121 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'122 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'123 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'124 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nff\r\n'125 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\nfff\r\n'126 '--{0}\r\nContent-Disposition: form-data; name="f"\r\n\r\n\r\n'127 '--{0}\r\nContent-Disposition: form-data; name="file";'128 ' filename="name.txt"\r\n'129 "Content-Type: text/plain\r\n\r\n<file content>\r\n"130 "--{0}--\r\n"131 "".format(boundary).encode("ascii")132 )

Fixed multipart header params encoding (#167)Nikbefore adoptionfb17459

lines 133–134why, one step back
133
134

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 135–143why, one step back
135def test_multipart_encode_files_allows_filenames_as_none():
136 files = {"file": (None, io.BytesIO(b"<file content>"))}137 with mock.patch("os.urandom", return_value=os.urandom(16)):138 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")139140 body, content_type = multipart.multipart_encode(data={}, files=files)141142 assert content_type == f"multipart/form-data; boundary={boundary}"143 assert body == (

Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950

lines 144–145why, one step back
144 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'
145 "<file content>\r\n--{0}--\r\n"

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

line 146why, one step back
146 "".format(boundary).encode("ascii")

Files without a filename should not set a Content-Type in multipart data. (#520)Mattwmaster58before adoptioned94950

lines 147–168why, one step back
147 )
148149150@pytest.mark.parametrize(151 "file_name,expected_content_type",152 [("example.json", "application/json"), ("example.log", "application/octet-stream")],153)154def test_multipart_encode_files_guesses_correct_content_type(155 file_name, expected_content_type156):157 files = {"file": (file_name, io.BytesIO(b"<file content>"))}158 with mock.patch("os.urandom", return_value=os.urandom(16)):159 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")160161 body, content_type = multipart.multipart_encode(data={}, files=files)162163 assert content_type == f"multipart/form-data; boundary={boundary}"164 assert body == (165 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '166 f'filename="{file_name}"\r\nContent-Type: '167 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"168 "".encode("ascii")

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

lines 169–188why, one step back
169 )
170171172def test_multipart_encode_files_allows_str_content():173 files = {"file": ("test.txt", "<string content>", "text/plain")}174 with mock.patch("os.urandom", return_value=os.urandom(16)):175 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")176177 body, content_type = multipart.multipart_encode(data={}, files=files)178179 assert content_type == f"multipart/form-data; boundary={boundary}"180 assert body == (181 '--{0}\r\nContent-Disposition: form-data; name="file"; '182 'filename="test.txt"\r\n'183 "Content-Type: text/plain\r\n\r\n<string content>\r\n"184 "--{0}--\r\n"185 "".format(boundary).encode("ascii")186 )187188

Fixed multipart header params encoding (#167)Nikbefore adoptionfb17459

lines 189–204why, one step back
189class TestHeaderParamHTML5Formatting:
190 def test_unicode(self):191 param = multipart._format_param("filename", "n\u00e4me")192 assert param == b'filename="n\xc3\xa4me"'193194 def test_ascii(self):195 param = multipart._format_param("filename", b"name")196 assert param == b'filename="name"'197198 def test_unicode_escape(self):199 param = multipart._format_param("filename", "hello\\world\u0022")200 assert param == b'filename="hello\\\\world%22"'201202 def test_unicode_with_control_character(self):203 param = multipart._format_param("filename", "hello\x1A\x1B\x1C")204 assert param == b'filename="hello%1A\x1B%1C"'