File: main_test.go

package info (click to toggle)
snapd 2.72-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 80,412 kB
  • sloc: sh: 16,506; ansic: 16,211; python: 11,213; makefile: 1,919; exp: 190; awk: 58; xml: 22
file content (742 lines) | stat: -rw-r--r-- 22,931 bytes parent folder | download | duplicates (3)
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
// -*- Mode: Go; indent-tabs-mode: t -*-

/*
 * Copyright (C) 2016 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/>.
 *
 */

package main_test

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"syscall"
	"testing"

	. "gopkg.in/check.v1"

	snapExec "github.com/snapcore/snapd/cmd/snap-exec"
	"github.com/snapcore/snapd/dirs"
	"github.com/snapcore/snapd/osutil"
	"github.com/snapcore/snapd/release"
	"github.com/snapcore/snapd/snap"
	"github.com/snapcore/snapd/snap/snaptest"
	"github.com/snapcore/snapd/testutil"
)

// Hook up check.v1 into the "go test" runner
func Test(t *testing.T) { TestingT(t) }

type snapExecSuite struct{}

var _ = Suite(&snapExecSuite{})

func (s *snapExecSuite) SetUpTest(c *C) {
	// clean previous parse runs
	snapExec.SetOptsCommand("")
	snapExec.SetOptsHook("")
}

func (s *snapExecSuite) TearDown(c *C) {
	dirs.SetRootDir("/")
}

var mockYaml = []byte(`name: snapname
version: 1.0
apps:
 app:
  command: run-app cmd-arg1 $SNAP_DATA
  stop-command: stop-app
  post-stop-command: post-stop-app
  completer: you/complete/me
  environment:
   BASE_PATH: /some/path
   LD_LIBRARY_PATH: ${BASE_PATH}/lib
   MY_PATH: $PATH
   TEST_PATH: /custom
 app2:
  command: run-app2
  stop-command: stop-app2
  post-stop-command: post-stop-app2
  command-chain: [chain1, chain2]
 nostop:
  command: nostop
components:
 comp:
  type: standard
  hooks:
   install:
`)

var mockClassicYaml = append([]byte("confinement: classic\n"), mockYaml...)

var mockComponentYaml = []byte(`component: snapname+comp
type: standard
version: 1.0
`)

var mockHookYaml = []byte(`name: snapname
version: 1.0
hooks:
 configure:
`)

var mockHookCommandChainYaml = []byte(`name: snapname
version: 1.0
hooks:
 configure:
  command-chain: [chain1, chain2]
components:
 comp:
  type: standard
  hooks:
   install:
    command-chain: [chain3, chain4]
`)

var binaryTemplate = `#!/bin/sh
echo "$(basename $0)" >> %[1]q
for arg in "$@"; do
echo "$arg" >> %[1]q
done
printf "\n" >> %[1]q`

func (s *snapExecSuite) TestInvalidCombinedParameters(c *C) {
	invalidParameters := []string{"--hook=hook-name", "--command=command-name", "snap-name"}
	_, _, err := snapExec.ParseArgs(invalidParameters)
	c.Check(err, ErrorMatches, ".*cannot use --hook and --command together.*")
}

func (s *snapExecSuite) TestInvalidExtraParameters(c *C) {
	invalidParameters := []string{"--hook=hook-name", "snap-name", "foo", "bar"}
	_, _, err := snapExec.ParseArgs(invalidParameters)
	c.Check(err, ErrorMatches, ".*too many arguments for hook \"hook-name\": snap-name foo bar.*")
}

func (s *snapExecSuite) TestFindCommand(c *C) {
	info, err := snap.InfoFromSnapYaml(mockYaml)
	c.Assert(err, IsNil)

	for _, t := range []struct {
		cmd      string
		expected string
	}{
		{cmd: "", expected: `run-app cmd-arg1 $SNAP_DATA`},
		{cmd: "stop", expected: "stop-app"},
		{cmd: "post-stop", expected: "post-stop-app"},
	} {
		cmd, err := snapExec.FindCommand(info.Apps["app"], t.cmd)
		c.Check(err, IsNil)
		c.Check(cmd, Equals, t.expected)
	}
}

func (s *snapExecSuite) TestFindCommandInvalidCommand(c *C) {
	info, err := snap.InfoFromSnapYaml(mockYaml)
	c.Assert(err, IsNil)

	_, err = snapExec.FindCommand(info.Apps["app"], "xxx")
	c.Check(err, ErrorMatches, `cannot use "xxx" command`)
}

func (s *snapExecSuite) TestFindCommandNoCommand(c *C) {
	info, err := snap.InfoFromSnapYaml(mockYaml)
	c.Assert(err, IsNil)

	_, err = snapExec.FindCommand(info.Apps["nostop"], "stop")
	c.Check(err, ErrorMatches, `no "stop" command found for "nostop"`)
}

func (s *snapExecSuite) TestSnapExecAppIntegration(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	execEnv := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		execEnv = env
		return nil
	})
	defer restore()

	// FIXME: TEST_PATH was meant to be just PATH but this uncovers another
	// bug in the test suite where mocking binaries misbehaves.
	oldPath := os.Getenv("TEST_PATH")
	os.Setenv("TEST_PATH", "/vanilla")
	defer os.Setenv("TEST_PATH", oldPath)

	// launch and verify its run the right way
	err := snapExec.ExecApp("snapname.app", "42", "stop", []string{"arg1", "arg2"})
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, fmt.Sprintf("%s/snapname/42/stop-app", dirs.SnapMountDir))
	c.Check(execArgs, DeepEquals, []string{execArgv0, "arg1", "arg2"})
	c.Check(execEnv, testutil.Contains, "BASE_PATH=/some/path")
	c.Check(execEnv, testutil.Contains, "LD_LIBRARY_PATH=/some/path/lib")
	c.Check(execEnv, testutil.Contains, fmt.Sprintf("MY_PATH=%s", os.Getenv("PATH")))
	// TEST_PATH is properly handled and we only see one value, /custom, defined
	// as an app-specific override.
	// See also https://bugs.launchpad.net/snapd/+bug/1860369
	c.Check(execEnv, Not(testutil.Contains), "TEST_PATH=/vanilla")
	c.Check(execEnv, testutil.Contains, "TEST_PATH=/custom")

	// ensure that CUPS_SERVER is absent since we didn't mock the /var/cups dir
	c.Check(execEnv, Not(testutil.Contains), "CUPS_SERVER=/var/cups")
}

func (s *snapExecSuite) TestSnapExecAppIntegrationCupsServerWorkaround(c *C) {
	dir := c.MkDir()
	dirs.SetRootDir(dir)
	snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	// mock the /var/cups dir is a bind-mount
	restore := snapExec.MockSyscallStat(func(p string, st *syscall.Stat_t) error {
		if strings.HasSuffix(p, "/var/cups/") {
			st.Dev = 2
		} else {
			st.Dev = 1
		}
		return nil
	})
	defer restore()

	execArgv0 := ""
	execArgs := []string{}
	execEnv := []string{}
	restore = snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		execEnv = env
		return nil
	})
	defer restore()

	// launch and verify its run the right way
	err := snapExec.ExecApp("snapname.app", "42", "stop", []string{"arg1", "arg2"})
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, fmt.Sprintf("%s/snapname/42/stop-app", dirs.SnapMountDir))
	c.Check(execArgs, DeepEquals, []string{execArgv0, "arg1", "arg2"})

	// ensure that CUPS_SERVER is now set since we did mock the /var/cups dir
	c.Check(execEnv, testutil.Contains, "CUPS_SERVER=/var/cups/cups.sock")
}

func (s *snapExecSuite) TestSnapExecAppCommandChainIntegration(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		return nil
	})
	defer restore()

	chain1_path := fmt.Sprintf("%s/snapname/42/chain1", dirs.SnapMountDir)
	chain2_path := fmt.Sprintf("%s/snapname/42/chain2", dirs.SnapMountDir)
	app_path := fmt.Sprintf("%s/snapname/42/run-app2", dirs.SnapMountDir)
	stop_path := fmt.Sprintf("%s/snapname/42/stop-app2", dirs.SnapMountDir)
	post_stop_path := fmt.Sprintf("%s/snapname/42/post-stop-app2", dirs.SnapMountDir)

	for _, t := range []struct {
		cmd      string
		args     []string
		expected []string
	}{
		// Normal command
		{expected: []string{chain1_path, chain2_path, app_path}},
		{args: []string{"arg1", "arg2"}, expected: []string{chain1_path, chain2_path, app_path, "arg1", "arg2"}},

		// Stop command
		{cmd: "stop", expected: []string{chain1_path, chain2_path, stop_path}},
		{cmd: "stop", args: []string{"arg1", "arg2"}, expected: []string{chain1_path, chain2_path, stop_path, "arg1", "arg2"}},

		// Post-stop command
		{cmd: "post-stop", expected: []string{chain1_path, chain2_path, post_stop_path}},
		{cmd: "post-stop", args: []string{"arg1", "arg2"}, expected: []string{chain1_path, chain2_path, post_stop_path, "arg1", "arg2"}},
	} {
		err := snapExec.ExecApp("snapname.app2", "42", t.cmd, t.args)
		c.Assert(err, IsNil)
		c.Check(execArgv0, Equals, t.expected[0])
		c.Check(execArgs, DeepEquals, t.expected)
	}
}

func (s *snapExecSuite) TestSnapExecHookIntegration(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockHookYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		return nil
	})
	defer restore()

	// launch and verify it ran correctly
	err := snapExec.ExecHook("snapname", "42", "configure")
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, fmt.Sprintf("%s/snapname/42/meta/hooks/configure", dirs.SnapMountDir))
	c.Check(execArgs, DeepEquals, []string{execArgv0})
}

func (s *snapExecSuite) TestSnapExecHookCommandChainIntegration(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockHookCommandChainYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		return nil
	})
	defer restore()

	chain1_path := fmt.Sprintf("%s/snapname/42/chain1", dirs.SnapMountDir)
	chain2_path := fmt.Sprintf("%s/snapname/42/chain2", dirs.SnapMountDir)
	hook_path := fmt.Sprintf("%s/snapname/42/meta/hooks/configure", dirs.SnapMountDir)

	err := snapExec.ExecHook("snapname", "42", "configure")
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, chain1_path)
	c.Check(execArgs, DeepEquals, []string{chain1_path, chain2_path, hook_path})
}

func (s *snapExecSuite) TestSnapExecHookMissingHookIntegration(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockHookYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	err := snapExec.ExecHook("snapname", "42", "missing-hook")
	c.Assert(err, NotNil)
	c.Assert(err, ErrorMatches, "cannot find hook \"missing-hook\" in \"snapname\"")
}

func (s *snapExecSuite) TestSnapExecIgnoresUnknownArgs(c *C) {
	snapApp, rest, err := snapExec.ParseArgs([]string{"--command=shell", "snapname.app", "--arg1", "arg2"})
	c.Assert(err, IsNil)
	c.Assert(snapExec.GetOptsCommand(), Equals, "shell")
	c.Assert(snapApp, DeepEquals, "snapname.app")
	c.Assert(rest, DeepEquals, []string{"--arg1", "arg2"})
}

func (s *snapExecSuite) TestSnapExecErrorsOnUnknown(c *C) {
	_, _, err := snapExec.ParseArgs([]string{"--command=shell", "--unknown", "snapname.app", "--arg1", "arg2"})
	c.Check(err, ErrorMatches, "unknown flag `unknown'")
}

func (s *snapExecSuite) TestSnapExecErrorsOnMissingSnapApp(c *C) {
	_, _, err := snapExec.ParseArgs([]string{"--command=shell"})
	c.Check(err, ErrorMatches, "need the application to run as argument")
}

func (s *snapExecSuite) TestSnapExecAppRealIntegration(c *C) {
	// we need a lot of mocks
	dirs.SetRootDir(c.MkDir())

	oldOsArgs := os.Args
	defer func() { os.Args = oldOsArgs }()

	os.Setenv("SNAP_REVISION", "42")
	defer os.Unsetenv("SNAP_REVISION")

	snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	canaryFile := filepath.Join(c.MkDir(), "canary.txt")
	script := fmt.Sprintf("%s/snapname/42/run-app", dirs.SnapMountDir)
	err := os.WriteFile(script, []byte(fmt.Sprintf(binaryTemplate, canaryFile)), 0755)
	c.Assert(err, IsNil)

	// we can not use the real syscall.execv here because it would
	// replace the entire test :)
	restore := snapExec.MockSyscallExec(actuallyExec)
	defer restore()

	// run it
	os.Args = []string{"snap-exec", "snapname.app", "foo", "--bar=baz", "foobar"}
	err = snapExec.Run()
	c.Assert(err, IsNil)

	c.Assert(canaryFile, testutil.FileEquals, `run-app
cmd-arg1
foo
--bar=baz
foobar

`)
}

func (s *snapExecSuite) TestSnapExecHookRealIntegration(c *C) {
	// we need a lot of mocks
	dirs.SetRootDir(c.MkDir())

	oldOsArgs := os.Args
	defer func() { os.Args = oldOsArgs }()

	os.Setenv("SNAP_REVISION", "42")
	defer os.Unsetenv("SNAP_REVISION")

	canaryFile := filepath.Join(c.MkDir(), "canary.txt")

	testSnap := snaptest.MockSnap(c, string(mockHookYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})
	hookPath := filepath.Join("meta", "hooks", "configure")
	hookPathAndContents := []string{hookPath, fmt.Sprintf(binaryTemplate, canaryFile)}
	snaptest.PopulateDir(testSnap.MountDir(), [][]string{hookPathAndContents})
	hookPath = filepath.Join(testSnap.MountDir(), hookPath)
	c.Assert(os.Chmod(hookPath, 0755), IsNil)

	// we can not use the real syscall.execv here because it would
	// replace the entire test :)
	restore := snapExec.MockSyscallExec(actuallyExec)
	defer restore()

	// run it
	os.Args = []string{"snap-exec", "--hook=configure", "snapname"}
	err := snapExec.Run()
	c.Assert(err, IsNil)

	c.Assert(canaryFile, testutil.FileEquals, "configure\n\n")
}

func actuallyExec(argv0 string, argv []string, env []string) error {
	cmd := exec.Command(argv[0], argv[1:]...)
	cmd.Env = env
	output, err := cmd.CombinedOutput()
	if len(output) > 0 {
		return fmt.Errorf("Expected output length to be 0, it was %d", len(output))
	}
	return err
}

func (s *snapExecSuite) TestSnapExecShellIntegration(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	execEnv := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		execEnv = env
		return nil
	})
	defer restore()

	// launch and verify its run the right way
	err := snapExec.ExecApp("snapname.app", "42", "shell", []string{"-c", "echo foo"})
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, "/bin/bash")
	c.Check(execArgs, DeepEquals, []string{execArgv0, "-c", "echo foo"})
	c.Check(execEnv, testutil.Contains, "LD_LIBRARY_PATH=/some/path/lib")

	// launch and verify shell still runs the command chain
	err = snapExec.ExecApp("snapname.app2", "42", "shell", []string{"-c", "echo foo"})
	c.Assert(err, IsNil)
	chain1 := fmt.Sprintf("%s/snapname/42/chain1", dirs.SnapMountDir)
	chain2 := fmt.Sprintf("%s/snapname/42/chain2", dirs.SnapMountDir)
	c.Check(execArgv0, Equals, chain1)
	c.Check(execArgs, DeepEquals, []string{chain1, chain2, "/bin/bash", "-c", "echo foo"})
}

func (s *snapExecSuite) TestSnapExecAppIntegrationWithVars(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	execEnv := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		execEnv = env
		return nil
	})
	defer restore()

	// setup env
	os.Setenv("SNAP_DATA", "/var/snap/snapname/42")
	defer os.Unsetenv("SNAP_DATA")

	// launch and verify its run the right way
	err := snapExec.ExecApp("snapname.app", "42", "", []string{"user-arg1"})
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, fmt.Sprintf("%s/snapname/42/run-app", dirs.SnapMountDir))
	c.Check(execArgs, DeepEquals, []string{execArgv0, "cmd-arg1", "/var/snap/snapname/42", "user-arg1"})
	c.Check(execEnv, testutil.Contains, "BASE_PATH=/some/path")
	c.Check(execEnv, testutil.Contains, "LD_LIBRARY_PATH=/some/path/lib")
	c.Check(execEnv, testutil.Contains, fmt.Sprintf("MY_PATH=%s", os.Getenv("PATH")))
}

func (s *snapExecSuite) TestSnapExecExpandEnvCmdArgs(c *C) {
	for _, t := range []struct {
		args     []string
		env      map[string]string
		expected []string
	}{
		{
			args:     []string{"foo"},
			env:      nil,
			expected: []string{"foo"},
		},
		{
			args:     []string{"$var"},
			env:      map[string]string{"var": "value"},
			expected: []string{"value"},
		},
		{
			args:     []string{"foo", "$not_existing"},
			env:      nil,
			expected: []string{"foo"},
		},
		{
			args:     []string{"foo", "$var", "baz"},
			env:      map[string]string{"var": "bar", "unrelated": "env"},
			expected: []string{"foo", "bar", "baz"},
		},
	} {
		env := osutil.Environment(t.env)
		c.Check(snapExec.ExpandEnvCmdArgs(t.args, env), DeepEquals, t.expected)
	}
}

func (s *snapExecSuite) TestSnapExecCompleteError(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	restore := snapExec.MockOsReadlink(func(p string) (string, error) {
		c.Assert(p, Equals, "/proc/self/exe")
		return "", fmt.Errorf("fail")
	})
	defer restore()

	// setup env
	os.Setenv("SNAP_DATA", "/var/snap/snapname/42")
	defer os.Unsetenv("SNAP_DATA")

	// launch and verify its run the right way
	err := snapExec.ExecApp("snapname.app", "42", "complete", []string{"foo"})
	c.Assert(err, ErrorMatches, "cannot find completion helper: fail")
}

func (s *snapExecSuite) TestSnapExecCompleteConfined(c *C) {
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		return nil
	})
	defer restore()

	restore = snapExec.MockOsReadlink(func(p string) (string, error) {
		c.Assert(p, Equals, "/proc/self/exe")
		// as if running inside the snap mount namespace
		return "/usr/lib/snapd/snap-exec", nil
	})
	defer restore()

	// setup env
	os.Setenv("SNAP_DATA", "/var/snap/snapname/42")
	defer os.Unsetenv("SNAP_DATA")

	// launch and verify its run the right way
	err := snapExec.ExecApp("snapname.app", "42", "complete", []string{"foo"})
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, "/bin/bash")
	c.Check(execArgs, DeepEquals, []string{execArgv0,
		dirs.CompletionHelperInCore,
		filepath.Join(dirs.SnapMountDir, "snapname/42/you/complete/me"),
		"foo"})
}

func (s *snapExecSuite) TestSnapExecCompleteClassicReexec(c *C) {
	restore := release.MockReleaseInfo(&release.OS{ID: "ubuntu"})
	defer restore()
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockClassicYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	restore = snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		return nil
	})
	defer restore()

	restore = snapExec.MockOsReadlink(func(p string) (string, error) {
		c.Assert(p, Equals, "/proc/self/exe")
		// as if it's reexeced from the snap
		return filepath.Join(dirs.SnapMountDir, "core/current", dirs.CoreLibExecDir, "snap-exec"), nil
	})
	defer restore()

	// setup env
	os.Setenv("SNAP_DATA", "/var/snap/snapname/42")
	defer os.Unsetenv("SNAP_DATA")

	// launch and verify its run the right way
	err := snapExec.ExecApp("snapname.app", "42", "complete", []string{"foo"})
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, "/bin/bash")
	c.Check(execArgs, DeepEquals, []string{execArgv0,
		filepath.Join(dirs.SnapMountDir, "core/current", dirs.CompletionHelperInCore),
		filepath.Join(dirs.SnapMountDir, "snapname/42/you/complete/me"),
		"foo"})
}

func (s *snapExecSuite) TestSnapExecCompleteClassicNoReexec(c *C) {
	restore := release.MockReleaseInfo(&release.OS{ID: "centos"})
	defer restore()
	dirs.SetRootDir(c.MkDir())
	snaptest.MockSnap(c, string(mockClassicYaml), &snap.SideInfo{
		Revision: snap.R("42"),
	})

	execArgv0 := ""
	execArgs := []string{}
	execEnv := []string{}
	restore = snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		execEnv = env
		return nil
	})
	defer restore()

	restore = snapExec.MockOsReadlink(func(p string) (string, error) {
		c.Assert(p, Equals, "/proc/self/exe")
		// running from distro libexecdir
		return filepath.Join(dirs.DistroLibExecDir, "snap-exec"), nil
	})
	defer restore()

	// setup env
	os.Setenv("SNAP_DATA", "/var/snap/snapname/42")
	defer os.Unsetenv("SNAP_DATA")
	os.Setenv("SNAP_SAVED_TMPDIR", "/var/tmp99")
	defer os.Unsetenv("SNAP_SAVED_TMPDIR")

	// launch and verify its run the right way
	err := snapExec.ExecApp("snapname.app", "42", "complete", []string{"foo"})
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, "/bin/bash")
	c.Check(execArgs, DeepEquals, []string{execArgv0,
		filepath.Join(dirs.DistroLibExecDir, "etelpmoc.sh"),
		filepath.Join(dirs.SnapMountDir, "snapname/42/you/complete/me"),
		"foo"})
	c.Check(execEnv, testutil.Contains, "SNAP_DATA=/var/snap/snapname/42")
	c.Check(execEnv, testutil.Contains, "TMPDIR=/var/tmp99")
}

func (s *snapExecSuite) TestSnapExecComponentHookIntegration(c *C) {
	dirs.SetRootDir(c.MkDir())
	snapInfo := snaptest.MockSnap(c, string(mockYaml), &snap.SideInfo{
		Revision: snap.R(42),
	})
	snaptest.MockComponentCurrent(c, string(mockComponentYaml), snapInfo, snap.ComponentSideInfo{
		Revision: snap.R(21),
	})

	execArgv0 := ""
	execArgs := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		return nil
	})
	defer restore()

	hookPath := filepath.Join(dirs.SnapMountDir, "/snapname/components/mnt/comp/21/meta/hooks/install")

	err := snapExec.ExecHook("snapname+comp", "42", "install")
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, hookPath)
	c.Check(execArgs, DeepEquals, []string{execArgv0})
}

func (s *snapExecSuite) TestSnapExecComponentHookCommandChainIntegration(c *C) {
	dirs.SetRootDir(c.MkDir())
	snapInfo := snaptest.MockSnap(c, string(mockHookCommandChainYaml), &snap.SideInfo{
		Revision: snap.R(42),
	})
	snaptest.MockComponentCurrent(c, string(mockComponentYaml), snapInfo, snap.ComponentSideInfo{
		Revision: snap.R(21),
	})

	execArgv0 := ""
	execArgs := []string{}
	restore := snapExec.MockSyscallExec(func(argv0 string, argv []string, env []string) error {
		execArgv0 = argv0
		execArgs = argv
		return nil
	})
	defer restore()

	chain3Path := filepath.Join(dirs.SnapMountDir, "/snapname/components/mnt/comp/21/chain3")
	chain4Path := filepath.Join(dirs.SnapMountDir, "/snapname/components/mnt/comp/21/chain4")
	hookPath := filepath.Join(dirs.SnapMountDir, "/snapname/components/mnt/comp/21/meta/hooks/install")

	err := snapExec.ExecHook("snapname+comp", "42", "install")
	c.Assert(err, IsNil)
	c.Check(execArgv0, Equals, chain3Path)
	c.Check(execArgs, DeepEquals, []string{chain3Path, chain4Path, hookPath})
}

func (s *snapExecSuite) TestSnapExecComponentWithoutHookError(c *C) {
	dirs.SetRootDir(c.MkDir())

	err := snapExec.ExecApp("snapname+comp", "42", "complete", []string{"foo"})
	c.Assert(err, ErrorMatches, `snap-exec cannot run a snap component without a hook specified \(use --hook\)`)
}