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 fileTake 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 back1import binascii2import cgi3import io4import os5from unittest import mock67import pytest8Renaming -> httpx (#129)Tom Christiebefore adoption2d09d5b
line 9why, one step back9from httpx import (Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 10–12why, one step back10 CertTypes,11 Client,12 Dispatcher,Merge pull request #241 from encode/protocol-supportTom Christiebefore adoptione0b523d
line 13why, one step back13 HTTPVersionTypes,Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 14–17why, one step back14 Request,15 Response,16 TimeoutTypes,17 VerifyTypes,Check disconnections on connection reacquiry (#145)Tom Christiebefore adoptionec365c0
line 18why, one step back18 multipart,Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 19–22why, one step back19)202122class MockDispatch(Dispatcher):Drop sync (#544)Tom Christiebefore adoption206c537
line 23why, one step back23 async def send(Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 24–28why, one step back24 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 back29 http_versions: HTTPVersionTypes = None,Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
line 30why, one step back30 ) -> Response:Drop sync (#544)Tom Christiebefore adoption206c537
lines 31–32why, one step back31 content = await request.read()32 return Response(200, content=content)Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 33–35why, one step back333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))Drop sync (#544)Tom Christiebefore adoption206c537
lines 36–37why, one step back36@pytest.mark.asyncio37async def test_multipart(value, output):Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 38–42why, one step back38 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 back43 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 back44 assert response.status_code == 2004546 # 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 back60@pytest.mark.asyncio61async def test_multipart_invalid_key(key):Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 62–65why, one step back62 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 back66 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 back67 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 back71@pytest.mark.asyncio72async def test_multipart_invalid_value(value):Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 73–76why, one step back73 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 back77 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 back78 assert "Invalid type for value" in str(e.value)7980Drop sync (#544)Tom Christiebefore adoption206c537
lines 81–82why, one step back81@pytest.mark.asyncio82async def test_multipart_file_tuple():Multipart data values encoding (#121)ambrozicbefore adoption0e8dae4
lines 83–87why, one step back83 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 back88 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 back89 assert response.status_code == 2009091 # 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 back127 '--{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 back129 "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 back133134Multipart files tweaks (#482)Yeray Diaz Diazbefore adoption9ec2cfc
lines 135–167why, one step back135def 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 )166167Fixed multipart header params encoding (#167)Nikbefore adoptionfb17459
lines 168–183why, one step back168class 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"'