-
Notifications
You must be signed in to change notification settings - Fork 512
Expand file tree
/
Copy pathtest_setup_assets.py
More file actions
644 lines (533 loc) · 19.3 KB
/
test_setup_assets.py
File metadata and controls
644 lines (533 loc) · 19.3 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
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2017-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 shutil
import textwrap
from pathlib import Path
from typing import Any
from unittest.mock import call
import pytest
from snapcraft import errors, models
from snapcraft.parts import setup_assets as parts_setup_assets
from snapcraft.parts.setup_assets import (
_create_hook_wrappers,
_ensure_hook,
_ensure_hook_executable,
_validate_command_chain,
_write_hook_wrapper,
setup_assets,
)
@pytest.fixture
def desktop_file():
def _write_file(filename: str):
Path(filename).write_text(
textwrap.dedent(
"""\
[Desktop Entry]
Name=appstream-desktop
Exec=appstream
Type=Application
Icon=/usr/share/icons/my-icon.svg"""
)
)
yield _write_file
@pytest.fixture
def yaml_data():
def _yaml_data(extra_data: dict[str, Any]) -> dict[str, Any]:
return {
"name": "test-project",
"base": "core22",
"confinement": "strict",
"parts": {},
**extra_data,
}
yield _yaml_data
@pytest.fixture
def gadget_yaml_file(new_dir):
Path("gadget.yaml").write_text(
textwrap.dedent(
"""\
gadget-key: gadget-value
"""
)
)
@pytest.fixture
def kernel_yaml_file(new_dir):
Path("kernel.yaml").write_text(
textwrap.dedent(
"""\
kernel-key: kernel-value
"""
)
)
def test_gadget(yaml_data, gadget_yaml_file, new_dir):
project = models.Project.unmarshal(
yaml_data(
{
"type": "gadget",
"version": "1.0",
"summary": "summary",
"description": "description",
}
)
)
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
# gadget file should be in meta/
gadget_path = Path("prime/meta/gadget.yaml")
assert gadget_path.is_file()
def test_gadget_missing(yaml_data, new_dir):
project = models.Project.unmarshal(
yaml_data(
{
"type": "gadget",
"version": "1.0",
"summary": "summary",
"description": "description",
}
)
)
with pytest.raises(errors.SnapcraftError) as raised:
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
assert str(raised.value) == "gadget.yaml is required for gadget snaps"
def test_kernel(yaml_data, kernel_yaml_file, new_dir):
project = models.Project.unmarshal(
{
"name": "custom-kernel",
"type": "kernel",
"confinement": "strict",
"version": "1.0",
"summary": "summary",
"description": "description",
"parts": {},
"build-base": "devel",
}
)
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
# kernel file should be in meta/
kernel_path = Path("prime/meta/kernel.yaml")
assert kernel_path.is_file()
def test_kernel_missing(yaml_data, new_dir):
project = models.Project.unmarshal(
{
"name": "custom-kernel",
"type": "kernel",
"confinement": "strict",
"version": "1.0",
"summary": "summary",
"description": "description",
"parts": {},
"build-base": "devel",
}
)
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
# kernel file should not be in meta/
kernel_path = Path("prime/meta/kernel.yaml")
assert not kernel_path.is_file()
@pytest.mark.parametrize(
"source,destination,copied",
[
(Path("foo"), Path("bar"), True),
(Path("foo"), Path("foo"), False),
(Path("foo"), Path("dest/foo"), True),
],
)
def test_copy_files(source, destination, copied, new_dir, mocker):
copy_mock = mocker.patch("shutil.copy")
Path("foo").touch()
Path("dest").mkdir()
Path("dest/foo").write_text("dest")
parts_setup_assets._copy_file(source, destination)
if copied:
assert copy_mock.mock_calls == [call(source, destination)]
else:
assert copy_mock.mock_calls == []
class TestSetupAssets:
"""Check copied assets and desktop entries."""
@pytest.fixture(autouse=True)
def setup_method_fixture(self, new_dir):
# create prime tree
Path("prime").mkdir()
Path("prime/test.sh").touch()
Path("prime/test.sh").chmod(0o755)
# create assets dir
Path("snap").mkdir()
def test_setup_assets_happy(self, desktop_file, yaml_data, new_dir):
desktop_file("prime/test.desktop")
Path("prime/usr/share/icons").mkdir(parents=True)
Path("prime/usr/share/icons/my-icon.svg").touch()
# define project
project = models.Project.unmarshal(
yaml_data(
{
"adopt-info": "part",
"apps": {
"app1": {
"command": "test.sh",
"common-id": "my.test.sh",
"desktop": "test.desktop",
},
},
},
)
)
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
# desktop file should be in meta/gui and named after app
desktop_path = Path("prime/meta/gui/app1.desktop")
assert desktop_path.is_file()
# desktop file content should make icon relative to ${SNAP}
content = desktop_path.read_text()
assert content == textwrap.dedent(
"""\
[Desktop Entry]
Name=appstream-desktop
Exec=test-project.app1
Type=Application
Icon=${SNAP}/usr/share/icons/my-icon.svg
"""
)
def test_hooks_default_handler(self, default_project, new_dir):
project_dir = new_dir
assets_dir = project_dir / "snap"
prime_dir = project_dir / "prime"
# Create a configure hook provided by the project
project_configure_hook = assets_dir / "hooks" / "configure"
project_configure_hook.parent.mkdir(parents=True)
project_configure_hook.write_text("project_configure")
# Create an install hook built through the project
built_install_hook = prime_dir / "snap" / "hooks" / "install"
built_install_hook.parent.mkdir(parents=True)
built_install_hook.write_text("built_install")
setup_assets(
default_project,
assets_dir=assets_dir,
project_dir=project_dir,
prime_dirs={None: Path("prime")},
)
hook_meta_dir = prime_dir / "meta" / "hooks"
# Assert the project configure hook has its wrapper
# to the copied over hook and is executable.
meta_configure_hook = hook_meta_dir / "configure"
assert meta_configure_hook.exists()
assert meta_configure_hook.read_text() == textwrap.dedent(
"""\
#!/bin/sh
exec "$SNAP/snap/hooks/configure" "$@"
"""
)
assert (
prime_dir / "snap" / "hooks" / "configure"
).read_text() == "project_configure"
assert oct(meta_configure_hook.stat().st_mode)[-3:] == "755"
# Assert the project install hook has its wrapper
# And is executable
meta_install_hook = hook_meta_dir / "install"
assert meta_install_hook.exists()
assert meta_install_hook.read_text() == textwrap.dedent(
"""\
#!/bin/sh
exec "$SNAP/snap/hooks/install" "$@"
"""
)
assert built_install_hook.read_text() == "built_install"
assert oct(meta_install_hook.stat().st_mode)[-3:] == "755"
def test_hooks_with_handler(self, default_project, new_dir):
project_dir = new_dir
assets_dir = project_dir / "snap"
prime_dir = project_dir / "prime"
# Create a configure hook provided by the project
project_configure_hook = assets_dir / "hooks" / "configure"
project_configure_hook.parent.mkdir(parents=True)
project_configure_hook.write_text("project_configure")
def handler(assets_dir, prime_dir) -> None:
hooks_meta_dir = prime_dir / "meta" / "hooks"
hooks_meta_dir.mkdir(parents=True)
for hook in (assets_dir / "hooks").iterdir():
shutil.copy(hook, hooks_meta_dir / hook.name)
setup_assets(
default_project,
assets_dir=assets_dir,
project_dir=project_dir,
prime_dirs={None: Path("prime")},
meta_directory_handler=handler,
)
hook_meta_dir = prime_dir / "meta" / "hooks"
# Assert the project configure hook was copied
# with no wrapper, is executable and that nothing
# was put in prime_dir/snap/hooks
meta_configure_hook = hook_meta_dir / "configure"
assert meta_configure_hook.exists()
assert meta_configure_hook.read_text() == "project_configure"
assert not (prime_dir / "snap" / "hooks" / "configure").exists()
assert oct(meta_configure_hook.stat().st_mode)[-3:] == "755"
def test_setup_assets_icon_in_assets_dir(self, desktop_file, yaml_data, new_dir):
desktop_file("prime/test.desktop")
Path("snap/gui").mkdir(parents=True)
Path("snap/gui/icon.svg").touch()
# define project
project = models.Project.unmarshal(
yaml_data(
{
"adopt-info": "part",
"apps": {
"app1": {
"command": "test.sh",
"common-id": "my.test.sh",
"desktop": "test.desktop",
},
},
},
)
)
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
# desktop file should be in meta/gui and named after app
desktop_path = Path("prime/meta/gui/app1.desktop")
assert desktop_path.is_file()
# desktop file content should make icon relative to ${SNAP}
content = desktop_path.read_text()
assert content == textwrap.dedent(
"""\
[Desktop Entry]
Name=appstream-desktop
Exec=test-project.app1
Type=Application
Icon=${SNAP}/snap/gui/icon.svg
"""
)
# icon file exists
assert Path("prime/snap/gui/icon.svg").is_file()
def test_setup_assets_configure_icon_no_apps(
self, desktop_file, yaml_data, new_dir
):
"""Configure icon when no `apps` are defined."""
desktop_file("prime/test.desktop")
Path("snap/gui").mkdir(parents=True)
Path("snap/gui/icon.svg").touch()
# define project
project = models.Project.unmarshal(yaml_data({"adopt-info": "part"}))
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
# icon file exists
assert Path("prime/snap/gui/icon.svg").is_file()
def test_setup_assets_remote_icon(self, desktop_file, yaml_data, new_dir):
# create primed tree (no icon)
desktop_file("prime/test.desktop")
# define project
project = models.Project.unmarshal(
yaml_data(
{
"adopt-info": "part",
"icon": "https://dashboard.snapcraft.io/site_media/appmedia/2018/04/Snapcraft-logo-bird.png",
"apps": {
"app1": {
"command": "test.sh",
"common-id": "my.test.sh",
"desktop": "test.desktop",
},
},
},
)
)
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
# desktop file should be in meta/gui and named after app
desktop_path = Path("prime/meta/gui/app1.desktop")
assert desktop_path.is_file()
# desktop file content should make icon relative to ${SNAP}
content = desktop_path.read_text()
assert content == textwrap.dedent(
"""\
[Desktop Entry]
Name=appstream-desktop
Exec=test-project.app1
Type=Application
Icon=${SNAP}/meta/gui/icon.png
"""
)
# icon was downloaded
icon_path = Path("prime/meta/gui/icon.png")
assert icon_path.is_file()
assert icon_path.stat().st_size > 0
class TestCommandChain:
"""Command chain items are valid."""
def test_setup_assets_app_command_chain_error(self, yaml_data, new_dir):
project = models.Project.unmarshal(
yaml_data(
{
"adopt-info": "part1",
"apps": {
"app1": {
"command": "test.sh",
"command-chain": ["does-not-exist"],
},
},
},
)
)
with pytest.raises(errors.SnapcraftError) as raised:
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
assert str(raised.value) == (
"Failed to generate snap metadata: The command-chain item 'does-not-exist' "
"defined in app 'app1' does not exist or is not executable."
)
def test_setup_assets_hook_command_chain_error(self, yaml_data, new_dir):
# define project
project = models.Project.unmarshal(
yaml_data(
{
"adopt-info": "part1",
"hooks": {
"hook1": {"command-chain": ["does-not-exist"]},
},
},
)
)
with pytest.raises(errors.SnapcraftError) as raised:
setup_assets(
project,
assets_dir=Path("snap"),
project_dir=Path.cwd(),
prime_dirs={None: Path("prime")},
)
assert str(raised.value) == (
"Failed to generate snap metadata: The command-chain item 'does-not-exist' "
"defined in hook 'hook1' does not exist or is not executable."
)
def test_command_chain_path_not_found(self, new_dir):
with pytest.raises(errors.SnapcraftError) as raised:
_validate_command_chain(["file-not-found"], name="foo", prime_dir=new_dir)
assert str(raised.value) == (
"Failed to generate snap metadata: The command-chain item 'file-not-found' "
"defined in foo does not exist or is not executable."
)
def test_command_chain_path_not_executable(self, new_dir):
Path("file-executable").touch()
Path("file-executable").chmod(0o755)
Path("file-not-executable").touch()
with pytest.raises(errors.SnapcraftError) as raised:
_validate_command_chain(
["file-executable", "file-not-executable"],
name="foo",
prime_dir=new_dir,
)
assert str(raised.value) == (
"Failed to generate snap metadata: The command-chain item 'file-not-executable' "
"defined in foo does not exist or is not executable."
)
def test_ensure_hook(new_dir):
"""Verify creation of executable placeholder hooks."""
hook_path: Path = new_dir / "configure"
_ensure_hook(hook_path)
assert hook_path.exists()
assert hook_path.read_text() == "#!/bin/true\n"
def test_ensure_hook_does_not_overwrite(new_dir):
"""Verify existing hooks are not overwritten with placeholder hooks."""
hook_path: Path = new_dir / "configure"
hook_path.write_text("#!/bin/python3\n")
hook_path.chmod(0o700)
_ensure_hook(hook_path)
assert hook_path.exists()
assert hook_path.read_text() == "#!/bin/python3\n"
assert oct(hook_path.stat().st_mode)[-3:] == "700"
def test_ensure_hook_executable(new_dir):
"""Verify _ensure_hook_executable makes a file executable."""
# create a non-executable file
hook_path: Path = new_dir / "configure"
hook_path.write_text("#!/bin/true\n")
hook_path.chmod(0o644)
_ensure_hook_executable(hook_path)
assert hook_path.exists()
assert oct(hook_path.stat().st_mode)[-3:] == "755"
def test_create_hook_wrappers(new_dir):
"""Verify hook wrappers are created for generated hooks."""
# create a directory for the hooks
hooks_snap_dir: Path = new_dir / "snap" / "hooks"
hooks_snap_dir.mkdir(parents=True)
# create 2 generated hooks
for hook_name in ["configure", "install"]:
hook: Path = hooks_snap_dir / hook_name
hook.write_text("#!/bin/true\n")
hook.chmod(0o644)
_create_hook_wrappers(new_dir)
# verify prime/meta/hooks directory was created
hooks_meta_dir = new_dir / "meta" / "hooks"
assert hooks_meta_dir.exists()
# verify wrappers were generated for each hook
for hook_name in ["configure", "install"]:
hook_wrapper = hooks_meta_dir / hook_name
assert hook_wrapper.exists()
def test_write_hook_wrapper(new_dir):
"""Verify hook wrappers are written correctly."""
# create a directory for the hooks
hooks_dir: Path = new_dir / "hooks"
hooks_dir.mkdir()
# create a generated hook
hook_name = "configure"
hook: Path = hooks_dir / hook_name
hook.write_text("#!/bin/true\n")
hook.chmod(0o644)
# create a directory for the hook wrappers
hook_wrapper_dir = new_dir / "hook-wrappers"
hook_wrapper_dir.mkdir()
hook_wrapper = hook_wrapper_dir / hook_name
_write_hook_wrapper(hook_name, hook_wrapper)
# verify content of hook wrapper
assert hook_wrapper.exists()
assert (
hook_wrapper.read_text()
== f'#!/bin/sh\nexec "$SNAP/snap/hooks/{hook_name}" "$@"\n'
)