File: test_create.py

package info (click to toggle)
python-briefcase 0.3.25-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 7,596 kB
  • sloc: python: 62,519; makefile: 60
file content (1294 lines) | stat: -rw-r--r-- 45,078 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
from subprocess import CalledProcessError
from unittest import mock

import pytest

from briefcase.exceptions import BriefcaseCommandError, RequirementsInstallError
from briefcase.integrations.subprocess import Subprocess
from briefcase.platforms.macOS.app import macOSAppCreateCommand

from ....utils import (
    create_file,
    create_installed_package,
    create_plist_file,
    mock_tgz_download,
)


@pytest.fixture
def create_command(dummy_console, tmp_path, first_app_templated):
    command = macOSAppCreateCommand(
        console=dummy_console,
        base_path=tmp_path / "base_path",
        data_path=tmp_path / "briefcase",
    )

    # mock subprocess app context for this app
    command.tools[first_app_templated].app_context = mock.MagicMock(spec_set=Subprocess)
    command.generate_template = mock.MagicMock()
    command.verify_not_on_icloud = mock.MagicMock()

    return command


@pytest.mark.parametrize(
    "permissions, info, entitlements, context",
    [
        # No permissions
        (
            {},
            {},
            {},
            {
                "info": {},
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                },
            },
        ),
        # Only custom permissions
        (
            {},
            {
                "NSCustomPermission": "Custom message",
            },
            {
                "com.apple.vm.networking": True,
            },
            {
                "info": {
                    "NSCustomPermission": "Custom message",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.vm.networking": True,
                },
            },
        ),
        # Camera permissions
        (
            {
                "camera": "I need to see you",
            },
            {},
            {},
            {
                "info": {
                    "NSCameraUsageDescription": "I need to see you",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.device.camera": True,
                },
            },
        ),
        # Microphone permissions
        (
            {
                "microphone": "I need to hear you",
            },
            {},
            {},
            {
                "info": {
                    "NSMicrophoneUsageDescription": "I need to hear you",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.device.microphone": True,
                },
            },
        ),
        # Coarse location permissions
        (
            {
                "coarse_location": "I need to know roughly where you are",
            },
            {},
            {},
            {
                "info": {
                    "NSLocationUsageDescription": "I need to know roughly where you are",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.personal-information.location": True,
                },
            },
        ),
        # Fine location permissions
        (
            {
                "fine_location": "I need to know exactly where you are",
            },
            {},
            {},
            {
                "info": {
                    "NSLocationUsageDescription": "I need to know exactly where you are",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.personal-information.location": True,
                },
            },
        ),
        # Background location permissions
        (
            {
                "background_location": "I always need to know where you are",
            },
            {},
            {},
            {
                "info": {
                    "NSLocationUsageDescription": "I always need to know where you are",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.personal-information.location": True,
                },
            },
        ),
        # Coarse location background permissions
        (
            {
                "coarse_location": "I need to know roughly where you are",
                "background_location": "I always need to know where you are",
            },
            {},
            {},
            {
                "info": {
                    "NSLocationUsageDescription": "I always need to know where you are",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.personal-information.location": True,
                },
            },
        ),
        # Fine location background permissions
        (
            {
                "fine_location": "I need to know exactly where you are",
                "background_location": "I always need to know where you are",
            },
            {},
            {},
            {
                "info": {
                    "NSLocationUsageDescription": "I always need to know where you are",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.personal-information.location": True,
                },
            },
        ),
        # Coarse and fine location permissions
        (
            {
                "coarse_location": "I need to know roughly where you are",
                "fine_location": "I need to know exactly where you are",
            },
            {},
            {},
            {
                "info": {
                    "NSLocationUsageDescription": "I need to know exactly where you are",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.personal-information.location": True,
                },
            },
        ),
        # Coarse and fine background location permissions
        (
            {
                "coarse_location": "I need to know roughly where you are",
                "fine_location": "I need to know exactly where you are",
                "background_location": "I always need to know where you are",
            },
            {},
            {},
            {
                "info": {
                    "NSLocationUsageDescription": "I always need to know where you are",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.personal-information.location": True,
                },
            },
        ),
        # Photo library permissions
        (
            {
                "photo_library": "I need to see your library",
            },
            {},
            {},
            {
                "info": {
                    "NSPhotoLibraryUsageDescription": "I need to see your library",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": True,
                    "com.apple.security.personal-information.photo_library": True,
                },
            },
        ),
        # Override and augment by cross-platform definitions
        (
            {
                "fine_location": "I need to know where you are",
            },
            {
                "NSCustomMessage": "Custom message",
                "NSLocationUsageDescription": "Platform specific",
            },
            {
                "com.apple.security.personal-information.location": False,
                "com.apple.security.cs.disable-library-validation": False,
                "com.apple.vm.networking": True,
            },
            {
                "info": {
                    "NSLocationUsageDescription": "Platform specific",
                    "NSCustomMessage": "Custom message",
                },
                "entitlements": {
                    "com.apple.security.cs.allow-unsigned-executable-memory": True,
                    "com.apple.security.cs.disable-library-validation": False,
                    "com.apple.security.personal-information.location": False,
                    "com.apple.vm.networking": True,
                },
            },
        ),
    ],
)
def test_permissions_context(
    create_command, first_app, permissions, info, entitlements, context
):
    """Platform-specific permissions can be added to the context."""
    # Set the permission, info and entitlement values
    first_app.permission = permissions
    first_app.info = info
    first_app.entitlement = entitlements
    # Extract the cross-platform permissions
    x_permissions = create_command._x_permissions(first_app)
    # Check that the final platform permissions are rendered as expected.
    assert context == create_command.permissions_context(first_app, x_permissions)


def test_generate_app_template(create_command, first_app, tmp_path):
    """After the app is generated, the location is checked for iCloud markers."""
    create_command.generate_app_template(first_app)

    # The template was generated. Check some basic details, but not the full context.
    create_command.generate_template.assert_called_once_with(
        template="https://github.com/beeware/briefcase-macOS-app-template.git",
        branch=None,
        output_path=tmp_path / "base_path/build/first-app/macos",
        extra_context=mock.ANY,
    )

    # iCloud was verified, with cleanup.
    create_command.verify_not_on_icloud.assert_called_once_with(first_app, cleanup=True)


def test_generate_app_template_formal_name_mismatch(
    create_command, first_app, tmp_path
):
    """If the app's formal name doesn't match the external package path, an error is
    raised."""
    first_app.external_package_path = "output/Unexpected Name.app"

    with pytest.raises(
        BriefcaseCommandError,
        match=(
            r"The app bundle referenced by external_package_path \(Unexpected Name.app\)\n"
            r"does not match the formal name of the app \('First App'\)."
        ),
    ):
        create_command.generate_app_template(first_app)

    # The template was not generated.
    create_command.generate_template.assert_not_called()

    # iCloud was not verified either.
    create_command.verify_not_on_icloud.assert_not_called()


def test_install_app_resources(create_command, first_app_templated, tmp_path):
    """The app bundle's modification time is updated when app resources are
    installed."""
    # Get the initial app modification time
    initial_timestamp = os.path.getmtime(
        create_command.binary_path(first_app_templated)
    )

    # Add a small sleep to make sure that a touch will definitely result in an updated
    # modification time
    time.sleep(0.1)

    # Install resources
    create_command.install_app_resources(first_app_templated)

    # Modification time has been updated, and is newer
    assert (
        os.path.getmtime(create_command.binary_path(first_app_templated))
        > initial_timestamp
    )


@pytest.mark.parametrize(
    "host_arch, other_arch",
    [
        ("arm64", "x86_64"),
        ("x86_64", "arm64"),
    ],
)
def test_install_app_packages(
    create_command,
    first_app_templated,
    tmp_path,
    host_arch,
    other_arch,
):
    """A 2-pass install of app packages is performed."""
    bundle_path = tmp_path / "base_path/build/first-app/macos/app"

    create_command.tools.host_arch = host_arch
    first_app_templated.requires = ["first", "second==1.2.3", "third>=3.2.1"]

    # Mock the result of finding the binary packages - 2 of the packages are binary;
    # the version on the loosely specified package doesn't match the lower bound.
    create_command.find_binary_packages = mock.Mock(
        return_value=[
            ("second", "1.2.3"),
            ("third", "3.4.5"),
        ]
    )

    # Mock the thin command so we can confirm it was invoked.
    create_command.thin_app_packages = mock.Mock()

    # Mock the merge command so we can confirm it was invoked.
    create_command.merge_app_packages = mock.Mock()

    create_command.install_app_requirements(first_app_templated)

    # We looked for binary packages in the host app_packages
    create_command.find_binary_packages.assert_called_once_with(
        bundle_path / f"app_packages.{host_arch}",
        universal_suffix="_universal2",
    )

    # A request was made to install requirements
    assert create_command.tools[first_app_templated].app_context.run.mock_calls == [
        # First call is to install the initial packages on the host arch
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / ('app_packages.' + host_arch)}",
                "--only-binary",
                ":all:",
                "--platform",
                f"macosx_10_12_{host_arch}",
                "first",
                "second==1.2.3",
                "third>=3.2.1",
            ],
            check=True,
            encoding="UTF-8",
        ),
        # Second call installs the binary packages for the other architecture.
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / ('app_packages.' + other_arch)}",
                "--no-deps",
                "--platform",
                f"macosx_10_12_{other_arch}",
                "--only-binary",
                ":all:",
                "second==1.2.3",
                "third==3.4.5",
            ],
            check=True,
            encoding="UTF-8",
        ),
    ]

    # The app packages folder has been created. The existence of the target and host
    # versions is validated as a result of the underlying install/merge methods.
    assert (bundle_path / f"app_packages.{other_arch}").is_dir()

    # An attempt was made thin the "other" arch packages.
    create_command.thin_app_packages.assert_called_once_with(
        bundle_path / f"app_packages.{other_arch}",
        arch=other_arch,
    )

    # An attempt was made to merge packages.
    create_command.merge_app_packages.assert_called_once_with(
        target_app_packages=bundle_path
        / "First App.app"
        / "Contents"
        / "Resources"
        / "app_packages",
        sources=[
            bundle_path / f"app_packages.{host_arch}",
            bundle_path / f"app_packages.{other_arch}",
        ],
    )


@pytest.mark.parametrize("old_config", [True, False])
def test_min_os_version(create_command, first_app_templated, old_config, tmp_path):
    """If the app specifies a min OS version, it is used for wheel installs."""
    create_command.tools.host_arch = "arm64"

    if old_config:
        # Old support packages didn't contain an XCframework; but they did have a
        # VERSIONS file. Delete the xcframework, and create the support package VERSIONS
        # file with a deliberately weird min macOS version
        shutil.rmtree(
            tmp_path / "base_path/build/first-app/macos/app/support/Python.xcframework"
        )
        create_file(
            tmp_path / "base_path/build/first-app/macos/app/support/VERSIONS",
            "\n".join(
                [
                    "Python version: 3.10.15",
                    "Build: b11",
                    "Min macOS version: 10.12",
                    "",
                ]
            ),
        )

    bundle_path = tmp_path / "base_path/build/first-app/macos/app"

    first_app_templated.requires = ["first", "second==1.2.3", "third>=3.2.1"]

    # Set a minimum OS version.
    first_app_templated.min_os_version = "13.2"

    # Mock the result of finding the binary packages - 2 of the packages are binary;
    # the version on the loosely specified package doesn't match the lower bound.
    create_command.find_binary_packages = mock.Mock(
        return_value=[
            ("second", "1.2.3"),
            ("third", "3.4.5"),
        ]
    )

    # Mock the thin command so we can confirm it was invoked.
    create_command.thin_app_packages = mock.Mock()

    # Mock the merge command so we can confirm it was invoked.
    create_command.merge_app_packages = mock.Mock()

    create_command.install_app_requirements(first_app_templated)

    # We looked for binary packages in the host app_packages
    create_command.find_binary_packages.assert_called_once_with(
        bundle_path / "app_packages.arm64",
        universal_suffix="_universal2",
    )

    # A request was made to install requirements
    assert create_command.tools[first_app_templated].app_context.run.mock_calls == [
        # First call is to install the initial packages on the host arch
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / 'app_packages.arm64'}",
                "--only-binary",
                ":all:",
                "--platform",
                "macosx_13_2_arm64",
                "first",
                "second==1.2.3",
                "third>=3.2.1",
            ],
            check=True,
            encoding="UTF-8",
        ),
        # Second call installs the binary packages for the other architecture.
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / 'app_packages.x86_64'}",
                "--no-deps",
                "--platform",
                "macosx_13_2_x86_64",
                "--only-binary",
                ":all:",
                "second==1.2.3",
                "third==3.4.5",
            ],
            check=True,
            encoding="UTF-8",
        ),
    ]

    # The app packages folder has been created. The existence of the target and host
    # versions is validated as a result of the underlying install/merge methods.
    assert (bundle_path / "app_packages.x86_64").is_dir()

    # An attempt was made thin the "other" arch packages.
    create_command.thin_app_packages.assert_called_once_with(
        bundle_path / "app_packages.x86_64",
        arch="x86_64",
    )

    # An attempt was made to merge packages.
    create_command.merge_app_packages.assert_called_once_with(
        target_app_packages=bundle_path
        / "First App.app"
        / "Contents"
        / "Resources"
        / "app_packages",
        sources=[
            bundle_path / "app_packages.arm64",
            bundle_path / "app_packages.x86_64",
        ],
    )


@pytest.mark.parametrize("old_config", [True, False])
def test_default_min_os_version(
    create_command,
    first_app_templated,
    old_config,
    tmp_path,
):
    """If the support package doesn't specify a min OS version, a default is used."""
    create_command.tools.host_arch = "arm64"

    if old_config:
        # Old support packages didn't contain an XCframework; but they did have a
        # VERSIONS file. Delete the xcframework, and create the support package VERSIONS
        # file with *no* min macOS version
        shutil.rmtree(
            tmp_path / "base_path/build/first-app/macos/app/support/Python.xcframework"
        )
        create_file(
            tmp_path / "base_path/build/first-app/macos/app/support/VERSIONS",
            "\n".join(
                [
                    "Python version: 3.10.15",
                    "Build: b11",
                    "",
                ]
            ),
        )
    else:
        # Replace the framework plist file with one without a min OS version.
        framework_plist = (
            tmp_path
            / "base_path/build/first-app/macos/app/support/Python.xcframework"
            / "macos-arm64_x86_64/Python.framework/Resources/Info.plist"
        )
        framework_plist.unlink()
        create_plist_file(
            framework_plist,
            {
                "CFBundleVersion": "3.10.15",
            },
        )

    bundle_path = tmp_path / "base_path/build/first-app/macos/app"

    first_app_templated.requires = ["first", "second==1.2.3", "third>=3.2.1"]

    # Mock the result of finding the binary packages - 2 of the packages are binary;
    # the version on the loosely specified package doesn't match the lower bound.
    create_command.find_binary_packages = mock.Mock(
        return_value=[
            ("second", "1.2.3"),
            ("third", "3.4.5"),
        ]
    )

    # Mock the thin command so we can confirm it was invoked.
    create_command.thin_app_packages = mock.Mock()

    # Mock the merge command so we can confirm it was invoked.
    create_command.merge_app_packages = mock.Mock()

    create_command.install_app_requirements(first_app_templated)

    # We looked for binary packages in the host app_packages
    create_command.find_binary_packages.assert_called_once_with(
        bundle_path / "app_packages.arm64",
        universal_suffix="_universal2",
    )

    # A request was made to install requirements
    assert create_command.tools[first_app_templated].app_context.run.mock_calls == [
        # First call is to install the initial packages on the host arch
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / 'app_packages.arm64'}",
                "--only-binary",
                ":all:",
                "--platform",
                "macosx_11_0_arm64",
                "first",
                "second==1.2.3",
                "third>=3.2.1",
            ],
            check=True,
            encoding="UTF-8",
        ),
        # Second call installs the binary packages for the other architecture.
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / 'app_packages.x86_64'}",
                "--no-deps",
                "--platform",
                "macosx_11_0_x86_64",
                "--only-binary",
                ":all:",
                "second==1.2.3",
                "third==3.4.5",
            ],
            check=True,
            encoding="UTF-8",
        ),
    ]

    # The app packages folder has been created. The existence of the target and host
    # versions is validated as a result of the underlying install/merge methods.
    assert (bundle_path / "app_packages.x86_64").is_dir()

    # An attempt was made thin the "other" arch packages.
    create_command.thin_app_packages.assert_called_once_with(
        bundle_path / "app_packages.x86_64",
        arch="x86_64",
    )

    # An attempt was made to merge packages.
    create_command.merge_app_packages.assert_called_once_with(
        target_app_packages=bundle_path
        / "First App.app"
        / "Contents"
        / "Resources"
        / "app_packages",
        sources=[
            bundle_path / "app_packages.arm64",
            bundle_path / "app_packages.x86_64",
        ],
    )


def test_invalid_min_os_version(create_command, first_app_templated):
    """If the app defines a min OS version that is incompatible with the support
    package, an error is raised."""
    first_app_templated.requires = ["first", "second==1.2.3", "third>=3.2.1"]

    # Set a min OS version that is incompatible with the support package.
    first_app_templated.min_os_version = "10.6"

    with pytest.raises(
        BriefcaseCommandError,
        match=(
            r"Your macOS app specifies a minimum macOS version of 10.6, "
            r"but the support package only supports 10.12"
        ),
    ):
        create_command.install_app_requirements(first_app_templated)

    # No request was made to install requirements
    create_command.tools[first_app_templated].app_context.run.assert_not_called()


@pytest.mark.parametrize(
    "host_arch, other_arch",
    [
        ("arm64", "x86_64"),
        ("arm64", "x86_64"),
    ],
)
def test_install_app_packages_no_binary(
    create_command,
    first_app_templated,
    tmp_path,
    host_arch,
    other_arch,
):
    """If there's no binaries in the first pass, the second pass isn't performed."""
    bundle_path = tmp_path / "base_path/build/first-app/macos/app"

    # Create pre-existing other-arch content
    create_installed_package(bundle_path / f"app_packages.{other_arch}", "legacy")

    create_command.tools.host_arch = host_arch
    first_app_templated.requires = ["first", "second==1.2.3", "third>=3.2.1"]

    # Mock the result of finding no binary packages.
    create_command.find_binary_packages = mock.Mock(return_value=[])

    # Mock the thin command so we can confirm it was invoked.
    create_command.thin_app_packages = mock.Mock()

    # Mock the merge command so we can confirm it was invoked.
    create_command.merge_app_packages = mock.Mock()

    create_command.install_app_requirements(first_app_templated)

    # We looked for binary packages in the host app_packages
    create_command.find_binary_packages.assert_called_once_with(
        bundle_path / f"app_packages.{host_arch}",
        universal_suffix="_universal2",
    )

    # A request was made to install requirements
    assert create_command.tools[first_app_templated].app_context.run.mock_calls == [
        # Only call is to install the initial packages on the host arch
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / ('app_packages.' + host_arch)}",
                "--only-binary",
                ":all:",
                "--platform",
                f"macosx_10_12_{host_arch}",
                "first",
                "second==1.2.3",
                "third>=3.2.1",
            ],
            check=True,
            encoding="UTF-8",
        ),
    ]

    # The app packages folder for the other architecture has been created, even though
    # it isn't needed. The existence of the target and host versions is validated as a
    # result of the underlying install/merge methods.
    assert (bundle_path / f"app_packages.{other_arch}").is_dir()

    # We still need to thin and merge the app packages; this is effectively just a copy.
    create_command.thin_app_packages.assert_called_once_with(
        bundle_path / f"app_packages.{other_arch}",
        arch=other_arch,
    )
    create_command.merge_app_packages.assert_called_once_with(
        target_app_packages=bundle_path
        / "First App.app"
        / "Contents"
        / "Resources"
        / "app_packages",
        sources=[
            bundle_path / f"app_packages.{host_arch}",
            bundle_path / f"app_packages.{other_arch}",
        ],
    )


def test_install_app_packages_failure(create_command, first_app_templated, tmp_path):
    """If the install of other-arch binaries fails, an exception is raised."""
    bundle_path = tmp_path / "base_path/build/first-app/macos/app"

    # Create pre-existing other-arch content
    create_installed_package(bundle_path / "app_packages.x86_64", "legacy")

    create_command.tools.host_arch = "arm64"
    first_app_templated.requires = ["first", "second==1.2.3", "third>=3.2.1"]

    # Mock the result of finding the binary packages - 2 of the packages are binary;
    # the version on the loosely specified package doesn't match the lower bound.
    create_command.find_binary_packages = mock.Mock(
        return_value=[
            ("second", "1.2.3"),
            ("third", "3.4.5"),
        ]
    )

    # Mock the thin command so we can confirm it was invoked.
    create_command.thin_app_packages = mock.Mock()

    # Mock the merge command so we can confirm it was invoked.
    create_command.merge_app_packages = mock.Mock()

    # Mock a failure on the second install
    create_command.tools[first_app_templated].app_context.run.side_effect = [
        None,
        subprocess.CalledProcessError(returncode=1, cmd="pip"),
    ]

    # Install the requirements; this will raise an error
    with pytest.raises(
        BriefcaseCommandError,
        match=(
            r"Unable to install requirements\. This may be because one of your\n"
            r"requirements is invalid, or because pip was unable to connect\n"
            r"to the PyPI server.\n"
        ),
    ):
        create_command.install_app_requirements(first_app_templated)

    # We looked for binary packages in the host app_packages
    create_command.find_binary_packages.assert_called_once_with(
        bundle_path / "app_packages.arm64",
        universal_suffix="_universal2",
    )

    # A request was made to install requirements
    assert create_command.tools[first_app_templated].app_context.run.mock_calls == [
        # First call is to install the initial packages on the host arch
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / 'app_packages.arm64'}",
                "--only-binary",
                ":all:",
                "--platform",
                "macosx_10_12_arm64",
                "first",
                "second==1.2.3",
                "third>=3.2.1",
            ],
            check=True,
            encoding="UTF-8",
        ),
        # Second call installs the binary packages for the other architecture;
        # this is the call that failed.
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / 'app_packages.x86_64'}",
                "--no-deps",
                "--platform",
                "macosx_10_12_x86_64",
                "--only-binary",
                ":all:",
                "second==1.2.3",
                "third==3.4.5",
            ],
            check=True,
            encoding="UTF-8",
        ),
    ]

    # The app packages folder for the other architecture has been created, even though
    # it isn't needed. The existence of the target and host versions is validated as a
    # result of the underlying install/merge methods.
    assert (bundle_path / "app_packages.x86_64").is_dir()

    # We didn't attempt to thin or  merge, because we didn't complete installing.
    create_command.thin_app_packages.assert_not_called()
    create_command.merge_app_packages.assert_not_called()


@pytest.mark.parametrize(
    "host_arch, other_arch",
    [
        ("arm64", "x86_64"),
        ("arm64", "x86_64"),
    ],
)
def test_install_app_packages_non_universal(
    create_command,
    first_app_templated,
    tmp_path,
    host_arch,
    other_arch,
):
    """If the app is non-universal, only a single install pass occurs, followed by
    thinning."""
    bundle_path = tmp_path / "base_path/build/first-app/macos/app"

    create_command.tools.host_arch = host_arch
    first_app_templated.requires = ["first", "second==1.2.3", "third>=3.2.1"]
    first_app_templated.universal_build = False

    # Mock the find_binary_packages command so we can confirm it wasn't invoked.
    create_command.find_binary_packages = mock.Mock()

    # Mock the thin command so we can confirm it was invoked.
    create_command.thin_app_packages = mock.Mock()

    # Mock the merge command so we can confirm it wasn't invoked.
    create_command.merge_app_packages = mock.Mock()

    create_command.install_app_requirements(first_app_templated)

    # We didn't search for binary packages
    create_command.find_binary_packages.assert_not_called()

    # One request was made to install requirements
    assert create_command.tools[first_app_templated].app_context.run.mock_calls == [
        mock.call(
            [
                sys.executable,
                "-u",
                "-X",
                "utf8",
                "-m",
                "pip",
                "install",
                "--disable-pip-version-check",
                "--upgrade",
                "--no-user",
                f"--target={bundle_path / 'First App.app' / 'Contents' / 'Resources' / 'app_packages'}",
                "--only-binary",
                ":all:",
                "--platform",
                f"macosx_10_12_{host_arch}",
                "first",
                "second==1.2.3",
                "third>=3.2.1",
            ],
            check=True,
            encoding="UTF-8",
        ),
    ]

    # An attempt was made to thin the app packages
    create_command.thin_app_packages.assert_called_once_with(
        bundle_path / "First App.app/Contents/Resources/app_packages",
        arch=host_arch,
    )

    # No attempt was made to merge packages.
    create_command.merge_app_packages.assert_not_called()


@pytest.mark.parametrize("pre_existing", [True, False])
def test_install_legacy_support_package(
    create_command,
    first_app_templated,
    tmp_path,
    pre_existing,
):
    """The legacy location for the standard library is used by default when installing
    the support package."""
    # Hard code the support revision
    first_app_templated.support_revision = "37"

    # Rewrite the app's briefcase.toml to use the legacy paths (i.e.,
    # a support path of Resources/support, and no stdlib_path)
    create_file(
        tmp_path / "base_path/build/first-app/macos/app/briefcase.toml",
        """
[paths]
app_packages_path="First App.app/Contents/Resources/app_packages"
support_path="First App.app/Contents/Resources/support"
info_plist_path="First App.app/Contents/Info.plist"
entitlements_path="Entitlements.plist"
""",
    )

    bundle_path = tmp_path / "base_path/build/first-app/macos/app"
    runtime_support_path = bundle_path / "First App.app/Contents/Resources/support"

    if pre_existing:
        create_file(
            runtime_support_path / "python-stdlib/old-stdlib",
            "old stdlib file",
        )

    # Mock download.file to return a support package
    create_command.tools.file.download = mock.MagicMock(
        side_effect=mock_tgz_download(
            f"Python-3.{sys.version_info.minor}-macOS-support.b37.tar.gz",
            [
                ("python-stdlib/stdlib.txt", "this is the standard library"),
                (
                    "platform-site/macosx.arm64/sitecustomize.py",
                    "this is the arm64 platform site",
                ),
                (
                    "platform-site/macosx.x86_64/sitecustomize.py",
                    "this is the x86_64 platform site",
                ),
                ("Python.xcframework/info.plist", "this is the xcframework"),
            ],
        )
    )

    # Install the support package
    create_command.install_app_support_package(first_app_templated)

    # Confirm that the support files have been unpacked into the bundle location
    assert (bundle_path / "support/python-stdlib/stdlib.txt").exists()
    assert (
        bundle_path / "support/platform-site/macosx.arm64/sitecustomize.py"
    ).exists()
    assert (
        bundle_path / "support/platform-site/macosx.x86_64/sitecustomize.py"
    ).exists()
    assert (bundle_path / "support/Python.xcframework/info.plist").exists()

    # The standard library has been copied to the app...
    assert (runtime_support_path / "python-stdlib/stdlib.txt").exists()
    # ... but the other support files have not.
    assert not (
        runtime_support_path / "platform-site/macosx.arm64/sitecustomize.py"
    ).exists()
    assert not (
        runtime_support_path / "platform-site/macosx.x86_64/sitecustomize.py"
    ).exists()
    assert not (runtime_support_path / "Python.xcframework/info.plist").exists()

    # The legacy content has been purged
    assert not (runtime_support_path / "python-stdlib/old-stdlib").exists()


@pytest.mark.parametrize("pre_existing", [True, False])
def test_install_support_package(
    create_command,
    first_app_templated,
    tmp_path,
    pre_existing,
):
    """The Python framework is copied out of the support package into the app bundle."""
    # Hard code the support revision
    first_app_templated.support_revision = "37"

    bundle_path = tmp_path / "base_path/build/first-app/macos/app"
    runtime_support_path = bundle_path / "First App.app/Contents/Frameworks"

    if pre_existing:
        create_file(
            runtime_support_path / "Python.framework/old-Python",
            "Old library",
        )

    # Mock download.file to return a support package
    create_command.tools.file.download = mock.MagicMock(
        side_effect=mock_tgz_download(
            f"Python-3.{sys.version_info.minor}-macOS-support.b37.tar.gz",
            content=[
                (
                    "platform-site/macosx.arm64/sitecustomize.py",
                    "this is the arm64 platform site",
                ),
                (
                    "platform-site/macosx.x86_64/sitecustomize.py",
                    "this is the x86_64 platform site",
                ),
                ("Python.xcframework/Info.plist", "this is the xcframework"),
                (
                    "Python.xcframework/macos-arm64_x86_64/Python.framework/Versions/Current/Python",
                    "this is the library",
                ),
            ],
            links=[
                (
                    "Python.xcframework/macos-arm64_x86_64/Python.framework/Python",
                    "Versions/Current/Python",
                ),
            ],
        )
    )

    # Install the support package
    create_command.install_app_support_package(first_app_templated)

    # Confirm that the support files have been unpacked into the bundle location
    assert (
        bundle_path / "support/platform-site/macosx.arm64/sitecustomize.py"
    ).exists()
    assert (
        bundle_path / "support/platform-site/macosx.x86_64/sitecustomize.py"
    ).exists()
    assert (bundle_path / "support/Python.xcframework/Info.plist").exists()
    assert (
        bundle_path
        / "support/Python.xcframework/macos-arm64_x86_64/Python.framework/Versions/Current/Python"
    ).is_file()
    assert (
        bundle_path
        / "support/Python.xcframework/macos-arm64_x86_64/Python.framework/Python"
    ).is_symlink()

    # The standard library has been copied to the app...
    assert (runtime_support_path / "Python.framework/Versions/Current/Python").is_file()
    assert (runtime_support_path / "Python.framework/Python").is_symlink()
    # ... but the other support files have not.
    assert not (
        runtime_support_path / "platform-site/macosx.arm64/sitecustomize.py"
    ).exists()
    assert not (
        runtime_support_path / "platform-site/macosx.x86_64/sitecustomize.py"
    ).exists()

    # The legacy content has been purged
    assert not (runtime_support_path / "python-stdlib/old-Python").exists()


def test_install_app_requirements_error_adds_install_hint_missing_x86_64_wheel(
    create_command, first_app_templated
):
    """Install_hint (mentioning a missing x86_64 wheel) is added when
    RequirementsInstallError is raised by _install_app_requirements in the macOS create
    command."""

    create_command.tools.host_arch = "x86_64"
    first_app_templated.min_os_version = "12.0"
    first_app_templated.requires = ["package-one", "package_two", "packagethree"]

    # Mock app_context for the generated app to simulate pip failure
    mock_app_context = mock.MagicMock(spec=Subprocess)
    mock_app_context.run.side_effect = CalledProcessError(returncode=1, cmd="pip")
    create_command.tools[first_app_templated].app_context = mock_app_context

    # Check that _install_app_requirements raises a RequirementsInstallError with an install hint
    with pytest.raises(
        RequirementsInstallError,
        match=r"x86_64 wheel that is compatible with a minimum\nmacOS version of 12.0",
    ):
        create_command._install_app_requirements(
            app=first_app_templated,
            requires=first_app_templated.requires,
            app_packages_path=Path("/test/path"),
        )

    # Ensure the mocked subprocess was called as expected
    mock_app_context.run.assert_called_once()


def test_install_app_requirements_error_adds_install_hint_missing_arm64_wheel(
    create_command, first_app_templated
):
    """Install_hint (mentioning a missing arm64 wheel) is added when
    RequirementsInstallError is raised by _install_app_requirements in the macOS create
    command."""

    create_command.tools.host_arch = "x86_64"
    first_app_templated.min_os_version = "12.0"
    first_app_templated.requires = ["package-one", "package_two", "packagethree"]

    # Fake a found binary package (so second install is triggered)
    create_command.find_binary_packages = mock.Mock(
        return_value=[("package-one", "1.0")]
    )

    # First call (host arch x86_64) succeeds, second (other arch arm64) fails
    create_command.tools[first_app_templated].app_context.run.side_effect = [
        None,
        CalledProcessError(returncode=1, cmd="pip"),
    ]

    # Check that _install_app_requirements raises a RequirementsInstallError with an install hint
    with pytest.raises(
        RequirementsInstallError,
        match=r"arm64 wheel that is compatible with a minimum\nmacOS version of 12.0",
    ):
        create_command._install_app_requirements(
            app=first_app_templated,
            requires=first_app_templated.requires,
            app_packages_path=Path("/test/path"),
        )

    # Ensure the mocked subprocess was called as expected
    assert create_command.tools[first_app_templated].app_context.run.call_count == 2