-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_download_photos_id.py
2209 lines (1958 loc) · 82.7 KB
/
test_download_photos_id.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import glob
import inspect
import logging
import os
import shutil
import sys
from typing import Any, List, NoReturn, Optional, Sequence, Tuple
from unittest import TestCase, mock
from unittest.mock import ANY, PropertyMock, call
import piexif
import pytest
from click.testing import CliRunner
from icloudpd import constants
from icloudpd.base import main
from icloudpd.string_helpers import truncate_middle
from piexif._exceptions import InvalidImageDataError
from pyicloud_ipd.asset_version import AssetVersion
from pyicloud_ipd.base import PyiCloudService
from pyicloud_ipd.exceptions import PyiCloudAPIResponseException
from pyicloud_ipd.services.photos import PhotoAlbum, PhotoAsset, PhotoLibrary
from pyicloud_ipd.version_size import AssetVersionSize, LivePhotoVersionSize
from requests import Response
from requests.exceptions import ConnectionError
from vcr import VCR
from tests.helpers import (
path_from_project_root,
print_result_exception,
recreate_path,
run_icloudpd_test,
)
vcr = VCR(decode_compressed_response=True, record_mode="none")
class DownloadPhotoNameIDTestCase(TestCase):
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog: pytest.LogCaptureFixture) -> None:
self._caplog = caplog
self.root_path = path_from_project_root(__file__)
self.fixtures_path = os.path.join(self.root_path, "fixtures")
self.vcr_path = os.path.join(self.root_path, "vcr_cassettes")
def test_download_and_skip_existing_photos_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_create = [
("2018/07/30", "IMG_7408_QVI4T2l.JPG", 1151066),
("2018/07/30", "IMG_7407_QVovd0F.JPG", 656257),
]
files_to_download = [("2018/07/31", "IMG_7409_QVk2Yyt.JPG")]
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
files_to_create,
files_to_download,
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"5",
"--skip-videos",
"--skip-live-photos",
"--set-exif-datetime",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
assert result.exit_code == 0
self.assertIn("DEBUG Looking up all photos from album All Photos...", self._caplog.text)
self.assertIn(
f"INFO Downloading 5 original photos to {data_dir} ...",
self._caplog.text,
)
for dir_name, file_name in files_to_download:
file_path = os.path.normpath(os.path.join(dir_name, file_name))
self.assertIn(
f"DEBUG Downloading {truncate_middle(os.path.join(data_dir, file_path), 96)}",
self._caplog.text,
)
self.assertNotIn(
"IMG_7409_QVk2Yyt.MOV",
self._caplog.text,
)
for dir_name, file_name in [
(dir_name, file_name) for (dir_name, file_name, _) in files_to_create
]:
file_path = os.path.normpath(os.path.join(dir_name, file_name))
self.assertIn(
f"DEBUG {truncate_middle(os.path.join(data_dir, file_path), 96)} already exists",
self._caplog.text,
)
self.assertIn(
"DEBUG Skipping IMG_7405_QVkrUjN.MOV, only downloading photos.",
self._caplog.text,
)
self.assertIn(
"DEBUG Skipping IMG_7404_QVI5TWx.MOV, only downloading photos.",
self._caplog.text,
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
# Check that file was downloaded
# Check that mtime was updated to the photo creation date
photo_mtime = os.path.getmtime(
os.path.join(data_dir, os.path.normpath("2018/07/31/IMG_7409_QVk2Yyt.JPG"))
)
photo_modified_time = datetime.datetime.fromtimestamp(photo_mtime, datetime.timezone.utc)
self.assertEqual("2018-07-31 07:22:24", photo_modified_time.strftime("%Y-%m-%d %H:%M:%S"))
def test_download_photos_and_set_exif_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_create = [
("2018/07/30", "IMG_7408_QVI4T2l.JPG", 1151066),
("2018/07/30", "IMG_7407_QVovd0F.JPG", 656257),
]
files_to_download = [
("2018/07/30", "IMG_7405_QVkrUjN.MOV"),
("2018/07/30", "IMG_7407_QVovd0F.MOV"),
("2018/07/30", "IMG_7408_QVI4T2l.MOV"),
("2018/07/31", "IMG_7409_QVk2Yyt.JPG"),
("2018/07/31", "IMG_7409_QVk2Yyt.MOV"),
]
# Download the first photo, but mock the video download
orig_download = PhotoAsset.download
def mocked_download(pa: PhotoAsset, _url: str) -> Response:
if not hasattr(PhotoAsset, "already_downloaded"):
response = orig_download(pa, _url)
setattr(PhotoAsset, "already_downloaded", True) # noqa: B010
return response
return mock.MagicMock()
with mock.patch.object(PhotoAsset, "download", new=mocked_download): # noqa: SIM117
with mock.patch("icloudpd.exif_datetime.get_photo_exif") as get_exif_patched:
get_exif_patched.return_value = False
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
files_to_create,
files_to_download,
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"4",
"--set-exif-datetime",
# '--skip-videos',
# "--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
assert result.exit_code == 0
self.assertIn(
"DEBUG Looking up all photos and videos from album All Photos...",
self._caplog.text,
)
self.assertIn(
f"INFO Downloading 4 original photos and videos to {data_dir} ...",
self._caplog.text,
)
self.assertIn(
f"DEBUG Downloading {truncate_middle(os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG')), 96)}",
self._caplog.text,
)
# 2018:07:31 07:22:24 utc
expectedDatetime = (
datetime.datetime(2018, 7, 31, 7, 22, 24, tzinfo=datetime.timezone.utc)
.astimezone()
.strftime("%Y-%m-%d %H:%M:%S%z")
)
self.assertIn(
f"DEBUG Setting EXIF timestamp for {truncate_middle(os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG')), 96)}: {expectedDatetime}",
self._caplog.text,
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
def test_download_photos_and_get_exif_exceptions_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_download = [("2018/07/31", "IMG_7409_QVk2Yyt.JPG")]
with mock.patch.object(piexif, "load") as piexif_patched:
piexif_patched.side_effect = InvalidImageDataError
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
files_to_download,
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--skip-videos",
"--skip-live-photos",
"--set-exif-datetime",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
assert result.exit_code == 0
self.assertIn("DEBUG Looking up all photos from album All Photos...", self._caplog.text)
self.assertIn(
f"INFO Downloading the first original photo to {data_dir} ...",
self._caplog.text,
)
# self.assertIn(
# f"DEBUG Downloading {os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG'))}",
# self._caplog.text,
# )
self.assertIn(
f"DEBUG Error fetching EXIF data for {os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG'))}",
self._caplog.text,
)
self.assertIn(
f"DEBUG Error setting EXIF data for {os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG'))}",
self._caplog.text,
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
def test_skip_existing_downloads_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_create = [
("2018/07/31", "IMG_7409_QVk2Yyt.JPG", 1884695),
("2018/07/31", "IMG_7409_QVk2Yyt.MOV", 3294075),
]
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
files_to_create,
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
# '--skip-videos',
# "--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
assert result.exit_code == 0
self.assertIn(
"DEBUG Looking up all photos and videos from album All Photos...", self._caplog.text
)
self.assertIn(
f"INFO Downloading the first original photo or video to {data_dir} ...",
self._caplog.text,
)
self.assertIn(
f"DEBUG {truncate_middle(os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG')), 96)} already exists",
self._caplog.text,
)
self.assertIn(
f"DEBUG {truncate_middle(os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.MOV')), 96)} already exists",
self._caplog.text,
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
def test_until_found_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_download_ext: Sequence[Tuple[str, str, str]] = [
("2018/07/31", "IMG_7409_QVk2Yyt.JPG", "photo"),
("2018/07/31", "IMG_7409_QVk2Yyt-medium.MOV", "photo"),
("2018/07/30", "IMG_7407_QVovd0F.JPG", "photo"),
("2018/07/30", "IMG_7407_QVovd0F-medium.MOV", "photo"),
("2018/07/30", "IMG_7403_QVc0VWt.MOV", "video"),
("2018/07/30", "IMG_7402_QVdYaDd.MOV", "video"),
("2018/07/30", "IMG_7399_QVVMcXN-medium.MOV", "photo"),
]
files_to_create_ext: Sequence[Tuple[str, str, str, int]] = [
("2018/07/30", "IMG_7408_QVI4T2l.JPG", "photo", 1151066),
("2018/07/30", "IMG_7408_QVI4T2l-medium.MOV", "photo", 894467),
("2018/07/30", "IMG_7405_QVkrUjN.MOV", "video", 36491351),
("2018/07/30", "IMG_7404_QVI5TWx.MOV", "video", 225935003),
# TODO large files on Windows times out
("2018/07/30", "IMG_7401_QVRJanZ.MOV", "photo", 565699696),
("2018/07/30", "IMG_7400_QVhFL01.JPG", "photo", 2308885),
("2018/07/30", "IMG_7400_QVhFL01-medium.MOV", "photo", 1238639),
("2018/07/30", "IMG_7399_QVVMcXN.JPG", "photo", 2251047),
]
files_to_create = [
(dir_name, file_name, size) for dir_name, file_name, _, size in files_to_create_ext
]
with mock.patch("icloudpd.download.download_media") as dp_patched:
dp_patched.return_value = True
with mock.patch("icloudpd.download.os.utime") as ut_patched:
ut_patched.return_value = None
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
files_to_create,
[], # we fake downloading
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--live-photo-size",
"medium",
"--until-found",
"3",
"--recent",
"20",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
expected_calls = list(
map(
lambda f: call(
ANY,
False,
ANY,
ANY,
os.path.join(data_dir, os.path.normpath(f[0]), f[1]),
ANY,
LivePhotoVersionSize.MEDIUM
if (f[2] == "photo" and f[1].endswith(".MOV"))
else AssetVersionSize.ORIGINAL,
),
files_to_download_ext,
)
)
dp_patched.assert_has_calls(expected_calls)
self.assertIn(
"DEBUG Looking up all photos and videos from album All Photos...",
self._caplog.text,
)
self.assertIn(
f"INFO Downloading ??? original photos and videos to {data_dir} ...",
self._caplog.text,
)
for s in files_to_create:
expected_message = f"DEBUG {truncate_middle(os.path.join(data_dir, os.path.normpath(s[0]), s[1]), 96)} already exists"
self.assertIn(expected_message, self._caplog.text)
for d in files_to_download_ext:
expected_message = f"DEBUG {truncate_middle(os.path.join(data_dir, os.path.normpath(d[0]), d[1]), 96)} already exists"
self.assertNotIn(expected_message, self._caplog.text)
self.assertIn(
"INFO Found 3 consecutive previously downloaded photos. Exiting",
self._caplog.text,
)
assert result.exit_code == 0
def test_handle_io_error_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
with mock.patch("icloudpd.download.open", create=True) as m:
# Raise IOError when we try to write to the destination file
m.side_effect = IOError
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--skip-videos",
"--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
self.assertIn(
"DEBUG Looking up all photos from album All Photos...", self._caplog.text
)
self.assertIn(
f"INFO Downloading the first original photo to {data_dir} ...",
self._caplog.text,
)
self.assertIn(
"ERROR IOError while writing file to "
f"{os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG'))}. "
"You might have run out of disk space, or the file might "
"be too large for your OS. Skipping this file...",
self._caplog.text,
)
assert result.exit_code == 0
def test_handle_session_error_during_download_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
def mock_raise_response_error(_arg: Any) -> NoReturn:
raise PyiCloudAPIResponseException("Invalid global session", "100")
with mock.patch("time.sleep") as sleep_mock: # noqa: SIM117
with mock.patch.object(PhotoAsset, "download") as pa_download:
pa_download.side_effect = mock_raise_response_error
# Let the initial authenticate() call succeed,
# but do nothing on the second try.
orig_authenticate = PyiCloudService.authenticate
def mocked_authenticate(self: PyiCloudService) -> None:
if not hasattr(self, "already_authenticated"):
orig_authenticate(self)
setattr(self, "already_authenticated", True) # noqa: B010
with mock.patch.object(PyiCloudService, "authenticate", new=mocked_authenticate):
# Pass fixed client ID via environment variable
_, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--skip-videos",
"--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
# Error msg should be repeated 5 times
assert self._caplog.text.count("Session error, re-authenticating...") == 5
self.assertIn(
"ERROR Could not download IMG_7409_QVk2Yyt.JPG. Please try again later.",
self._caplog.text,
)
# Make sure we only call sleep 4 times (skip the first retry)
self.assertEqual(sleep_mock.call_count, 4)
assert result.exit_code == 0
def test_handle_session_error_during_photo_iteration_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
def mock_raise_response_error(_offset: int) -> NoReturn:
raise PyiCloudAPIResponseException("Invalid global session", "100")
with mock.patch("time.sleep") as sleep_mock: # noqa: SIM117
with mock.patch.object(PhotoAlbum, "photos_request") as pa_photos_request:
pa_photos_request.side_effect = mock_raise_response_error
# Let the initial authenticate() call succeed,
# but do nothing on the second try.
orig_authenticate = PyiCloudService.authenticate
def mocked_authenticate(self: PyiCloudService) -> None:
if not hasattr(self, "already_authenticated"):
orig_authenticate(self)
setattr(self, "already_authenticated", True) # noqa: B010
with mock.patch.object(PyiCloudService, "authenticate", new=mocked_authenticate):
# Pass fixed client ID via environment variable
_, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--skip-videos",
"--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
# Error msg should be repeated 5 times
assert self._caplog.text.count("Session error, re-authenticating...") == 5
self.assertIn(
"ERROR iCloud re-authentication failed. Please try again later.",
self._caplog.text,
)
# Make sure we only call sleep 4 times (skip the first retry)
self.assertEqual(sleep_mock.call_count, 4)
assert result.exit_code == 1
def test_handle_connection_error_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
def mock_raise_response_error(_arg: Any) -> NoReturn:
raise ConnectionError("Connection Error")
with mock.patch.object(PhotoAsset, "download") as pa_download:
pa_download.side_effect = mock_raise_response_error
# Let the initial authenticate() call succeed,
# but do nothing on the second try.
orig_authenticate = PyiCloudService.authenticate
def mocked_authenticate(self: PyiCloudService) -> None:
if not hasattr(self, "already_authenticated"):
orig_authenticate(self)
setattr(self, "already_authenticated", True) # noqa: B010
with mock.patch("icloudpd.constants.WAIT_SECONDS", 0): # noqa: SIM117
with mock.patch.object(PyiCloudService, "authenticate", new=mocked_authenticate):
_, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--skip-videos",
"--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
# Error msg should be repeated 5 times
assert (
self._caplog.text.count(
"Error downloading IMG_7409_QVk2Yyt.JPG, retrying after 0 seconds..."
)
== 5
)
self.assertIn(
"ERROR Could not download IMG_7409_QVk2Yyt.JPG. Please try again later.",
self._caplog.text,
)
assert result.exit_code == 0
def test_handle_albums_error_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
def mock_raise_response_error() -> None:
raise PyiCloudAPIResponseException("Api Error", "100")
with mock.patch.object(PhotoLibrary, "_fetch_folders") as pa_photos_request:
pa_photos_request.side_effect = mock_raise_response_error
# Let the initial authenticate() call succeed,
# but do nothing on the second try.
orig_authenticate = PyiCloudService.authenticate
def mocked_authenticate(self: PyiCloudService) -> None:
if not hasattr(self, "already_authenticated"):
orig_authenticate(self)
setattr(self, "already_authenticated", True) # noqa: B010
with mock.patch("icloudpd.constants.WAIT_SECONDS", 0): # noqa: SIM117
with mock.patch.object(PyiCloudService, "authenticate", new=mocked_authenticate):
_, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--skip-videos",
"--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
assert result.exit_code == 1
def test_missing_size_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
with mock.patch.object(PhotoAsset, "download") as pa_download:
pa_download.return_value = False
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"3",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
self.assertIn(
"DEBUG Looking up all photos and videos from album All Photos...",
self._caplog.text,
)
self.assertIn(
f"INFO Downloading 3 original photos and videos to {data_dir} ...",
self._caplog.text,
)
# These error messages should not be repeated more than once for each size
for filename in [
"IMG_7409_QVk2Yyt.JPG",
"IMG_7408_QVI4T2l.JPG",
"IMG_7407_QVovd0F.JPG",
]:
for size in ["original"]:
self.assertEqual(
sum(
1
for line in self._caplog.text.splitlines()
if line
== f"ERROR Could not find URL to download {filename} for size {size}"
),
1,
f"Errors for {filename} size {size}",
)
for filename in [
"IMG_7409_QVk2Yyt.MOV",
"IMG_7408_QVI4T2l.MOV",
"IMG_7407_QVovd0F.MOV",
]:
for size in ["originalVideo"]:
self.assertEqual(
sum(
1
for line in self._caplog.text.splitlines()
if line
== f"ERROR Could not find URL to download {filename} for size {size}"
),
1,
f"Errors for {filename} size {size}",
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
self.assertEqual(result.exit_code, 0, "Exit code")
def test_size_fallback_to_original_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
with mock.patch("icloudpd.download.download_media") as dp_patched:
dp_patched.return_value = True
with mock.patch("icloudpd.download.os.utime") as ut_patched:
ut_patched.return_value = None
with mock.patch.object(
PhotoAsset, "versions", new_callable=mock.PropertyMock
) as pa:
pa.return_value = {
AssetVersionSize.ORIGINAL: AssetVersion(
"IMG_7409_QVk2Yyt.JPG", 1, "http", "jpeg"
),
AssetVersionSize.MEDIUM: AssetVersion(
"IMG_7409_QVk2Yyt.JPG", 2, "ftp", "movie"
),
}
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--size",
"thumb",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
self.assertIn(
"DEBUG Looking up all photos and videos from album All Photos...",
self._caplog.text,
)
self.assertIn(
f"INFO Downloading the first thumb photo or video to {data_dir} ...",
self._caplog.text,
)
self.assertIn(
f"DEBUG Downloading {truncate_middle(os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG')), 96)}",
self._caplog.text,
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
dp_patched.assert_called_once_with(
ANY,
False,
ANY,
ANY,
f"{os.path.join(data_dir, os.path.normpath('2018/07/31/IMG_7409_QVk2Yyt.JPG'))}",
ANY,
AssetVersionSize.ORIGINAL,
)
assert result.exit_code == 0
def test_force_size_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
with mock.patch("icloudpd.download.download_media") as dp_patched:
dp_patched.return_value = True
with mock.patch.object(PhotoAsset, "versions", new_callable=PropertyMock) as pa:
pa.return_value = {
AssetVersionSize.ORIGINAL: {"filename": "IMG1.JPG"},
AssetVersionSize.MEDIUM: {"filename": "IMG_1.JPG"},
}
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
[],
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--size",
"thumb",
"--force-size",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
self.assertIn(
"DEBUG Looking up all photos and videos from album All Photos...",
self._caplog.text,
)
self.assertIn(
f"INFO Downloading the first thumb photo or video to {data_dir} ...",
self._caplog.text,
)
self.assertIn(
"ERROR thumb size does not exist for IMG_7409_QVk2Yyt.JPG. Skipping...",
self._caplog.text,
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
dp_patched.assert_not_called()
assert result.exit_code == 0
def test_invalid_creation_date_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_download = [("2018/01/01", "IMG_7409_QVk2Yyt.JPG")]
with mock.patch.object(PhotoAsset, "created", new_callable=mock.PropertyMock) as dt_mock:
# Can't mock `astimezone` because it's a readonly property, so have to
# create a new class that inherits from datetime.datetime
class NewDateTime(datetime.datetime):
def astimezone(self, _tz: (Optional[Any]) = None) -> NoReturn:
raise ValueError("Invalid date")
dt_mock.return_value = NewDateTime(2018, 1, 1, 0, 0, 0)
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
files_to_download,
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
self.assertIn(
"DEBUG Looking up all photos and videos from album All Photos...",
self._caplog.text,
)
self.assertIn(
f"INFO Downloading the first original photo or video to {data_dir} ...",
self._caplog.text,
)
self.assertIn(
"ERROR Could not convert photo created date to local timezone (2018-01-01 00:00:00)",
self._caplog.text,
)
self.assertIn(
f"DEBUG Downloading {truncate_middle(os.path.join(data_dir, os.path.normpath('2018/01/01/IMG_7409_QVk2Yyt.JPG')), 96)}",
self._caplog.text,
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
assert result.exit_code == 0
@pytest.mark.skipif(sys.platform == "win32", reason="does not run on windows")
@pytest.mark.skipif(sys.platform == "darwin", reason="does not run on mac")
def test_invalid_creation_year_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_download = [("5/01/01", "IMG_7409_QVk2Yyt.JPG")]
with mock.patch.object(PhotoAsset, "created", new_callable=mock.PropertyMock) as dt_mock:
# Can't mock `astimezone` because it's a readonly property, so have to
# create a new class that inherits from datetime.datetime
class NewDateTime(datetime.datetime):
def astimezone(self, _tz: (Optional[Any]) = None) -> NoReturn:
raise ValueError("Invalid date")
dt_mock.return_value = NewDateTime(5, 1, 1, 0, 0, 0)
data_dir, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos.yml",
[],
files_to_download,
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--skip-live-photos",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
],
)
self.assertIn(
"DEBUG Looking up all photos and videos from album All Photos...",
self._caplog.text,
)
self.assertIn(
f"INFO Downloading the first original photo or video to {data_dir} ...",
self._caplog.text,
)
self.assertIn(
"ERROR Could not convert photo created date to local timezone (0005-01-01 00:00:00)",
self._caplog.text,
)
self.assertIn(
f"DEBUG Downloading {truncate_middle(os.path.join(data_dir, os.path.normpath('5/01/01/IMG_7409_QVk2Yyt.JPG')), 96)}",
self._caplog.text,
)
self.assertIn("INFO All photos have been downloaded", self._caplog.text)
assert result.exit_code == 0
def test_missing_item_type_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_download = [
("2018/07/31", "IMG_7409_QVk2Yyt.JPG"),
]
_, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos_missing_item_type.yml",
[],
files_to_download,
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",
"--recent",
"1",
"--no-progress-bar",
"--file-match-policy",
"name-id7",
"--skip-live-photos",
],
)
assert result.exit_code == 0
def test_missing_item_type_value_name_id7(self) -> None:
base_dir = os.path.join(self.fixtures_path, inspect.stack()[0][3])
files_to_download = [
("2018/07/31", "IMG_7409_QVk2Yyt.JPG"),
]
_, result = run_icloudpd_test(
self.assertEqual,
self.root_path,
base_dir,
"listing_photos_missing_item_type_value.yml",
[],
files_to_download,
[
"--username",
"jdoe@gmail.com",
"--password",
"password1",