test_multipart.py
This file
Path
tests/test_multipart.py
278 lines · 9.8 KiB · Python
Last changed by
Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
History of this fileTake it
The walk stopped after 200 commits: lines older than 3acd72a point at it.
Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
lines 1–3why, one step back1import cgi2import io3import osHttpcore interface (#804)Tom Christiebefore adoption3046e92
line 4why, one step back4import typingRemove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
lines 5–6why, one step back5from unittest import mock6Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 7why, one step back7import httpcoreRemove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
lines 8–10why, one step back8import pytest910import httpxUse sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 11why, one step back11from httpx._content_streams import MultipartStream, encodeRemove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
lines 12–14why, one step back12from httpx._utils import format_form_param1314Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 15–16why, one step back15class MockTransport(httpcore.SyncHTTPTransport):16 def request(Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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
line 20why, one step back20 headers: typing.List[typing.Tuple[bytes, bytes]] = None,Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 21why, one step back21 stream: httpcore.SyncByteStream = 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–27why, one step back23 ) -> typing.Tuple[24 bytes,25 int,26 bytes,27 typing.List[typing.Tuple[bytes, bytes]],Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 28why, one step back28 httpcore.SyncByteStream,Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 29why, one step back29 ]:Type check tests (#1054)Florimond Mancabefore adoption0296c2b
line 30why, one step back30 assert stream is not NoneUse sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 31why, one step back31 content = httpcore.IteratorByteStream(iterator=(part for part in stream))Httpcore interface (#804)Tom Christiebefore adoption3046e92
line 32why, one step back32 return b"HTTP/1.1", 200, b"OK", [], contentRemove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
lines 33–35why, one step back333435@pytest.mark.parametrize(("value,output"), (("abc", b"abc"), (b"abc", b"abc")))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 36–37why, one step back36def test_multipart(value, output):37 client = httpx.Client(transport=MockTransport())Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 38why, one step back38Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 39–43why, one step back39 # 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 = client.post("http://127.0.0.1:8000/", data=data, files=files)43 assert response.status_code == 200Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 44why, one step back44Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
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)Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 54why, one step back54Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
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>"]Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 59why, one step back59Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 60why, one step back60Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 61why, one step back61@pytest.mark.parametrize(("key"), (b"abc", 1, 2.3, None))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 62–63why, one step back62def test_multipart_invalid_key(key):63 client = httpx.Client(transport=MockTransport())Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 64why, one step back64Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 65–73why, one step back65 data = {key: "abc"}66 files = {"file": io.BytesIO(b"<file content>")}67 with pytest.raises(TypeError) as e:68 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)Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 74why, one step back74Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
line 75why, one step back75Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 76why, one step back76@pytest.mark.parametrize(("value"), (1, 2.3, None, [None, "abc"], {None: "abc"}))Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 77–78why, one step back77def test_multipart_invalid_value(value):78 client = httpx.Client(transport=MockTransport())Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 79why, one step back79Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 80–84why, one step back80 data = {"text": value}81 files = {"file": io.BytesIO(b"<file content>")}82 with pytest.raises(TypeError) as e:83 client.post("http://127.0.0.1:8000/", data=data, files=files)84 assert "Invalid type for value" in str(e.value)Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
lines 85–86why, one step back8586Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 87–88why, one step back87def test_multipart_file_tuple():88 client = httpx.Client(transport=MockTransport())Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
line 89why, one step back89Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9
lines 90–110why, one step back90 # 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 = client.post("http://127.0.0.1:8000/", data=data, files=files)95 assert response.status_code == 2009697 # 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)106107 # 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>"]Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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>")117Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
lines 118–123why, one step back118 data = {119 "a": "1",120 "b": b"C",121 "c": ["11", "22", "33"],122 "d": "",123 }Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb
line 124why, one step back124 files = {"file": ("name.txt", open(path, "rb"))}Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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 back128Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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()132Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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 = (Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
lines 135–146why, 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'140 '--{0}\r\nContent-Disposition: form-data; name="d"\r\n\r\n\r\n'141 '--{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) == contentRemove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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:Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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()Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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()Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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) == (Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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:Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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()Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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()Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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) == (Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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")}Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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()Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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()Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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 = (Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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"Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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")Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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) == contentRemove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a
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"'