Debian Codegraph @

tests/integrations/file/test_File__download.py

raw
1 import os
2 import platform
3 import shutil
4 import ssl
5 import stat
6 from collections.abc import Iterable, Iterator
7 from pathlib import Path
8 from unittest import mock
9
10 import httpcore
11 import httpx
12 import pytest
13
14 from briefcase.exceptions import (
15 BadNetworkResourceError,
16 MissingNetworkResourceError,
17 NetworkFailure,
18 )
19 from briefcase.integrations.base import ToolCache
20
21 TEMPORARY_DOWNLOAD_FILE_SUFFIX = ".download"
22
23
24 @pytest.fixture
25 def mock_tools(mock_tools) -> ToolCache:
26 mock_tools.httpx = mock.MagicMock(spec_set=httpx)
27 # Restore move so the temporary file can be moved after downloaded
28 mock_tools.shutil.move = mock.MagicMock(wraps=shutil.move)
29 return mock_tools
30
31
32 class _IteratorByteSteam(httpx.SyncByteStream):
33 """Shim that satisfies ``httpx.Response`` ``stream`` parameter type.
34
35 Cannot be replaced by any ``Iterable[bytes]`` because the base class requires
36 an explicit finalization method ``close``.
37 """
38
39 def __init__(self, iterable: Iterable[bytes]) -> None:
40 self.iterable = iterable
41
42 def __iter__(self) -> Iterator[bytes]:
43 return iter(self.iterable)
44
45
46 def _make_httpx_response(
47 *,
48 url: str,
49 status_code: int,
50 stream: list[bytes],
51 method: str = "GET",
52 headers: dict | None = None,
53 ) -> httpx.Response:
54 """Create a real ``httpx.Response`` with key methods wrapped by ``mock.Mock`` for
55 spying.
56
57 Wrapped methods:
58 response.read
59 response.iter_bytes
60 response.headers.get
61 """
62 if headers is None:
63 headers = {}
64
65 response = httpx.Response(
66 request=httpx.Request(
67 method=method,
68 url=httpx.URL(url),
69 ),
70 status_code=status_code,
71 headers=httpx.Headers(headers),
72 # Always use ``stream`` rather than content because it's more flexible
73 # even if the request is made non-streaming or the response is read with
74 # ``response.read()``, httpx will still consume the ``stream`` response
75 # content internally. This allows testing both the non-streaming and
76 # streaming download paths without needing to complicate the response params
77 stream=_IteratorByteSteam(stream),
78 )
79
80 response.read = mock.Mock(wraps=response.read)
81 response.iter_bytes = mock.Mock(wraps=response.iter_bytes)
82 response.headers.get = mock.Mock(wraps=response.headers.get)
83
84 return response
85
86
87 @pytest.fixture
88 def file_perms() -> int:
89 """The expected permissions for the downloaded file.
90
91 Since umask can vary on different systems, it is updated to a known value and reset
92 after the test finishes.
93
94 On Windows, the umask seems to always be zero and chmod doesn't really do anything
95 anyway.
96 """
97 if platform.system() == "Windows":
98 yield 0o666
99 else:
100 orig_umask = os.umask(0o077)
101 yield 0o600
102 os.umask(orig_umask)
103
104
105 @pytest.mark.parametrize(
106 ("url", "content_disposition"),
107 [
108 # A `None` value for `content_disposition` means we skip the header.
109 # Other values are passed through as HTTP header values.
110 ("https://example.com/path/to/something.zip", None),
111 # Ensure empty header is ignored.
112 ("https://example.com/path/to/something.zip", ""),
113 # Paradigmatic case for Content-Disposition: attachment.
114 (
115 "https://example.com/path/to/irrelevant.zip",
116 "attachment; filename=something.zip",
117 ),
118 # Ensure extra parameters are ignored.
119 (
120 "https://example.com/path/to/irrelevant.zip",
121 "attachment; filename=something.zip; ignored=okay",
122 ),
123 # Ensure garbage headers are ignored.
124 ("https://example.com/path/to/something.zip", "garbage"),
125 # Ensure we respect unusual quoting & case permitted by RFC 6266.
126 (
127 "https://example.com/path/to/irrelevant.zip",
128 'ATTACHment; filename= "something.zip"',
129 ),
130 # Ensure we use filename=, even if filename*= is provided. This makes us a
131 # "legacy user agent" in the terms of RFC 6266, for our own simplicity.
132 (
133 "https://example.com/path/to/irrelevant.zip",
134 'attachment; filename="something.zip"; filename*=utf-8'
135 "''%e2%82%ac%20rates",
136 ),
137 ],
138 )
139 def test_new_download_oneshot(mock_tools, file_perms, url, content_disposition):
140 """If no content-length is provided, ``File`` downloadds the file all at once."""
141 response = _make_httpx_response(
142 method="GET",
143 url=url,
144 status_code=200,
145 headers=(
146 {
147 "content-disposition": content_disposition,
148 }
149 if content_disposition is not None
150 else {}
151 ),
152 stream=[b"all content"],
153 )
154 mock_tools.httpx.stream.return_value.__enter__.return_value = response
155
156 # Download the file
157 filename = mock_tools.file.download(
158 url="https://example.com/support?useful=Yes",
159 download_path=mock_tools.base_path / "downloads",
160 )
161
162 # httpx.stream has been invoked, but content isn't iterated
163 mock_tools.httpx.stream.assert_called_with(
164 "GET",
165 "https://example.com/support?useful=Yes",
166 follow_redirects=True,
167 verify=mock_tools.file.ssl_context,
168 )
169 response.headers.get.assert_called_with("content-length")
170 response.read.assert_called_once()
171
172 # The filename is derived from the URL or header
173 assert filename == mock_tools.base_path / "downloads/something.zip"
174
175 # Temporary file was created in download dir and was renamed
176 temp_filename = Path(mock_tools.shutil.move.call_args_list[0].args[0])
177 assert temp_filename.parent == mock_tools.base_path / "downloads"
178 assert temp_filename.name.startswith("something.zip.")
179 assert temp_filename.name.endswith(TEMPORARY_DOWNLOAD_FILE_SUFFIX)
180 mock_tools.shutil.move.assert_called_with(str(temp_filename), filename)
181
182 # File permissions were set
183 mock_tools.os.chmod.assert_called_with(filename, file_perms)
184 assert stat.S_IMODE(os.stat(filename).st_mode) == file_perms
185
186 # Attempt to delete Temporary file was made
187 mock_tools.os.remove.assert_called_with(str(temp_filename))
188
189 # File content is as expected
190 with (mock_tools.base_path / "downloads/something.zip").open(encoding="utf-8") as f:
191 assert f.read() == "all content"
192
193
194 def test_new_download_chunked(mock_tools, file_perms):
195 """If a content-length is provided, ``File`` streams the response rather than
196 downloading it all at once."""
197 response = _make_httpx_response(
198 method="GET",
199 url="https://example.com/path/to/something.zip",
200 status_code=200,
201 headers={"content-length": "24"},
202 stream=[
203 b"chunk-1;",
204 b"chunk-2;",
205 b"chunk-3;",
206 ],
207 )
208 mock_tools.httpx.stream.return_value.__enter__.return_value = response
209
210 # Download the file
211 filename = mock_tools.file.download(
212 url="https://example.com/support?useful=Yes",
213 download_path=mock_tools.base_path,
214 )
215
216 # httpx.stream has been invoked, and content is chunked.
217 mock_tools.httpx.stream.assert_called_with(
218 "GET",
219 "https://example.com/support?useful=Yes",
220 follow_redirects=True,
221 verify=mock_tools.file.ssl_context,
222 )
223 response.headers.get.assert_called_with("content-length")
224 response.iter_bytes.assert_called_once_with(chunk_size=1048576)
225
226 # The filename is derived from the URL
227 assert filename == mock_tools.base_path / "something.zip"
228
229 # Temporary file was created in download dir and was renamed
230 temp_filename = Path(mock_tools.shutil.move.call_args_list[0].args[0])
231 assert temp_filename.parent == mock_tools.base_path
232 assert temp_filename.name.startswith("something.zip.")
233 assert temp_filename.name.endswith(TEMPORARY_DOWNLOAD_FILE_SUFFIX)
234 mock_tools.shutil.move.assert_called_with(str(temp_filename), filename)
235
236 # File permissions were set
237 mock_tools.os.chmod.assert_called_with(filename, file_perms)
238 assert stat.S_IMODE(os.stat(filename).st_mode) == file_perms
239
240 # Attempt to delete Temporary file was made
241 mock_tools.os.remove.assert_called_with(str(temp_filename))
242
243 # The downloaded file exists, and content is as expected
244 assert filename.exists()
245 with (mock_tools.base_path / "something.zip").open(encoding="utf-8") as f:
246 assert f.read() == "chunk-1;chunk-2;chunk-3;"
247
248
249 def test_already_downloaded(mock_tools):
250 """If the file already exists on disk, it isn't re-downloaded.
251
252 The request is still made to derive the filename, but the content is never streamed.
253 """
254
255 # Create an existing file
256 existing_file = mock_tools.base_path / "something.zip"
257 with existing_file.open("w", encoding="utf-8") as f:
258 f.write("existing content")
259
260 url = "https://example.com/path/to/something.zip"
261
262 response = _make_httpx_response(
263 status_code=200,
264 url=url,
265 # Use content and a content-encoding that would cause a DecodeError
266 # if ``File`` tried to read the response content.
267 # Because the file already exists, ``File`` shouldn't try to read
268 # the response, and the ``DecodingError`` won't occur.
269 headers={"content-length": "100", "content-encoding": "gzip"},
270 stream=[b"definitely not gzip content"],
271 )
272 mock_tools.httpx.stream.return_value.__enter__.return_value = response
273
274 # Download the file
275 filename = mock_tools.file.download(
276 url=url,
277 download_path=mock_tools.base_path,
278 )
279
280 # The GET request will have been made
281 mock_tools.httpx.stream.assert_called_with(
282 "GET",
283 url,
284 follow_redirects=True,
285 verify=mock_tools.file.ssl_context,
286 )
287
288 # The request's Content-Disposition header is consumed to
289 # examine the filename; the request is abandoned before
290 # any other headers are read.
291 response.headers.get.assert_called_once_with("Content-Disposition")
292
293 # but the file existed, so the method returns
294 assert filename == existing_file
295 assert filename.exists()
296
297 # Temporary file was not created, moved, or deleted
298 mock_tools.shutil.move.assert_not_called()
299 mock_tools.os.chmod.assert_not_called()
300 mock_tools.os.remove.assert_not_called()
301
302
303 def test_missing_resource(mock_tools):
304 """MissingNetworkResourceError raises for 404 status code."""
305 url = "https://example.com/something.zip?useful=Yes"
306 response = _make_httpx_response(
307 url=url,
308 status_code=404,
309 stream=[],
310 )
311
312 mock_tools.httpx.stream.return_value.__enter__.return_value = response
313
314 # Download the file
315 with pytest.raises(MissingNetworkResourceError):
316 mock_tools.file.download(
317 url=url,
318 download_path=mock_tools.base_path,
319 )
320
321 # httpx.stream has been invoked, but nothing else.
322 mock_tools.httpx.stream.assert_called_with(
323 "GET",
324 url,
325 follow_redirects=True,
326 verify=mock_tools.file.ssl_context,
327 )
328 response.headers.get.assert_not_called()
329
330 # The file doesn't exist as a result of the download failure
331 assert not (mock_tools.base_path / "something.zip").exists()
332
333 # Temporary file was not created, moved, or deleted
334 mock_tools.shutil.move.assert_not_called()
335 mock_tools.os.chmod.assert_not_called()
336 mock_tools.os.remove.assert_not_called()
337
338
339 def test_bad_resource(mock_tools):
340 """BadNetworkResourceError raises for non-200 status code."""
341 url = "https://example.com/something.zip?useful=Yes"
342 response = _make_httpx_response(
343 status_code=500,
344 url=url,
345 stream=[],
346 )
347
348 mock_tools.httpx.stream.return_value.__enter__.return_value = response
349
350 # Download the file
351 with pytest.raises(BadNetworkResourceError):
352 mock_tools.file.download(
353 url=url,
354 download_path=mock_tools.base_path,
355 )
356
357 # httpx.stream has been invoked, but nothing else.
358 mock_tools.httpx.stream.assert_called_with(
359 "GET",
360 url,
361 follow_redirects=True,
362 verify=mock_tools.file.ssl_context,
363 )
364 response.headers.get.assert_not_called()
365
366 # The file doesn't exist as a result of the download failure
367 assert not (mock_tools.base_path / "something.zip").exists()
368
369 # Temporary file was not created, moved, or deleted
370 mock_tools.shutil.move.assert_not_called()
371 mock_tools.os.chmod.assert_not_called()
372 mock_tools.os.remove.assert_not_called()
373
374
375 def test_iter_bytes_connection_error(mock_tools):
376 """NetworkFailure raised if response.iter_bytes() errors and cleans up temporary
377 files."""
378 url = "https://example.com/something.zip?useful=Yes"
379 response = _make_httpx_response(
380 status_code=200,
381 url=url,
382 # Force a real DecodingError by setting the response encoding to
383 # gzip with response content that is _not_ gzip
384 headers={"content-length": "100", "content-encoding": "gzip"},
385 stream=[b"definitely not gzip content"],
386 )
387 mock_tools.httpx.stream.return_value.__enter__.return_value = response
388
389 # Download the file
390 with pytest.raises(NetworkFailure, match=r"Unable to download something\.zip"):
391 mock_tools.file.download(
392 url="https://example.com/something.zip?useful=Yes",
393 download_path=mock_tools.base_path,
394 )
395
396 # httpx.stream has been invoked, but nothing else.
397 mock_tools.httpx.stream.assert_called_with(
398 "GET",
399 "https://example.com/something.zip?useful=Yes",
400 follow_redirects=True,
401 verify=mock_tools.file.ssl_context,
402 )
403 response.headers.get.assert_called_with("content-length")
404
405 # The file doesn't exist as a result of the download failure
406 assert not (mock_tools.base_path / "something.zip").exists()
407
408 # Temporary file was not moved
409 mock_tools.shutil.move.assert_not_called()
410 mock_tools.os.chmod.assert_not_called()
411
412 # Failure happens during response streaming, so the temporary file is create
413 # but then also correctly cleaned up after the failure
414 temp_filename = Path(mock_tools.os.remove.call_args_list[0].args[0])
415 assert temp_filename.parent == mock_tools.base_path
416 assert temp_filename.name.startswith("something.zip.")
417 assert temp_filename.name.endswith(TEMPORARY_DOWNLOAD_FILE_SUFFIX)
418 mock_tools.os.remove.assert_called_with(str(temp_filename))
419
420
421 def test_connection_error(mock_tools):
422 """NetworkFailure raised if the connection fails."""
423 # Use ftp scheme to force raising a real ProtocolError without needing to mock
424 url = "ftp://example.com/something.zip"
425
426 # Use the real httpx for this test instead of the MagicMock'd one from mock_tools
427 # Keep using the fixture though, so that it still gets cleaned up after the test
428 mock_tools.httpx = mock.Mock(wraps=httpx)
429
430 # Failure leads to filename never being read, so the error message will use the full URL
431 # rather than the filename
432 with pytest.raises(NetworkFailure, match=f"Unable to download {url}"):
433 mock_tools.file.download(
434 url=url,
435 download_path=mock_tools.base_path,
436 )
437
438 # httpx.stream has been invoked, but nothing else.
439 mock_tools.httpx.stream.assert_called_with(
440 "GET",
441 url,
442 follow_redirects=True,
443 verify=mock_tools.file.ssl_context,
444 )
445
446 # The file doesn't exist as a result of the download failure
447 assert not (mock_tools.base_path / "something.zip").exists()
448
449 # Temporary file was never created because the failure happens before a response
450 # is every received
451 assert not (mock_tools.base_path / "something.zip.download").exists()
452
453 # Temporary file was not created, moved, or deleted
454 mock_tools.shutil.move.assert_not_called()
455 mock_tools.os.chmod.assert_not_called()
456 mock_tools.os.remove.assert_not_called()
457
458
459 def test_redirect_connection_error(mock_tools):
460 """NetworkFailure raises if the request leads to too many redirects."""
461 mock_tools.httpx.stream.side_effect = [
462 httpx.TooManyRedirects("Exceeded max redirects")
463 ]
464
465 # Download the file
466 with pytest.raises(
467 NetworkFailure,
468 match=r"Unable to download https\:\/\/example.com\/something\.zip\?useful=Yes",
469 ):
470 mock_tools.file.download(
471 url="https://example.com/something.zip?useful=Yes",
472 download_path=mock_tools.base_path,
473 )
474
475 # httpx.stream has been invoked, but nothing else.
476 mock_tools.httpx.stream.assert_called_with(
477 "GET",
478 "https://example.com/something.zip?useful=Yes",
479 follow_redirects=True,
480 verify=mock_tools.file.ssl_context,
481 )
482
483 # The file doesn't exist as a result of the download failure
484 assert not (mock_tools.base_path / "something.zip").exists()
485
486 # Temporary file was not created, moved, or deleted
487 mock_tools.shutil.move.assert_not_called()
488 mock_tools.os.chmod.assert_not_called()
489 mock_tools.os.remove.assert_not_called()
490
491
492 def test_ssl_verification_error(mock_tools):
493 """NetworkFailure is raised if the request fails due to SSL."""
494 # Mock an SSL verification error
495 error = httpx.ConnectError("connection error")
496 error.__context__ = httpcore.ConnectError()
497 error.__context__.__context__ = ssl.SSLCertVerificationError()
498 mock_tools.httpx.stream.side_effect = [error]
499
500 # Download the file
501 with pytest.raises(
502 NetworkFailure,
503 match=(
504 r"a connection to the server could not be established "
505 r"due to a certificate verification problem"
506 ),
507 ):
508 mock_tools.file.download(
509 url="https://example.com/something.zip",
510 download_path=mock_tools.base_path,
511 )
512
513 # httpx.stream has been invoked, but nothing else.
514 mock_tools.httpx.stream.assert_called_with(
515 "GET",
516 "https://example.com/something.zip",
517 follow_redirects=True,
518 verify=mock_tools.file.ssl_context,
519 )
520
521 # The file doesn't exist as a result of the download failure
522 assert not (mock_tools.base_path / "something.zip").exists()
523
524 # Temporary file was not created, moved, or deleted
525 mock_tools.shutil.move.assert_not_called()
526 mock_tools.os.chmod.assert_not_called()
527 mock_tools.os.remove.assert_not_called()
528
529
530 def test_unknown_httpcore_connectionerror(mock_tools):
531 """NetworkFailure is raised if an unknown core connection error occurs."""
532 # Mock a connection error at the level of httpcore
533 error = httpx.ConnectError("connection error")
534 error.__context__ = httpcore.ConnectError()
535 mock_tools.httpx.stream.side_effect = [error]
536
537 # Download the file
538 with pytest.raises(
539 NetworkFailure,
540 match=(
541 r"a connection to the server could not be established.\n\n"
542 r"The reported cause of the problem "
543 ),
544 ):
545 mock_tools.file.download(
546 url="https://example.com/something.zip",
547 download_path=mock_tools.base_path,
548 )
549
550 # httpx.stream has been invoked, but nothing else.
551 mock_tools.httpx.stream.assert_called_with(
552 "GET",
553 "https://example.com/something.zip",
554 follow_redirects=True,
555 verify=mock_tools.file.ssl_context,
556 )
557
558 # The file doesn't exist as a result of the download failure
559 assert not (mock_tools.base_path / "something.zip").exists()
560
561 # Temporary file was not created, moved, or deleted
562 mock_tools.shutil.move.assert_not_called()
563 mock_tools.os.chmod.assert_not_called()
564 mock_tools.os.remove.assert_not_called()
565
566
567 def test_unknown_httpx_connectionerror(mock_tools):
568 """NetworkFailure is raised if an unknown httpx connection error occurs."""
569 # Mock a connection error at the level of httpx
570 error = httpx.ConnectError("connection error")
571 mock_tools.httpx.stream.side_effect = [error]
572
573 # Download the file
574 with pytest.raises(
575 NetworkFailure,
576 match=(
577 r"a connection to the server could not be established.\n\n"
578 r"The reported cause of the problem "
579 ),
580 ):
581 mock_tools.file.download(
582 url="https://example.com/something.zip",
583 download_path=mock_tools.base_path,
584 )
585
586 # httpx.stream has been invoked, but nothing else.
587 mock_tools.httpx.stream.assert_called_with(
588 "GET",
589 "https://example.com/something.zip",
590 follow_redirects=True,
591 verify=mock_tools.file.ssl_context,
592 )
593
594 # The file doesn't exist as a result of the download failure
595 assert not (mock_tools.base_path / "something.zip").exists()
596
597 # Temporary file was not created, moved, or deleted
598 mock_tools.shutil.move.assert_not_called()
599 mock_tools.os.chmod.assert_not_called()
600 mock_tools.os.remove.assert_not_called()