-
Notifications
You must be signed in to change notification settings - Fork 512
Expand file tree
/
Copy pathtest_projects.py
More file actions
2810 lines (2456 loc) · 99.9 KB
/
test_projects.py
File metadata and controls
2810 lines (2456 loc) · 99.9 KB
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
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2022-2024 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import itertools
from typing import Any, Dict, cast
import pydantic
import pytest
from craft_application.errors import CraftValidationError
from craft_application.models import BuildInfo, UniqueStrList, VersionStr
from craft_platforms import DebianArchitecture
from craft_providers.bases import BaseName
import snapcraft.models
from snapcraft import const, errors, providers
from snapcraft.models import (
MANDATORY_ADOPTABLE_FIELDS,
Architecture,
ComponentProject,
ContentPlug,
GrammarAwareProject,
Hook,
Platform,
Project,
)
from snapcraft.models.project import apply_root_packages
# required project data for core24 snaps
CORE24_DATA = {"base": "core24", "grade": "devel"}
VALID_DURATIONS = ["10ns", "10us", "10ms", "10s", "10m", "10m4s3us"]
INVALID_DURATIONS = ["10", "10 s", "10 seconds", "1:00", "invalid"]
@pytest.fixture
def project_yaml_data():
def _project_yaml_data(
*, name: str = "name", version: str = "0.1", summary: str = "summary", **kwargs
) -> Dict[str, Any]:
return {
"name": name,
"version": version,
"base": "core22",
"summary": summary,
"description": "description",
"grade": "stable",
"confinement": "strict",
"parts": {},
**kwargs,
}
yield _project_yaml_data
@pytest.fixture
def app_yaml_data(project_yaml_data):
def _app_yaml_data(**kwargs) -> Dict[str, Any]:
data = project_yaml_data()
data["apps"] = {"app1": {"command": "/bin/true", **kwargs}}
return data
yield _app_yaml_data
@pytest.fixture
def socket_yaml_data(app_yaml_data):
def _socket_yaml_data(**kwargs) -> Dict[str, Any]:
data = app_yaml_data()
data["apps"]["app1"]["sockets"] = {"socket1": {**kwargs}}
return data
yield _socket_yaml_data
@pytest.fixture
def fake_project_with_numbers(project_yaml_data):
"""Returns a fake project with numbers in string fields.
This includes numbers in fields that are validated by snapcraft and fields
validated by craft-parts.
"""
return project_yaml_data(
# string
version=1.0,
# string
icon=2,
# list[str]
website=[3.0, 4],
# dict[str, str]
environment={
"float": 5.0,
"int": 6,
},
parts={
"p1": {
"plugin": "nil",
# string
"source-type": 7,
# string
"source-commit": 8.0,
# list[str]
"build-snaps": [9, 10.0],
# dict[str, str]
"build-environment": [
{"float": 11.0},
{"int": 12},
],
}
},
)
class TestProjectDefaults:
"""Ensure unspecified items have the correct default value."""
def test_project_defaults(self, project_yaml_data):
project = Project.unmarshal(project_yaml_data())
assert project.build_base == project.base
assert project.compression == "xz"
assert project.contact is None
assert project.donation is None
assert project.issues is None
assert project.source_code is None
assert project.website is None
assert project.type is None
assert project.icon is None
assert project.layout is None
assert project.license is None
assert project.package_repositories is None
assert project.assumes == []
assert project.hooks is None
assert project.passthrough is None
assert project.apps is None
assert project.plugs is None
assert project.slots is None
assert project.epoch is None
assert project.environment is None
assert project.adopt_info is None
assert project.architectures == [
Architecture(
build_on=cast(UniqueStrList, [str(DebianArchitecture.from_host())]),
build_for=cast(UniqueStrList, [str(DebianArchitecture.from_host())]),
)
]
assert project.ua_services is None
assert project.system_usernames is None
assert project.provenance is None
assert project.components is None
def test_app_defaults(self, project_yaml_data):
data = project_yaml_data(apps={"app1": {"command": "/bin/true"}})
project = Project.unmarshal(data)
assert project.apps is not None
app = project.apps["app1"]
assert app is not None
assert app.command == "/bin/true"
assert app.autostart is None
assert app.common_id is None
assert app.bus_name is None
assert app.completer is None
assert app.stop_command is None
assert app.post_stop_command is None
assert app.start_timeout is None
assert app.stop_timeout is None
assert app.watchdog_timeout is None
assert app.reload_command is None
assert app.restart_delay is None
assert app.timer is None
assert app.daemon is None
assert app.after == []
assert app.before == []
assert app.refresh_mode is None
assert app.stop_mode is None
assert app.restart_condition is None
assert app.install_mode is None
assert app.slots is None
assert app.plugs is None
assert app.aliases is None
assert app.environment is None
assert app.command_chain == []
class TestProjectValidation:
"""Validate top-level project items."""
def test_build_base_validation_reentrant(self, project_yaml_data):
"""Validators should be reentrant.
Changing a field causes all validators to re-run, so validators should not
fail when validating an existing model.
This is a regression test for `base: core22` and `build-base: bare`, where
the validators receive "build-base" when creating the model and "build_base"
when re-validating.
"""
data = project_yaml_data(
base="bare",
# build-base has to be parsed for the validator to allow 'architectures'
build_base="core22",
architectures=["amd64"],
)
project = Project.unmarshal(data)
# changing any value will re-run the validators, which should not raise an error
project.version = cast(VersionStr, "1.2.3")
@pytest.mark.parametrize("field", ["name", "confinement", "parts"])
def test_mandatory_fields(self, field, project_yaml_data):
data = project_yaml_data()
data.pop(field)
error = f"{field}\n Field required"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(data)
@pytest.mark.parametrize(
"snap_type,requires_base",
[
("app", True),
("gadget", True),
("base", False),
("kernel", False),
("snapd", False),
],
)
def test_mandatory_base(self, snap_type, requires_base, project_yaml_data):
data = project_yaml_data(type=snap_type)
data.pop("base")
if requires_base:
error = "Snap base must be declared when type is not"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(data)
else:
project = Project.unmarshal(data)
assert project.base is None
def test_mandatory_adoptable_fields_definition(self):
assert MANDATORY_ADOPTABLE_FIELDS == (
"version",
"summary",
"description",
)
@pytest.mark.parametrize("field", MANDATORY_ADOPTABLE_FIELDS)
def test_adoptable_fields(self, field, project_yaml_data):
data = project_yaml_data()
data.pop(field)
error = f"Required field '{field}' is not set and 'adopt-info' not used."
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(data)
@pytest.mark.parametrize("field", MANDATORY_ADOPTABLE_FIELDS)
def test_adoptable_field_not_required(self, field, project_yaml_data):
data = project_yaml_data()
data.pop(field)
data["adopt-info"] = "part1"
project = Project.unmarshal(data)
assert getattr(project, field) is None
@pytest.mark.parametrize("field", MANDATORY_ADOPTABLE_FIELDS)
def test_adoptable_field_assignment(self, field, project_yaml_data):
data = project_yaml_data()
data["adopt-info"] = "part1"
project = Project.unmarshal(data)
setattr(project, field, None)
@pytest.mark.parametrize(
"name",
[
"name",
"name-with-dashes",
"name0123",
"0123name",
"a234567890123456789012345678901234567890",
],
)
def test_project_name_valid(self, name, project_yaml_data):
project = Project.unmarshal(project_yaml_data(name=name))
assert project.name == name
@pytest.mark.parametrize(
"name,error",
[
("name_with_underscores", "snap names can only use"),
("name-with-UPPERCASE", "snap names can only use"),
("name with spaces", "snap names can only use"),
("-name-starts-with-hyphen", "snap names cannot start with a hyphen"),
("name-ends-with-hyphen-", "snap names cannot end with a hyphen"),
("name-has--two-hyphens", "snap names cannot have two hyphens in a row"),
("123456", "snap names can only use"),
(
"a2345678901234567890123456789012345678901",
"String should have at most 40 characters",
),
],
)
def test_project_name_invalid(self, name, error, project_yaml_data):
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(name=name))
@pytest.mark.parametrize(
"version",
[
"1",
"1.0",
"1.0.1-5.2~build0.20.04:1+1A",
"git",
"1~",
"1+",
"x" * 32,
],
)
def test_project_version_valid(self, version, project_yaml_data):
project = Project.unmarshal(project_yaml_data(version=version))
assert project.version == version
def test_project_version_invalid(self, project_yaml_data):
"""Test one invalid version as this is inherited from Craft Application."""
error = "invalid version: Valid versions consist of"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(version="1=1"))
@pytest.mark.parametrize(
"snap_type",
["app", "gadget", "kernel", "snapd", "base", "_invalid"],
)
def test_project_type(self, snap_type, project_yaml_data):
data = project_yaml_data(type=snap_type)
if snap_type in ["base", "kernel", "snapd"]:
data.pop("base")
if snap_type != "_invalid":
project = Project.unmarshal(data)
assert project.type == snap_type
else:
error = "Input should be 'app', 'base', 'gadget', 'kernel' or 'snapd'"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(data)
@pytest.mark.parametrize(
"confinement", ["strict", "devmode", "classic", "_invalid"]
)
def test_project_confinement(self, confinement, project_yaml_data):
data = project_yaml_data(confinement=confinement)
if confinement != "_invalid":
project = Project.unmarshal(data)
assert project.confinement == confinement
else:
error = "Input should be 'classic', 'devmode' or 'strict'"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(data)
@pytest.mark.parametrize("grade", ["devel", "stable", "_invalid"])
def test_project_grade(self, grade, project_yaml_data):
data = project_yaml_data(grade=grade)
if grade != "_invalid":
project = Project.unmarshal(data)
assert project.grade == grade
else:
error = "Input should be 'stable' or 'devel'"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(data)
@pytest.mark.parametrize("grade", ["devel", "stable", "_invalid"])
def test_project_grade_assignment(self, grade, project_yaml_data):
data = project_yaml_data()
project = Project.unmarshal(data)
if grade != "_invalid":
project.grade = grade
else:
error = "Input should be 'stable' or 'devel'"
with pytest.raises(pydantic.ValidationError, match=error):
project.grade = grade # type: ignore
def test_project_summary_valid(self, project_yaml_data):
summary = "x" * 78
project = Project.unmarshal(project_yaml_data(summary=summary))
assert project.summary == summary
def test_project_summary_invalid(self, project_yaml_data):
summary = "x" * 79
error = "String should have at most 78 characters"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(summary=summary))
@pytest.mark.parametrize(
"epoch",
[
"0",
"1",
"1*",
"12345",
"12345*",
],
)
def test_project_epoch_valid(self, epoch, project_yaml_data):
project = Project.unmarshal(project_yaml_data(epoch=epoch))
assert project.epoch == epoch
@pytest.mark.parametrize(
"epoch",
[
"",
"invalid",
"0*",
"012345",
"-1",
"*1",
"1**",
],
)
def test_project_epoch_invalid(self, epoch, project_yaml_data):
error = "Epoch is a positive integer followed by an optional asterisk"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(epoch=epoch))
def test_project_package_repository(self, project_yaml_data):
repos = [
{
"type": "apt",
"ppa": "test/somerepo",
},
{
"type": "apt",
"url": "https://some/url",
"key-id": "ABCDE12345" * 4,
},
]
project = Project.unmarshal(project_yaml_data(package_repositories=repos))
assert project.package_repositories == repos
def test_project_package_repository_missing_fields(self, project_yaml_data):
repos = [
{
"type": "apt",
},
]
error = r"url\n Field required.*\n.*\n.*key-id\n Field required"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(package_repositories=repos))
def test_project_package_repository_extra_fields(self, project_yaml_data):
repos = [
{
"type": "apt",
"extra": "something",
},
]
error = "Extra inputs are not permitted"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(package_repositories=repos))
@pytest.mark.parametrize(
"environment",
[
{"SINGLE_VARIABLE": "foo"},
{"FIRST_VARIABLE": "foo", "SECOND_VARIABLE": "bar"},
],
)
def test_project_environment_valid(self, environment, project_yaml_data):
project = Project.unmarshal(project_yaml_data(environment=environment))
for variable in environment:
assert variable in project.environment
@pytest.mark.parametrize(
"environment",
[
"i am a string",
["i", "am", "a", "list"],
[{"i": "am"}, {"a": "list"}, {"of": "dictionaries"}],
],
)
def test_project_environment_invalid(self, environment, project_yaml_data):
error = "Input should be a valid dictionary"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(environment=environment))
@pytest.mark.parametrize(
"plugs",
[
{"empty-plug": None},
{"string-plug": "home"},
{"dict-plug": {"string-parameter": "foo", "bool-parameter": True}},
],
)
def test_project_plugs_valid(self, plugs, project_yaml_data):
project = Project.unmarshal(project_yaml_data(plugs=plugs))
assert project.plugs == plugs
@pytest.mark.parametrize(
"plugs",
[
"i am a string",
["i", "am", "a", "list"],
[{"i": "am"}, {"a": "list"}, {"of": "dictionaries"}],
],
)
def test_project_plugs_invalid(self, plugs, project_yaml_data):
error = "Input should be a valid dictionary"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(plugs=plugs))
def test_project_content_plugs_valid(self, project_yaml_data):
content_plug_data = {
"content-interface": {
"interface": "content",
"target": "test-target",
"content": "test-content",
"default-provider": "test-provider",
}
}
content_plug = ContentPlug(**content_plug_data["content-interface"])
project = Project.unmarshal(project_yaml_data(plugs=content_plug_data))
assert project.plugs is not None
assert project.plugs["content-interface"] == content_plug
def test_project_content_plugs_missing_target(self, project_yaml_data):
content_plug = {
"content-interface": {
"interface": "content",
"content": "test-content",
"default-provider": "test-provider",
}
}
error = ".*'content-interface' must have a 'target' parameter"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(plugs=content_plug))
def test_project_get_content_snaps(self, project_yaml_data):
content_plug_data = {
"content-interface": {
"interface": "content",
"target": "test-target",
"content": "test-content",
"default-provider": "test-provider",
}
}
project = Project.unmarshal(project_yaml_data(plugs=content_plug_data))
assert project.get_content_snaps() == ["test-provider"]
def test_project_default_provider_with_channel(self, project_yaml_data):
content_plug_data = {
"content-interface": {
"interface": "content",
"target": "test-target",
"content": "test-content",
"default-provider": "test-provider/edge",
}
}
error = (
"Specifying a snap channel in 'default_provider' is not supported: "
"test-provider/edge"
)
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(plugs=content_plug_data))
@pytest.mark.parametrize("decl_type", ["symlink", "bind", "bind-file", "type"])
def test_project_layout(self, decl_type, project_yaml_data):
project = Project.unmarshal(
project_yaml_data(layout={"foo": {decl_type: "bar"}})
)
assert project.layout is not None
assert project.layout["foo"][decl_type] == "bar"
def test_project_layout_invalid(self, project_yaml_data):
error = "Input should be 'symlink', 'bind', 'bind-file' or 'type'"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(layout={"foo": {"invalid": "bar"}}))
@pytest.mark.parametrize(
"slots",
[
{"test-slot": {"interface": "some-value"}},
{
"db-socket": {
"interface": "content",
"content": "db-socket",
"write": ["$SNAP_COMMON/postgres/sockets"],
},
},
],
)
def test_slot_valid(self, slots, project_yaml_data):
project = Project.unmarshal(project_yaml_data(slots=slots))
assert project.slots == slots
def test_project_build_base_devel_grade_devel(self, project_yaml_data):
"""When build_base is `devel`, the grade must be `devel`."""
project = Project.unmarshal(
project_yaml_data(build_base="devel", grade="devel")
)
assert project.grade == "devel"
@pytest.mark.parametrize("build_base", ["core22", "devel"])
def test_project_grade_not_defined(self, build_base, project_yaml_data):
"""Do not validate the grade if it is not defined, regardless of build_base."""
data = project_yaml_data(build_base=build_base)
data.pop("grade")
project = Project.unmarshal(data)
assert project.build_base == build_base
assert not project.grade
def test_project_build_base_devel_grade_stable_error(self, project_yaml_data):
"""Raise an error if build_base is `devel` and grade is `stable`."""
error = "grade must be 'devel' when build-base is 'devel'"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(build_base="devel", grade="stable"))
@pytest.mark.parametrize(
("base", "expected_base"),
[
("bare", None),
*providers.SNAPCRAFT_BASE_TO_PROVIDER_BASE.items(),
("core22-desktop", providers.SNAPCRAFT_BASE_TO_PROVIDER_BASE["core22"]),
("core24-desktop", providers.SNAPCRAFT_BASE_TO_PROVIDER_BASE["core24"]),
],
)
def test_provider_base(self, base, expected_base, project_yaml_data):
providers_base = Project._providers_base(base)
assert providers_base == expected_base
def test_provider_base_error(self, project_yaml_data):
with pytest.raises(CraftValidationError) as raised:
Project._providers_base("unknown")
assert "Unknown base 'unknown'" in str(raised.value)
def test_project_global_plugs_warning(self, project_yaml_data, emitter):
data = project_yaml_data(plugs={"desktop": None, "desktop-legacy": None})
Project.unmarshal(data)
expected_message = (
"Warning: implicit plug assignment in 'desktop' and 'desktop-legacy'. "
"Plugs should be assigned to the app to which they apply, and not "
"implicitly assigned via the global 'plugs:' stanza "
"which is intended for configuration only."
"\n(Reference: https://snapcraft.io/docs/snapcraft-top-level-metadata"
"#heading--plugs-and-slots-for-an-entire-snap)"
)
emitter.assert_message(expected_message)
def test_project_global_slots_warning(self, project_yaml_data, emitter):
data = project_yaml_data(slots={"home": None, "removable-media": None})
Project.unmarshal(data)
expected_message = (
"Warning: implicit slot assignment in 'home' and 'removable-media'. "
"Slots should be assigned to the app to which they apply, and not "
"implicitly assigned via the global 'slots:' stanza "
"which is intended for configuration only."
"\n(Reference: https://snapcraft.io/docs/snapcraft-top-level-metadata"
"#heading--plugs-and-slots-for-an-entire-snap)"
)
emitter.assert_message(expected_message)
def test_links_scalar(self, project_yaml_data):
data = project_yaml_data(
contact="https://matrix.to/#/#nickvision:matrix.org",
donation="https://github.com/sponsors/nlogozzo",
issues="https://github.com/NickvisionApps/Parabolic/issues",
source_code="https://github.com/NickvisionApps/Parabolic",
website="https://github.com/NickvisionApps/Parabolic",
)
project = Project.unmarshal(data)
assert project.contact == ["https://matrix.to/#/#nickvision:matrix.org"]
assert project.donation == ["https://github.com/sponsors/nlogozzo"]
assert project.issues == ["https://github.com/NickvisionApps/Parabolic/issues"]
assert project.source_code == ["https://github.com/NickvisionApps/Parabolic"]
assert project.website == ["https://github.com/NickvisionApps/Parabolic"]
def test_links_list(self, project_yaml_data):
data = project_yaml_data(
contact=[
"https://matrix.to/#/#nickvision:matrix.org",
"hello@example.org",
],
donation=[
"https://github.com/sponsors/nlogozzo",
"https://paypal.me/nlogozzo",
],
issues=[
"https://github.com/NickvisionApps/Parabolic/issues",
"https://github.com/NickvisionApps/Denaro/issues",
],
source_code=[
"https://github.com/NickvisionApps/Parabolic",
"https://github.com/NickvisionApps/Denaro",
],
website=[
"https://github.com/NickvisionApps/Parabolic",
"https://github.com/NickvisionApps/Denaro",
],
)
project = Project.unmarshal(data)
assert project.contact == [
"https://matrix.to/#/#nickvision:matrix.org",
"hello@example.org",
]
assert project.donation == [
"https://github.com/sponsors/nlogozzo",
"https://paypal.me/nlogozzo",
]
assert project.issues == [
"https://github.com/NickvisionApps/Parabolic/issues",
"https://github.com/NickvisionApps/Denaro/issues",
]
assert project.source_code == [
"https://github.com/NickvisionApps/Parabolic",
"https://github.com/NickvisionApps/Denaro",
]
assert project.website == [
"https://github.com/NickvisionApps/Parabolic",
"https://github.com/NickvisionApps/Denaro",
]
def test_coerce_numbers(self, fake_project_with_numbers):
"""Coerce numbers into strings."""
project = Project.unmarshal(fake_project_with_numbers)
assert project.version == "1.0"
assert project.icon == "2"
assert project.website == ["3.0", "4"]
assert project.environment == {"float": "5.0", "int": "6"}
# parts remain a dictionary with original types
assert project.parts["p1"]["source-type"] == 7
assert project.parts["p1"]["source-commit"] == 8.0
assert project.parts["p1"]["build-snaps"] == [9, 10.0]
assert project.parts["p1"]["build-environment"] == [
{"float": 11.0},
{"int": 12},
]
class TestHookValidation:
"""Validate hooks."""
@pytest.mark.parametrize(
"hooks",
[
{"configure": {}},
{
"configure": {
"command-chain": ["test-1", "test-2"],
"environment": {
"FIRST_VARIABLE": "test-3",
"SECOND_VARIABLE": "test-4",
},
"plugs": ["home", "network"],
}
},
],
)
def test_project_hooks_valid(self, hooks, project_yaml_data):
configure_hook_data = Hook(**hooks["configure"])
project = Project.unmarshal(project_yaml_data(hooks=hooks))
assert project.hooks is not None
assert project.hooks["configure"] == configure_hook_data
def test_project_hooks_command_chain_invalid(self, project_yaml_data):
hook = {"configure": {"command-chain": ["_invalid!"]}}
error = "'_invalid!' is not a valid command chain"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(hooks=hook))
@pytest.mark.parametrize(
"environment",
[
"i am a string",
["i", "am", "a", "list"],
[{"i": "am"}, {"a": "list"}, {"of": "dictionaries"}],
],
)
def test_project_hooks_environment_invalid(self, environment, project_yaml_data):
hooks = {"configure": {"environment": environment}}
error = "Input should be a valid dictionary"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(hooks=hooks))
def test_project_hooks_plugs_empty(self, project_yaml_data):
hook = {"configure": {"plugs": []}}
error = "'plugs' field cannot be empty"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(hooks=hook))
class TestPlatforms:
"""Validate platforms."""
VALID_PLATFORM_ARCHITECTURES = [
# single architecture in a list
*(list(x) for x in itertools.combinations(const.SnapArch, 1)),
# two architectures in a list
*(list(x) for x in itertools.combinations(const.SnapArch, 2)),
]
@pytest.mark.parametrize("build_on", VALID_PLATFORM_ARCHITECTURES)
@pytest.mark.parametrize("build_for", [[arch] for arch in const.SnapArch])
def test_platform_validation_lists(self, build_on, build_for, project_yaml_data):
"""Unmarshal build-on and build-for lists."""
platform_data = Platform(**{"build-on": build_on, "build-for": build_for})
assert platform_data.build_for == build_for
assert platform_data.build_on == build_on
@pytest.mark.parametrize("build_on", const.SnapArch)
@pytest.mark.parametrize("build_for", const.SnapArch)
def test_platform_validation_strings(self, build_on, build_for, project_yaml_data):
"""Unmarshal and vectorize build-on and build-for strings."""
platform_data = Platform(**{"build-on": build_on, "build-for": build_for})
assert platform_data.build_for == [build_for]
assert platform_data.build_on == [build_on]
def test_platform_build_for_requires_build_on(self, project_yaml_data):
"""Raise an error if build-for is provided by build-on is not."""
error = r"build-on\n Field required"
with pytest.raises(pydantic.ValidationError, match=error):
Platform(**{"build-for": [const.SnapArch.amd64]}) # type: ignore[reportArgumentType]
def test_platforms_not_allowed_core22(self, project_yaml_data):
error = (
"'platforms' keyword is not supported for base 'core22'. "
"Use 'architectures' keyword instead."
)
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(project_yaml_data(platforms={"amd64": None}))
@pytest.mark.parametrize(
("architectures", "expected"),
[
pytest.param([], {}, id="empty"),
pytest.param(
["amd64"],
{
"amd64": Platform(
build_for=[const.SnapArch("amd64")],
build_on=[const.SnapArch("amd64")],
)
},
id="simple",
),
pytest.param(
[Architecture(build_on="amd64", build_for="riscv64")],
{
"riscv64": Platform(
build_for=[const.SnapArch("riscv64")],
build_on=[const.SnapArch("amd64")],
)
},
id="cross-compile-from-object",
),
pytest.param(
[
Architecture.unmarshal(
{"build_on": ["amd64"], "build_for": ["riscv64"]}
)
],
{
"riscv64": Platform(
build_for=[const.SnapArch("riscv64")],
build_on=[const.SnapArch("amd64")],
)
},
id="cross-compile",
),
pytest.param(
[
Architecture.unmarshal(
{"build_on": ["amd64", "arm64"], "build_for": ["riscv64"]}
),
Architecture.unmarshal(
{"build_on": ["amd64", "arm64"], "build_for": ["arm64"]}
),
],
{
"riscv64": Platform(
build_for=[const.SnapArch("riscv64")],
build_on=[const.SnapArch("amd64"), const.SnapArch("arm64")],
),
"arm64": Platform(
build_for=[const.SnapArch("arm64")],
build_on=[const.SnapArch("amd64"), const.SnapArch("arm64")],
),
},
id="complex",
),
pytest.param(
[Architecture.unmarshal({"build_on": ["s390x"], "build_for": ["all"]})],
{
"all": Platform(
build_for=["all"],
build_on=[const.SnapArch("s390x")],
)
},
id="all",
),
],
)
def test_from_architectures(self, architectures, expected):
assert Platform.from_architectures(architectures) == expected
class TestAppValidation:
"""Validate apps."""
def test_app_command(self, app_yaml_data):
data = app_yaml_data(command="test-command")
project = Project.unmarshal(data)
assert project.apps is not None
assert project.apps["app1"].command == "test-command"
@pytest.mark.parametrize(
"autostart",
["myapp.desktop", "_invalid"],
)
def test_app_autostart(self, autostart, app_yaml_data):
data = app_yaml_data(autostart=autostart)
if autostart != "_invalid":
project = Project.unmarshal(data)
assert project.apps is not None
assert project.apps["app1"].autostart == autostart
else:
error = (
"apps.app1.autostart\n Value error, '_invalid' is not a valid "
"desktop file name"
)
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(data)
def test_app_common_id(self, app_yaml_data):
data = app_yaml_data(common_id="test-common-id")
project = Project.unmarshal(data)
assert project.apps is not None
assert project.apps["app1"].common_id == "test-common-id"
def test_app_completer(self, app_yaml_data):
data = app_yaml_data(completer="test-completer")
project = Project.unmarshal(data)
assert project.apps is not None
assert project.apps["app1"].completer == "test-completer"
def test_app_stop_command(self, app_yaml_data):
data = app_yaml_data(stop_command="test-stop-command")
project = Project.unmarshal(data)
assert project.apps is not None
assert project.apps["app1"].stop_command == "test-stop-command"
def test_app_post_stop_command(self, app_yaml_data):
data = app_yaml_data(post_stop_command="test-post-stop-command")
project = Project.unmarshal(data)
assert project.apps is not None
assert project.apps["app1"].post_stop_command == "test-post-stop-command"
@pytest.mark.parametrize("start_timeout", VALID_DURATIONS)
def test_app_start_timeout_valid(self, start_timeout, app_yaml_data):
data = app_yaml_data(start_timeout=start_timeout)
project = Project.unmarshal(data)
assert project.apps is not None
assert project.apps["app1"].start_timeout == start_timeout
@pytest.mark.parametrize("start_timeout", INVALID_DURATIONS)
def test_app_start_timeout_invalid(self, start_timeout, app_yaml_data):
data = app_yaml_data(start_timeout=start_timeout)
error = f"'{start_timeout}' is not a valid time value"
with pytest.raises(pydantic.ValidationError, match=error):
Project.unmarshal(data)