test_multipart.py
This file
Path
tests/test_multipart.py
267 lines · 9.5 KiB · Python
Last changed by
Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
History of this fileTake it
The walk stopped after 200 commits: lines older than bacc2d1 point at it.
Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 1–9why, one step back1import cgi2import io3import os4import typing5from unittest import mock67import pytest89import httpxRefactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 10why, one step back10from httpx._content import encode_requestMap HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 11–13why, one step back11from httpx._utils import format_form_param1213Refactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d
lines 14–15why, one step back14def echo_request_content(request: httpx.Request) -> httpx.Response:15 return httpx.Response(200, content=request.content)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 16–18why, one step back161718@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 19why, one step back19def test_multipart(value, output):Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 20why, one step back20 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 21why, one step back21Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 22–26why, one step back22 # Test with a single-value 'data' argument, and a plain file 'files' argument.23 data = {"text": value}24 files = {"file": io.BytesIO(b"<file content>")}25 response = client.post("http://127.0.0.1:8000/", data=data, files=files)26 assert response.status_code == 200Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 27why, one step back27Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 28–36why, one step back28 # We're using the cgi module to verify the behavior here, which is a29 # bit grungy, but sufficient just for our testing purposes.30 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]31 content_length = response.request.headers["Content-Length"]32 pdict: dict = {33 "boundary": boundary.encode("ascii"),34 "CONTENT-LENGTH": content_length,35 }36 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 37why, one step back37Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 38–41why, one step back38 # Note that the expected return type for text fields39 # appears to differs from 3.6 to 3.7+40 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]41 assert multipart["file"] == [b"<file content>"]Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 42why, one step back42Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 43why, one step back43Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 44why, one step back44@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 45why, one step back45def test_multipart_invalid_key(key):Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 46why, one step back46 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 47why, one step back47Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 48–56why, one step back48 data = {key: "abc"}49 files = {"file": io.BytesIO(b"<file content>")}50 with pytest.raises(TypeError) as e:51 client.post(52 "http://127.0.0.1:8000/",53 data=data,54 files=files,55 )56 assert "Invalid type for name" in str(e.value)Include invalid name/value when raising TypeError in DataField (#1368)plotskibefore adoption589c6e0
line 57why, one step back57 assert repr(key) in str(e.value)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 58why, one step back58Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 59why, one step back59Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 60why, one step back60@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 61why, one step back61def test_multipart_invalid_value(value):Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 62why, one step back62 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 63why, one step back63Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 64–68why, one step back64 data = {"text": value}65 files = {"file": io.BytesIO(b"<file content>")}66 with pytest.raises(TypeError) as e:67 client.post("http://127.0.0.1:8000/", data=data, files=files)68 assert "Invalid type for value" in str(e.value)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 69–70why, one step back6970Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 71why, one step back71def test_multipart_file_tuple():Add `httpx.MockTransport()` (#1401)Tom Christiebefore adoption9c7c2ac
line 72why, one step back72 client = httpx.Client(transport=httpx.MockTransport(echo_request_content))Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 73why, one step back73Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 74–94why, one step back74 # Test with a list of values 'data' argument,75 # and a tuple style 'files' argument.76 data = {"text": ["abc"]}77 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}78 response = client.post("http://127.0.0.1:8000/", data=data, files=files)79 assert response.status_code == 2008081 # We're using the cgi module to verify the behavior here, which is a82 # bit grungy, but sufficient just for our testing purposes.83 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]84 content_length = response.request.headers["Content-Length"]85 pdict: dict = {86 "boundary": boundary.encode("ascii"),87 "CONTENT-LENGTH": content_length,88 }89 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)9091 # Note that the expected return type for text fields92 # appears to differs from 3.6 to 3.7+93 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]94 assert multipart["file"] == [b"<file content>"]Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 95–110why, one step back959697def test_multipart_encode(tmp_path: typing.Any) -> None:98 path = str(tmp_path / "name.txt")99 with open(path, "wb") as f:100 f.write(b"<file content>")101102 data = {103 "a": "1",104 "b": b"C",105 "c": ["11", "22", "33"],106 "d": "",107 }108 files = {"file": ("name.txt", open(path, "rb"))}109110 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 111why, one step back111 boundary = os.urandom(16).hex()Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 112why, one step back112Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 113why, one step back113 headers, stream = encode_request(data=data, files=files)Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 114why, one step back114 assert isinstance(stream, typing.Iterable)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 115–128why, one step back115116 content = (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\n\r\n'123 '--{0}\r\nContent-Disposition: form-data; name="file";'124 ' filename="name.txt"\r\n'125 "Content-Type: text/plain\r\n\r\n<file content>\r\n"126 "--{0}--\r\n"127 "".format(boundary).encode("ascii")128 )Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
lines 129–133why, one step back129 assert headers == {130 "Content-Type": f"multipart/form-data; boundary={boundary}",131 "Content-Length": str(len(content)),132 }133 assert content == b"".join(stream)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 134–138why, one step back134135136def test_multipart_encode_files_allows_filenames_as_none() -> None:137 files = {"file": (None, io.BytesIO(b"<file content>"))}138 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 139why, one step back139 boundary = os.urandom(16).hex()Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 140why, one step back140Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 141why, one step back141 headers, stream = encode_request(data={}, files=files)Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 142why, one step back142 assert isinstance(stream, typing.Iterable)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 143why, one step back143Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 144why, one step back144 content = (Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 145–148why, one step back145 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'146 "<file content>\r\n--{0}--\r\n"147 "".format(boundary).encode("ascii")148 )Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
lines 149–153why, one step back149 assert headers == {150 "Content-Type": f"multipart/form-data; boundary={boundary}",151 "Content-Length": str(len(content)),152 }153 assert content == b"".join(stream)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 154–168why, one step back154155156@pytest.mark.parametrize(157 "file_name,expected_content_type",158 [159 ("example.json", "application/json"),160 ("example.txt", "text/plain"),161 ("no-extension", "application/octet-stream"),162 ],163)164def test_multipart_encode_files_guesses_correct_content_type(165 file_name: str, expected_content_type: str166) -> None:167 files = {"file": (file_name, io.BytesIO(b"<file content>"))}168 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 169why, one step back169 boundary = os.urandom(16).hex()Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 170why, one step back170Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 171why, one step back171 headers, stream = encode_request(data={}, files=files)Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 172why, one step back172 assert isinstance(stream, typing.Iterable)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 173why, one step back173Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 174why, one step back174 content = (Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 175–179why, one step back175 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '176 f'filename="{file_name}"\r\nContent-Type: '177 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"178 "".encode("ascii")179 )Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
lines 180–184why, one step back180 assert headers == {181 "Content-Type": f"multipart/form-data; boundary={boundary}",182 "Content-Length": str(len(content)),183 }184 assert content == b"".join(stream)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 185–195why, one step back185186187@pytest.mark.parametrize(188 "value, output",189 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),190)191def test_multipart_encode_files_allows_bytes_or_str_content(192 value: typing.Union[str, bytes], output: str193) -> None:194 files = {"file": ("test.txt", value, "text/plain")}195 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 196why, one step back196 boundary = os.urandom(16).hex()Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 197why, one step back197Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 198why, one step back198 headers, stream = encode_request(data={}, files=files)Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 199why, one step back199 assert isinstance(stream, typing.Iterable)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 200–207why, one step back200201 content = (202 '--{0}\r\nContent-Disposition: form-data; name="file"; '203 'filename="test.txt"\r\n'204 "Content-Type: text/plain\r\n\r\n{1}\r\n"205 "--{0}--\r\n"206 "".format(boundary, output).encode("ascii")207 )Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
lines 208–212why, one step back208 assert headers == {209 "Content-Type": f"multipart/form-data; boundary={boundary}",210 "Content-Length": str(len(content)),211 }212 assert content == b"".join(stream)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 213–231why, one step back213214215def test_multipart_encode_non_seekable_filelike() -> None:216 """217 Test that special readable but non-seekable filelike objects are supported,218 at the cost of reading them into memory at most once.219 """220221 class IteratorIO(io.IOBase):222 def __init__(self, iterator: typing.Iterator[bytes]) -> None:223 self._iterator = iterator224225 def read(self, *args: typing.Any) -> bytes:226 return b"".join(self._iterator)227228 def data() -> typing.Iterator[bytes]:229 yield b"Hello"230 yield b"World"231Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 232why, one step back232 fileobj: typing.Any = IteratorIO(data())Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
line 233why, one step back233 files = {"file": fileobj}Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
lines 234–235why, one step back234 headers, stream = encode_request(files=files, boundary=b"+++")235 assert isinstance(stream, typing.Iterable)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 236–244why, one step back236237 content = (238 b"--+++\r\n"239 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'240 b"Content-Type: application/octet-stream\r\n"241 b"\r\n"242 b"HelloWorld\r\n"243 b"--+++--\r\n"244 )Drop ContentStream (#1295)Tom Christiebefore adoptionfbb21fb
line 245why, one step back245 assert headers == {Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 246–248why, one step back246 "Content-Type": "multipart/form-data; boundary=+++",247 "Content-Length": str(len(content)),248 }Refactor content streams (#1296)Tom Christiebefore adoption354c4ca
line 249why, one step back249 assert content == b"".join(stream)Map HTTPCore exceptions (#1044)Florimond Mancabefore adoptionbacc2d1
lines 250–267why, one step back250251252class TestHeaderParamHTML5Formatting:253 def test_unicode(self):254 param = format_form_param("filename", "n\u00e4me")255 assert param == b'filename="n\xc3\xa4me"'256257 def test_ascii(self):258 param = format_form_param("filename", b"name")259 assert param == b'filename="name"'260261 def test_unicode_escape(self):262 param = format_form_param("filename", "hello\\world\u0022")263 assert param == b'filename="hello\\\\world%22"'264265 def test_unicode_with_control_character(self):266 param = format_form_param("filename", "hello\x1A\x1B\x1C")267 assert param == b'filename="hello%1A\x1B%1C"'