Skip to content
Myr

test_multipart.py

This file

Path

tests/test_multipart.py

183 lines · 7.0 KiB · Python

Last changed by

Drop sync (#544)Tom Christiebefore adoption206c537

History of this file

Take it

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

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

lines 1–8why, one step back
1import binascii
2import cgi3import io4import os5from unittest import mock67import pytest8

Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b

line 9why, one step back
9from httpx import (

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

lines 10–12why, one step back
10 CertTypes,
11 Client,12 Dispatcher,

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

line 13why, one step back
13 HTTPVersionTypes,

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

lines 14–17why, one step back
14 Request,
15 Response,16 TimeoutTypes,17 VerifyTypes,

Check disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0

line 18why, one step back
18 multipart,

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

lines 19–22why, one step back
19)
202122class MockDispatch(Dispatcher):

Drop sync (#544)Tom Christiebefore adoption206c537

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

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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,

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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)

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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):

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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)

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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):

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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)

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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):

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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)

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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():

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

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)

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

lines 89–126why, 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'

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

lines 127–128why, one step back
127 '--{0}\r\nContent-Disposition: form-data; name="file";'
128 ' filename="name.txt"\r\n'

Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4

lines 129–132why, one step back
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–167why, 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 == (144 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n'145 "Content-Type: application/octet-stream\r\n\r\n<file content>\r\n"146 "--{0}--\r\n"147 "".format(boundary).encode("ascii")148 )149150151def test_multipart_encode_files_allows_str_content():152 files = {"file": ("test.txt", "<string content>", "text/plain")}153 with mock.patch("os.urandom", return_value=os.urandom(16)):154 boundary = binascii.hexlify(os.urandom(16)).decode("ascii")155156 body, content_type = multipart.multipart_encode(data={}, files=files)157158 assert content_type == f"multipart/form-data; boundary={boundary}"159 assert body == (160 '--{0}\r\nContent-Disposition: form-data; name="file"; '161 'filename="test.txt"\r\n'162 "Content-Type: text/plain\r\n\r\n<string content>\r\n"163 "--{0}--\r\n"164 "".format(boundary).encode("ascii")165 )166167

Fixed multipart header params encoding (#167)Nikbefore adoptionfb17459

lines 168–183why, one step back
168class TestHeaderParamHTML5Formatting:
169 def test_unicode(self):170 param = multipart._format_param("filename", "n\u00e4me")171 assert param == b'filename="n\xc3\xa4me"'172173 def test_ascii(self):174 param = multipart._format_param("filename", b"name")175 assert param == b'filename="name"'176177 def test_unicode_escape(self):178 param = multipart._format_param("filename", "hello\\world\u0022")179 assert param == b'filename="hello\\\\world%22"'180181 def test_unicode_with_control_character(self):182 param = multipart._format_param("filename", "hello\x1A\x1B\x1C")183 assert param == b'filename="hello%1A\x1B%1C"'