test_multipart.py
This file
Path
tests/test_multipart.py
262 lines · 9.4 KiB · Python
Last changed by
encode -> encode_request (#1292)Tom Christiebefore adoption09f94ed
History of this fileTake it
The walk stopped after 200 commits: lines older than 19bf211 point at it.
Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 1–9why, one step back1import cgi2import io3import os4import typing5from unittest import mock67import pytest89import httpxencode -> encode_request (#1292)Tom Christiebefore adoption09f94ed
line 10why, one step back10from httpx._content_streams import MultipartStream, encode_requestTest Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 11why, one step back11from httpx._utils import format_form_paramRefactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d
line 12why, one step back12from tests.utils import MockTransportTest Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 13–14why, one step back1314Refactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d
lines 15–16why, one step back15def echo_request_content(request: httpx.Request) -> httpx.Response:16 return httpx.Response(200, content=request.content)Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 17–19why, one step back171819@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 20why, one step back20def test_multipart(value, output):Refactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d
line 21why, one step back21 client = httpx.Client(transport=MockTransport(echo_request_content))Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 22why, one step back22Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 23–27why, one step back23 # Test with a single-value 'data' argument, and a plain file 'files' argument.24 data = {"text": value}25 files = {"file": io.BytesIO(b"<file content>")}26 response = client.post("http://127.0.0.1:8000/", data=data, files=files)27 assert response.status_code == 200Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 28why, one step back28Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 29–37why, one step back29 # We're using the cgi module to verify the behavior here, which is a30 # bit grungy, but sufficient just for our testing purposes.31 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]32 content_length = response.request.headers["Content-Length"]33 pdict: dict = {34 "boundary": boundary.encode("ascii"),35 "CONTENT-LENGTH": content_length,36 }37 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 38why, one step back38Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 39–42why, one step back39 # Note that the expected return type for text fields40 # appears to differs from 3.6 to 3.7+41 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]42 assert multipart["file"] == [b"<file content>"]Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 43why, one step back43Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 44why, one step back44Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 45why, one step back45@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 46why, one step back46def test_multipart_invalid_key(key):Refactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d
line 47why, one step back47 client = httpx.Client(transport=MockTransport(echo_request_content))Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 48why, one step back48Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 49–57why, one step back49 data = {key: "abc"}50 files = {"file": io.BytesIO(b"<file content>")}51 with pytest.raises(TypeError) as e:52 client.post(53 "http://127.0.0.1:8000/",54 data=data,55 files=files,56 )57 assert "Invalid type for name" in str(e.value)Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 58why, one step back58Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 59why, one step back59Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
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):Refactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d
line 62why, one step back62 client = httpx.Client(transport=MockTransport(echo_request_content))Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
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)Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 69–70why, one step back6970Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 71why, one step back71def test_multipart_file_tuple():Refactor tests to use `MockTransport(<handler_function>)` (#1281)Tom Christiebefore adoptionc2afd2d
line 72why, one step back72 client = httpx.Client(transport=MockTransport(echo_request_content))Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
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>"]Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
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()Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 112why, one step back112encode -> encode_request (#1292)Tom Christiebefore adoption09f94ed
line 113why, one step back113 stream = encode_request(data=data, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 114why, one step back114 assert isinstance(stream, MultipartStream)Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 115–137why, one step back115 assert stream.can_replay()116117 assert stream.content_type == f"multipart/form-data; boundary={boundary}"118 content = (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\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 )131 assert stream.get_headers()["Content-Length"] == str(len(content))132 assert b"".join(stream) == content133134135def test_multipart_encode_files_allows_filenames_as_none() -> None:136 files = {"file": (None, io.BytesIO(b"<file content>"))}137 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 138why, one step back138 boundary = os.urandom(16).hex()Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 139why, one step back139encode -> encode_request (#1292)Tom Christiebefore adoption09f94ed
line 140why, one step back140 stream = encode_request(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 141why, one step back141 assert isinstance(stream, MultipartStream)Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 142–164why, one step back142 assert stream.can_replay()143144 assert stream.content_type == f"multipart/form-data; boundary={boundary}"145 assert b"".join(stream) == (146 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'147 "<file content>\r\n--{0}--\r\n"148 "".format(boundary).encode("ascii")149 )150151152@pytest.mark.parametrize(153 "file_name,expected_content_type",154 [155 ("example.json", "application/json"),156 ("example.txt", "text/plain"),157 ("no-extension", "application/octet-stream"),158 ],159)160def test_multipart_encode_files_guesses_correct_content_type(161 file_name: str, expected_content_type: str162) -> None:163 files = {"file": (file_name, io.BytesIO(b"<file content>"))}164 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 165why, one step back165 boundary = os.urandom(16).hex()Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 166why, one step back166encode -> encode_request (#1292)Tom Christiebefore adoption09f94ed
line 167why, one step back167 stream = encode_request(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 168why, one step back168 assert isinstance(stream, MultipartStream)Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 169–179why, one step back169 assert stream.can_replay()170171 assert stream.content_type == f"multipart/form-data; boundary={boundary}"172 assert b"".join(stream) == (173 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '174 f'filename="{file_name}"\r\nContent-Type: '175 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"176 "".encode("ascii")177 )178179Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
lines 180–187why, one step back180@pytest.mark.parametrize(181 "value, output",182 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),183)184def test_multipart_encode_files_allows_bytes_or_str_content(185 value: typing.Union[str, bytes], output: str186) -> None:187 files = {"file": ("test.txt", value, "text/plain")}Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 188why, one step back188 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 189why, one step back189 boundary = os.urandom(16).hex()Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 190why, one step back190encode -> encode_request (#1292)Tom Christiebefore adoption09f94ed
line 191why, one step back191 stream = encode_request(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 192why, one step back192 assert isinstance(stream, MultipartStream)Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 193–198why, one step back193 assert stream.can_replay()194195 assert stream.content_type == f"multipart/form-data; boundary={boundary}"196 content = (197 '--{0}\r\nContent-Disposition: form-data; name="file"; '198 'filename="test.txt"\r\n'Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
line 199why, one step back199 "Content-Type: text/plain\r\n\r\n{1}\r\n"Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 200why, one step back200 "--{0}--\r\n"Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
line 201why, one step back201 "".format(boundary, output).encode("ascii")Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 202–226why, one step back202 )203 assert stream.get_headers()["Content-Length"] == str(len(content))204 assert b"".join(stream) == content205206207def test_multipart_encode_non_seekable_filelike() -> None:208 """209 Test that special readable but non-seekable filelike objects are supported,210 at the cost of reading them into memory at most once.211 """212213 class IteratorIO(io.IOBase):214 def __init__(self, iterator: typing.Iterator[bytes]) -> None:215 self._iterator = iterator216217 def seekable(self) -> bool:218 return False219220 def read(self, *args: typing.Any) -> bytes:221 return b"".join(self._iterator)222223 def data() -> typing.Iterator[bytes]:224 yield b"Hello"225 yield b"World"226Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 227why, one step back227 fileobj: typing.Any = IteratorIO(data())Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
line 228why, one step back228 files = {"file": fileobj}encode -> encode_request (#1292)Tom Christiebefore adoption09f94ed
line 229why, one step back229 stream = encode_request(files=files, boundary=b"+++")Test Suite on GitHub Actions (#907)Tom Christiebefore adoption19bf211
lines 230–262why, one step back230 assert not stream.can_replay()231232 content = (233 b"--+++\r\n"234 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'235 b"Content-Type: application/octet-stream\r\n"236 b"\r\n"237 b"HelloWorld\r\n"238 b"--+++--\r\n"239 )240 assert stream.get_headers() == {241 "Content-Type": "multipart/form-data; boundary=+++",242 "Content-Length": str(len(content)),243 }244 assert b"".join(stream) == content245246247class TestHeaderParamHTML5Formatting:248 def test_unicode(self):249 param = format_form_param("filename", "n\u00e4me")250 assert param == b'filename="n\xc3\xa4me"'251252 def test_ascii(self):253 param = format_form_param("filename", b"name")254 assert param == b'filename="name"'255256 def test_unicode_escape(self):257 param = format_form_param("filename", "hello\\world\u0022")258 assert param == b'filename="hello\\\\world%22"'259260 def test_unicode_with_control_character(self):261 param = format_form_param("filename", "hello\x1A\x1B\x1C")262 assert param == b'filename="hello%1A\x1B%1C"'