Skip to content
Myr

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 file

Take 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 back
1import cgi
2import io3import os

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 4why, one step back
4import typing

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 5–6why, one step back
5from unittest import mock
6

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 7why, one step back
7import httpcore

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 8–10why, one step back
8import pytest
910import httpx

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 11why, one step back
11from httpx._content_streams import MultipartStream, encode

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 12–14why, one step back
12from httpx._utils import format_form_param
1314

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 15–16why, one step back
15class MockTransport(httpcore.SyncHTTPTransport):
16 def request(

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 17why, one step back
17 self,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 18why, one step back
18 method: bytes,

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 19why, one step back
19 url: typing.Tuple[bytes, bytes, typing.Optional[int], bytes],

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 20why, one step back
20 headers: typing.List[typing.Tuple[bytes, bytes]] = None,

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 21why, one step back
21 stream: httpcore.SyncByteStream = None,

Update to httpcore 0.10 (#1126)Tom Christiebefore adoption876e722

line 22why, one step back
22 timeout: typing.Mapping[str, typing.Optional[float]] = None,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

lines 23–27why, one step back
23 ) -> 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 back
28 httpcore.SyncByteStream,

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 29why, one step back
29 ]:

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 30why, one step back
30 assert stream is not None

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 31why, one step back
31 content = httpcore.IteratorByteStream(iterator=(part for part in stream))

Httpcore interface (#804)Tom Christiebefore adoption3046e92

line 32why, one step back
32 return b"HTTP/1.1", 200, b"OK", [], content

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 33–35why, one step back
33
3435@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 back
36def test_multipart(value, output):
37 client = httpx.Client(transport=MockTransport())

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 38why, one step back
38

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 39–43why, one step back
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 = client.post("http://127.0.0.1:8000/", data=data, files=files)43 assert response.status_code == 200

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 44why, one step back
44

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 45–53why, one step back
45 # We're using the cgi module to verify the behavior here, which is a
46 # 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 back
54

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 55–58why, one step back
55 # Note that the expected return type for text fields
56 # 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 back
59

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 60why, one step back
60

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 61why, one step back
61@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 back
62def test_multipart_invalid_key(key):
63 client = httpx.Client(transport=MockTransport())

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 64why, one step back
64

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 65–73why, one step back
65 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 back
74

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

line 75why, one step back
75

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 76why, one step back
76@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 back
77def test_multipart_invalid_value(value):
78 client = httpx.Client(transport=MockTransport())

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 79why, one step back
79

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 80–84why, one step back
80 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 back
85
86

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 87–88why, one step back
87def test_multipart_file_tuple():
88 client = httpx.Client(transport=MockTransport())

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 89why, one step back
89

Use sync client in test cases (#1241)Tom Christiebefore adoptione39a6d9

lines 90–110why, one step back
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 = 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 back
111
112

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 113–117why, one step back
113def 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>")117

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 118–123why, one step back
118 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 back
124 files = {"file": ("name.txt", open(path, "rb"))}

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 125–126why, one step back
125
126 with mock.patch("os.urandom", return_value=os.urandom(16)):

Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc

line 127why, one step back
127 boundary = os.urandom(16).hex()

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 128why, one step back
128

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 129why, one step back
129 stream = encode(data=data, files=files)

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 130why, one step back
130 assert isinstance(stream, MultipartStream)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 131–132why, one step back
131 assert stream.can_replay()
132

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 133why, one step back
133 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 134why, one step back
134 content = (

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 135–146why, one step back
135 '--{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 back
147 assert stream.get_headers()["Content-Length"] == str(len(content))
148 assert b"".join(stream) == content

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 149–150why, one step back
149
150

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 151why, one step back
151def test_multipart_encode_files_allows_filenames_as_none() -> None:

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 152–153why, one step back
152 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 back
154 boundary = os.urandom(16).hex()

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 155–156why, one step back
155
156 stream = encode(data={}, files=files)

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 157why, one step back
157 assert isinstance(stream, MultipartStream)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 158why, one step back
158 assert stream.can_replay()

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 159–160why, one step back
159
160 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 161why, one step back
161 assert b"".join(stream) == (

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 162–176why, one step back
162 '--{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 back
177 file_name: str, expected_content_type: str
178) -> None:

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 179–180why, one step back
179 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 back
181 boundary = os.urandom(16).hex()

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 182–183why, one step back
182
183 stream = encode(data={}, files=files)

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 184why, one step back
184 assert isinstance(stream, MultipartStream)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 185why, one step back
185 assert stream.can_replay()

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 186–187why, one step back
186
187 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 188why, one step back
188 assert b"".join(stream) == (

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 189–195why, one step back
189 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 )194195

Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2

lines 196–203why, one step back
196@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 back
204 with mock.patch("os.urandom", return_value=os.urandom(16)):

Simplify bytes to hex string conversion (#1049)Taneli Hukkinenbefore adoption6a20cfc

line 205why, one step back
205 boundary = os.urandom(16).hex()

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 206–207why, one step back
206
207 stream = encode(data={}, files=files)

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 208why, one step back
208 assert isinstance(stream, MultipartStream)

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 209why, one step back
209 assert stream.can_replay()

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 210–211why, one step back
210
211 assert stream.content_type == f"multipart/form-data; boundary={boundary}"

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

line 212why, one step back
212 content = (

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 213–214why, one step back
213 '--{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 back
215 "Content-Type: text/plain\r\n\r\n{1}\r\n"

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 216why, one step back
216 "--{0}--\r\n"

Fix bytes support in multipart uploads (#974)Florimond Mancabefore adoptionab9ace2

line 217why, one step back
217 "".format(boundary, output).encode("ascii")

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

line 218why, one step back
218 )

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 219–242why, one step back
219 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"242

Type check tests (#1054)Florimond Mancabefore adoption0296c2b

line 243why, one step back
243 fileobj: typing.Any = IteratorIO(data())

Implement streaming multipart uploads (#857)Florimond Mancabefore adoption5829ecb

lines 244–260why, one step back
244 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) == content

Remove stitches in `requirements.txt` (#888)Florimond Mancabefore adoption3acd72a

lines 261–278why, one step back
261
262263class 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"'