File: context_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 (284 lines) | stat: -rw-r--r-- 8,376 bytes parent folder | download | duplicates (2)
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
// -*- 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 hookstate

import (
	"encoding/json"
	"os"

	. "gopkg.in/check.v1"

	"github.com/snapcore/snapd/logger"
	"github.com/snapcore/snapd/overlord/state"
	"github.com/snapcore/snapd/snap"
)

type contextSuite struct {
	context *Context
	task    *state.Task
	state   *state.State
	setup   *HookSetup

	componentContext *Context
	componentSetup   *HookSetup
	componentTask    *state.Task
}

var _ = Suite(&contextSuite{})

func (s *contextSuite) SetUpTest(c *C) {
	s.state = state.New(nil)
	s.state.Lock()
	defer s.state.Unlock()

	s.task = s.state.NewTask("test-task", "my test task")
	s.setup = &HookSetup{Snap: "test-snap", Revision: snap.R(1), Hook: "test-hook"}
	var err error
	s.context, err = NewContext(s.task, s.task.State(), s.setup, nil, "")
	c.Check(err, IsNil)

	s.componentTask = s.state.NewTask("standard-component-task", "my test component task")
	s.componentSetup = &HookSetup{
		Snap:              "test-snap",
		Revision:          snap.R(1),
		Hook:              "test-hook",
		Component:         "standard-component",
		ComponentRevision: snap.R(2),
	}
	s.componentContext, err = NewContext(s.componentTask, s.componentTask.State(), s.componentSetup, nil, "")
	c.Check(err, IsNil)
}

func (s *contextSuite) TestHookSetup(c *C) {
	c.Check(s.context.HookName(), Equals, "test-hook")
	c.Check(s.context.InstanceName(), Equals, "test-snap")
	c.Check(s.context.IsSnapHook(), Equals, true)
	c.Check(s.context.IsComponentHook(), Equals, false)

	c.Check(s.componentContext.ComponentName(), Equals, "standard-component")
	c.Check(s.componentContext.ComponentRevision(), Equals, snap.R(2))
	c.Check(s.componentContext.IsSnapHook(), Equals, false)
	c.Check(s.componentContext.IsComponentHook(), Equals, true)
}

func (s *contextSuite) TestHookSource(c *C) {
	c.Check(s.context.HookSource(), Equals, "test-snap")
	c.Check(s.componentContext.HookSource(), Equals, "test-snap+standard-component")

	// insert an instance key for a quick test
	s.componentContext.setup.Snap = "test-snap_instance-key"
	defer func() { s.componentContext.setup.Snap = "test-snap" }()

	c.Check(s.componentContext.HookSource(), Equals, "test-snap_instance-key+standard-component")
}

func (s *contextSuite) TestSetAndGet(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	var output string
	c.Check(s.context.Get("foo", &output), NotNil)

	s.context.Set("foo", "bar")
	c.Check(s.context.Get("foo", &output), IsNil, Commentf("Expected context to contain 'foo'"))
	c.Check(output, Equals, "bar")

	// Test another non-existing key, but after the context data was created.
	c.Check(s.context.Get("baz", &output), NotNil)
}

func (s *contextSuite) TestSetAndGetNumber(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	s.context.Set("num", 1234567890)

	var output any
	c.Check(s.context.Get("num", &output), IsNil)
	c.Assert(output, Equals, json.Number("1234567890"))
}

func (s *contextSuite) TestSetPersistence(c *C) {
	s.context.Lock()
	s.context.Set("foo", "bar")
	s.context.Unlock()

	// Verify that "foo" is still "bar" within another context of the same hook
	// on the same task.
	anotherContext := &Context{task: s.task, state: s.task.State(), setup: s.setup}
	anotherContext.Lock()
	defer anotherContext.Unlock()

	var output string
	c.Check(anotherContext.Get("foo", &output), IsNil, Commentf("Expected new context to also contain 'foo'"))
	c.Check(output, Equals, "bar")
}

func (s *contextSuite) TestSetUnmarshalable(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	defer func() {
		c.Check(recover(), Matches, ".*cannot marshal context value.*", Commentf("Expected panic when attempting install"))
	}()

	s.context.Set("foo", func() {})
}

func (s *contextSuite) TestGetIsolatedFromTask(c *C) {
	// Set data in the task itself
	s.task.State().Lock()
	s.task.Set("foo", "bar")
	s.task.State().Unlock()

	s.context.Lock()
	defer s.context.Unlock()

	// Verify that "foo" is not set when asking for data from the hook context
	var output string
	c.Check(s.context.Get("foo", &output), NotNil, Commentf("Expected context data to be isolated from task"))
}

func (s *contextSuite) TestCache(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	c.Check(s.context.Cached("foo"), IsNil)

	s.context.Cache("foo", "bar")
	c.Check(s.context.Cached("foo"), Equals, "bar")

	// Test another non-existing key, but after the context cache was created.
	c.Check(s.context.Cached("baz"), IsNil)
}

func (s *contextSuite) TestDone(c *C) {
	s.context.Lock()
	defer s.context.Unlock()

	called := false
	s.context.OnDone(func() error {
		called = true
		return nil
	})

	s.context.Done()
	c.Check(called, Equals, true, Commentf("Expected finalizer to be called"))
}

func (s *contextSuite) TestEphemeralContextGetSet(c *C) {
	context, err := NewContext(nil, s.state, &HookSetup{Snap: "test-snap"}, nil, "")
	c.Assert(err, IsNil)
	context.Lock()
	defer context.Unlock()

	var output string
	c.Check(context.Get("foo", &output), NotNil)

	context.Set("foo", "bar")
	c.Check(context.Get("foo", &output), IsNil, Commentf("Expected context to contain 'foo'"))
	c.Check(output, Equals, "bar")

	// Test another non-existing key, but after the context data was created.
	c.Check(context.Get("baz", &output), NotNil)
}

func (s *contextSuite) TestChangeID(c *C) {
	context, err := NewContext(nil, s.state, &HookSetup{Snap: "test-snap"}, nil, "")
	c.Assert(err, IsNil)
	c.Check(context.ChangeID(), Equals, "")

	s.state.Lock()
	defer s.state.Unlock()

	task := s.state.NewTask("foo", "")
	context, err = NewContext(task, s.state, &HookSetup{Snap: "test-snap"}, nil, "")
	c.Assert(err, IsNil)
	c.Check(context.ChangeID(), Equals, "")

	chg := s.state.NewChange("bar", "")
	chg.AddTask(task)
	context, err = NewContext(task, s.state, &HookSetup{Snap: "test-snap"}, nil, "")
	c.Assert(err, IsNil)
	c.Check(context.ChangeID(), Equals, chg.ID())
}

func (s *contextSuite) TestChangeErrorf(c *C) {
	mockLog, restore := logger.MockLogger()
	defer restore()

	if v, ok := os.LookupEnv("SNAPD_DEBUG"); ok {
		os.Unsetenv("SNAPD_DEBUG")
		defer os.Setenv("SNAPD_DEBUG=%v", v)
	}

	s.state.Lock()
	task1 := s.state.NewTask("foo1", "summary foo1")
	task2 := s.state.NewTask("foo2", "summary foo2")
	s.state.Unlock()

	for _, tc := range []struct {
		task                 *state.Task
		ignoreError          bool
		expectedLoggerOutput string
		expectedTaskLog      string
	}{
		{nil, false, `.* context.go:.*: some error\n`, ``},
		{nil, true, `.* context.go:.*: some error\n`, ``},
		// ignore error hooks log errors to both logger and task
		{task1, true, `.* context.go:.*: ERROR task ` + task1.ID() + ` \(summary foo1\): some error\n`, `.* ERROR some error`},
		// normal hooks only log errors to the task
		{task2, false, ``, `.* ERROR some error`},
	} {
		hs := &HookSetup{Snap: "test-snap", IgnoreError: tc.ignoreError}
		context, err := NewContext(tc.task, s.state, hs, nil, "")
		c.Assert(err, IsNil)
		context.Lock()
		context.Errorf("some error")
		context.Unlock()
		c.Check(mockLog.String(), Matches, tc.expectedLoggerOutput)
		mockLog.Reset()
		if tc.task != nil {
			s.state.Lock()
			taskLog := tc.task.Log()
			s.state.Unlock()
			if tc.expectedTaskLog != "" {
				c.Assert(taskLog, HasLen, 1)
				c.Check(taskLog[0], Matches, tc.expectedTaskLog)
			} else {
				c.Assert(taskLog, HasLen, 0)
			}
		}
	}
}

func (s *contextSuite) TestChangeErrorfHookSetupNilPointerDoesNotCausePanic(c *C) {
	s.state.Lock()
	task := s.state.NewTask("foo", "")
	s.state.Unlock()

	var hookSetup *HookSetup = nil
	context, err := NewContext(task, s.state, hookSetup, nil, "")
	c.Assert(err, IsNil)
	// it's enough to check here that there is no panic from "nil" hookSetup
	context.Lock()
	context.Errorf("some error")
	context.Unlock()
}