test_multipart.py
This file
Path
tests/test_multipart.py
278 lines · 10.2 KiB · Python
Last changed by
Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
History of this fileTake it
The walk stopped after 200 commits: lines older than 6614831 point at it.
Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 1–3why, one step back1import cgi2import io3import osHttpcore interface (#804)Tom Christiebefore adoption3046e92
line 4why, one step back4import typingUse a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 5–6why, one step back5from unittest import mock6Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 7why, one step back7import httpcoreUse a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 8–10why, one step back8import pytest910import httpxType check tests (#1054)Florimond Mancabefore adoption0296c2b
line 11why, one step back11from httpx._content_streams import AsyncIteratorStream, MultipartStream, encodeUse a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 12–14why, one step back12from httpx._utils import format_form_param1314Replace remaining occurrences of dispatch with transport (#1010)Josep Cugatbefore adoption89a8100
line 15why, one step back15class MockTransport(httpcore.AsyncHTTPTransport):Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 16why, one step back16 async def request(Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 17why, one step back17 self,Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 18why, one step back18 method: bytes,Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 19why, one step back19 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 20–21why, one step back20 headers: typing.List[typing.Tuple[bytes, bytes]] = None,21 stream: httpcore.AsyncByteStream = None,Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722
line 22why, one step back22 timeout: typing.Mapping[str, typing.Optional[float]] = None,Httpcore interface (#804)Tom Christiebefore adoption3046e92
lines 23–29why, one step back23 ) -> typing.Tuple[24 bytes,25 int,26 bytes,27 typing.List[typing.Tuple[bytes, bytes]],28 httpcore.AsyncByteStream,29 ]:Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 30why, one step back30 assert stream is not NoneHttpcore interface (#804)Tom Christiebefore adoption3046e92
lines 31–32why, one step back31 content = AsyncIteratorStream(aiterator=(part async for part in stream))32 return b"HTTP/1.1", 200, b"OK", [], contentUse a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 33–37why, one step back333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))36@pytest.mark.asyncio37async def test_multipart(value, output):Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 38–43why, one step back38 async with httpx.AsyncClient(transport=MockTransport()) as client:39 # Test with a single-value 'data' argument, and a plain file 'files' argument.40 data = {"text": value}41 files = {"file": io.BytesIO(b"<file content>")}42 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)43 assert response.status_code == 200Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 44why, one step back44Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 45–53why, one step back45 # We're using the cgi module to verify the behavior here, which is a46 # bit grungy, but sufficient just for our testing purposes.47 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]48 content_length = response.request.headers["Content-Length"]49 pdict: dict = {50 "boundary": boundary.encode("ascii"),51 "CONTENT-LENGTH": content_length,52 }53 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 54why, one step back54Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 55–58why, one step back55 # Note that the expected return type for text fields56 # appears to differs from 3.6 to 3.7+57 assert multipart["text"] == [output.decode()] or multipart["text"] == [output]58 assert multipart["file"] == [b"<file content>"]Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 59–63why, one step back596061@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))62@pytest.mark.asyncio63async def test_multipart_invalid_key(key):Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 64–73why, one step back64 async with httpx.AsyncClient(transport=MockTransport()) as client:65 data = {key: "abc"}66 files = {"file": io.BytesIO(b"<file content>")}67 with pytest.raises(TypeError) as e:68 await client.post(69 "http://127.0.0.1:8000/",70 data=data,71 files=files,72 )73 assert "Invalid type for name" in str(e.value)Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 74–78why, one step back747576@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))77@pytest.mark.asyncio78async def test_multipart_invalid_value(value):Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 79–84why, one step back79 async with httpx.AsyncClient(transport=MockTransport()) as client:80 data = {"text": value}81 files = {"file": io.BytesIO(b"<file content>")}82 with pytest.raises(TypeError) as e:83 await client.post("http://127.0.0.1:8000/", data=data, files=files)84 assert "Invalid type for value" in str(e.value)Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 85–88why, one step back858687@pytest.mark.asyncio88async def test_multipart_file_tuple():Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 89–95why, one step back89 async with httpx.AsyncClient(transport=MockTransport()) as client:90 # Test with a list of values 'data' argument,91 # and a tuple style 'files' argument.92 data = {"text": ["abc"]}93 files = {"file": ("name.txt", io.BytesIO(b"<file content>"))}94 response = await client.post("http://127.0.0.1:8000/", data=data, files=files)95 assert response.status_code == 200Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 96why, one step back96Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 97–105why, one step back97 # We're using the cgi module to verify the behavior here, which is a98 # bit grungy, but sufficient just for our testing purposes.99 boundary = response.request.headers["Content-Type"].split("boundary=")[-1]100 content_length = response.request.headers["Content-Length"]101 pdict: dict = {102 "boundary": boundary.encode("ascii"),103 "CONTENT-LENGTH": content_length,104 }105 multipart = cgi.parse_multipart(io.BytesIO(response.content), pdict)Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 106why, one step back106Closing AsyncClient in all tests (#871) (#1219)cdelerbefore adoptionfa7661b
lines 107–110why, one step back107 # Note that the expected return type for text fields108 # appears to differs from 3.6 to 3.7+109 assert multipart["text"] == ["abc"] or multipart["text"] == [b"abc"]110 assert multipart["file"] == [b"<file content>"]Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 111–112why, one step back111112Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 113–117why, one step back113def test_multipart_encode(tmp_path: typing.Any) -> None:114 path = str(tmp_path / "name.txt")115 with open(path, "wb") as f:116 f.write(b"<file content>")117Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 118–121why, one step back118 data = {119 "a": "1",120 "b": b"C",121 "c": ["11", "22", "33"],Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 122why, one step back122 "d": "",Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 123why, one step back123 }Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 124why, one step back124 files = {"file": ("name.txt", open(path, "rb"))}Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 125–126why, one step back125126 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 127why, one step back127 boundary = os.urandom(16).hex()Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 128why, one step back128Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 129why, one step back129 stream = encode(data=data, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 130why, one step back130 assert isinstance(stream, MultipartStream)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 131–132why, one step back131 assert stream.can_replay()132Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 133why, one step back133 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 134why, one step back134 content = (Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 135–139why, one step back135 '--{0}\r\nContent-Disposition: form-data; name="a"\r\n\r\n1\r\n'136 '--{0}\r\nContent-Disposition: form-data; name="b"\r\n\r\nC\r\n'137 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n11\r\n'138 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n22\r\n'139 '--{0}\r\nContent-Disposition: form-data; name="c"\r\n\r\n33\r\n'Don't support broken dict-of-dicts case for data argument (#811)Tom Christiebefore adoption3333152
line 140why, one step back140 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 141–146why, one step back141 '--{0}\r\nContent-Disposition: form-data; name="file";'142 ' filename="name.txt"\r\n'143 "Content-Type: text/plain\r\n\r\n<file content>\r\n"144 "--{0}--\r\n"145 "".format(boundary).encode("ascii")146 )Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 147–148why, one step back147 assert stream.get_headers()["Content-Length"] == str(len(content))148 assert b"".join(stream) == contentUse a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 149–150why, one step back149150Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 151why, one step back151def test_multipart_encode_files_allows_filenames_as_none() -> None:Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 152–153why, one step back152 files = {"file": (None, io.BytesIO(b"<file content>"))}153 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 154why, one step back154 boundary = os.urandom(16).hex()Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 155–156why, one step back155156 stream = encode(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 157why, one step back157 assert isinstance(stream, MultipartStream)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 158why, one step back158 assert stream.can_replay()Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 159–160why, one step back159160 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 161why, one step back161 assert b"".join(stream) == (Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 162–176why, one step back162 '--{0}\r\nContent-Disposition: form-data; name="file"\r\n\r\n'163 "<file content>\r\n--{0}--\r\n"164 "".format(boundary).encode("ascii")165 )166167168@pytest.mark.parametrize(169 "file_name,expected_content_type",170 [171 ("example.json", "application/json"),172 ("example.txt", "text/plain"),173 ("no-extension", "application/octet-stream"),174 ],175)176def test_multipart_encode_files_guesses_correct_content_type(Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 177–178why, one step back177 file_name: str, expected_content_type: str178) -> None:Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 179–180why, one step back179 files = {"file": (file_name, io.BytesIO(b"<file content>"))}180 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 181why, one step back181 boundary = os.urandom(16).hex()Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 182–183why, one step back182183 stream = encode(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 184why, one step back184 assert isinstance(stream, MultipartStream)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 185why, one step back185 assert stream.can_replay()Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 186–187why, one step back186187 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 188why, one step back188 assert b"".join(stream) == (Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 189–195why, one step back189 f'--{boundary}\r\nContent-Disposition: form-data; name="file"; '190 f'filename="{file_name}"\r\nContent-Type: '191 f"{expected_content_type}\r\n\r\n<file content>\r\n--{boundary}--\r\n"192 "".encode("ascii")193 )194195Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
lines 196–203why, one step back196@pytest.mark.parametrize(197 "value, output",198 ((b"<bytes content>", "<bytes content>"), ("<string content>", "<string content>")),199)200def test_multipart_encode_files_allows_bytes_or_str_content(201 value: typing.Union[str, bytes], output: str202) -> None:203 files = {"file": ("test.txt", value, "text/plain")}Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 204why, one step back204 with mock.patch("os.urandom", return_value=os.urandom(16)):Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc
line 205why, one step back205 boundary = os.urandom(16).hex()Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 206–207why, one step back206207 stream = encode(data={}, files=files)Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 208why, one step back208 assert isinstance(stream, MultipartStream)Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 209why, one step back209 assert stream.can_replay()Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 210–211why, one step back210211 assert stream.content_type == f"multipart/form-data; boundary={boundary}"Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 212why, one step back212 content = (Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 213–214why, one step back213 '--{0}\r\nContent-Disposition: form-data; name="file"; '214 'filename="test.txt"\r\n'Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
line 215why, one step back215 "Content-Type: text/plain\r\n\r\n{1}\r\n"Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 216why, one step back216 "--{0}--\r\n"Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2
line 217why, one step back217 "".format(boundary, output).encode("ascii")Use a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
line 218why, one step back218 )Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 219–242why, one step back219 assert stream.get_headers()["Content-Length"] == str(len(content))220 assert b"".join(stream) == content221222223def test_multipart_encode_non_seekable_filelike() -> None:224 """225 Test that special readable but non-seekable filelike objects are supported,226 at the cost of reading them into memory at most once.227 """228229 class IteratorIO(io.IOBase):230 def __init__(self, iterator: typing.Iterator[bytes]) -> None:231 self._iterator = iterator232233 def seekable(self) -> bool:234 return False235236 def read(self, *args: typing.Any) -> bytes:237 return b"".join(self._iterator)238239 def data() -> typing.Iterator[bytes]:240 yield b"Hello"241 yield b"World"242Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 243why, one step back243 fileobj: typing.Any = IteratorIO(data())Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
lines 244–260why, one step back244 files = {"file": fileobj}245 stream = encode(files=files, boundary=b"+++")246 assert not stream.can_replay()247248 content = (249 b"--+++\r\n"250 b'Content-Disposition: form-data; name="file"; filename="upload"\r\n'251 b"Content-Type: application/octet-stream\r\n"252 b"\r\n"253 b"HelloWorld\r\n"254 b"--+++--\r\n"255 )256 assert stream.get_headers() == {257 "Content-Type": "multipart/form-data; boundary=+++",258 "Content-Length": str(len(content)),259 }260 assert b"".join(stream) == contentUse a base_url in app dispatcher examples (#799)Florimond Mancabefore adoption6614831
lines 261–278why, one step back261262263class TestHeaderParamHTML5Formatting:264 def test_unicode(self):265 param = format_form_param("filename", "n\u00e4me")266 assert param == b'filename="n\xc3\xa4me"'267268 def test_ascii(self):269 param = format_form_param("filename", b"name")270 assert param == b'filename="name"'271272 def test_unicode_escape(self):273 param = format_form_param("filename", "hello\\world\u0022")274 assert param == b'filename="hello\\\\world%22"'275276 def test_unicode_with_control_character(self):277 param = format_form_param("filename", "hello\x1A\x1B\x1C")278 assert param == b'filename="hello%1A\x1B%1C"'