Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

206 lines · 7.8 KiB · Python

Last changed by

Better HTTP/2 defaults. (#584)Tom Christiebefore adoption30229f1

History of this file

Take it

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

lines 1–21why, one step back
1import binascii
2import 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):

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Drop sync (#544)Tom Christiebefore adoption206c537

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

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

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

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

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

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

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

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

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

lines 145–149why, one step back
145 )
146147148@pytest.mark.parametrize(149 "file_name,expected_content_type",

Minor test fixes (#583)Tom Christiebefore adoption12d00b2

lines 150–154why, one step back
150 [
151 ("example.json", "application/json"),152 ("example.txt", "text/plain"),153 ("no-extension", "application/octet-stream"),154 ],

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

lines 155–170why, one step back
155)
156def test_multipart_encode_files_guesses_correct_content_type(157 file_name, expected_content_type158):159 files = {"file": (file_name, io.BytesIO(b"<file content>"))}160 with mock.patch("os.urandom", return_value=os.urandom(16)):161 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")162163 body, content_type = multipart.multipart_encode(data={}, files=files)164165 assert content_type == f"multipart/form-data; boundary={boundary}"166 assert body == (167 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '168 f'filename="{file_name}"\r\nContent-Type: '169 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"170 "".encode("ascii")

Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc

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

Run SSLConfig cert loading in threadpool (#209)Can Sarıgölbefore adoptionc5248e6

lines 191–206why, one step back
191class TestHeaderParamHTML5Formatting:
192 def test_unicode(self):193 param = multipart._format_param("filename", "n\u00e4me")194 assert param == b'filename="n\xc3\xa4me"'195196 def test_ascii(self):197 param = multipart._format_param("filename", b"name")198 assert param == b'filename="name"'199200 def test_unicode_escape(self):201 param = multipart._format_param("filename", "hello\\world\u0022")202 assert param == b'filename="hello\\\\world%22"'203204 def test_unicode_with_control_character(self):205 param = multipart._format_param("filename", "hello\x1A\x1B\x1C")206 assert param == b'filename="hello%1A\x1B%1C"'