-
Notifications
You must be signed in to change notification settings - Fork 680
Expand file tree
/
Copy pathexport_test.go
More file actions
651 lines (545 loc) · 17.8 KB
/
Copy pathexport_test.go
File metadata and controls
651 lines (545 loc) · 17.8 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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2016-2022 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 snapstate
import (
"context"
"time"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/asserts/snapasserts"
"github.com/snapcore/snapd/overlord/snapstate/backend"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/store"
"github.com/snapcore/snapd/testutil"
userclient "github.com/snapcore/snapd/usersession/client"
)
type (
ManagerBackend managerBackend
MinimalInstallInfo = minimalInstallInfo
SnapUpdate = update
InstallSnapInfo = installSnapInfo
DirMigrationOptions = dirMigrationOptions
Migration = migration
ReRefreshSetup = reRefreshSetup
TooSoonError = tooSoonError
Target = target
InstallContext = installContext
)
var ComponentSetupTask = componentSetupTask
var RemoveComponentTasks = removeComponentTasks
const (
None = none
Full = full
Hidden = hidden
Home = home
RevertHidden = revertHidden
DisableHome = disableHome
RevertFull = revertFull
)
func SetSnapManagerBackend(s *SnapManager, b ManagerBackend) {
s.backend = b
}
func MockSnapReadInfo(mock func(name string, si *snap.SideInfo) (*snap.Info, error)) (restore func()) {
old := snapReadInfo
snapReadInfo = mock
return func() { snapReadInfo = old }
}
func MockReadComponentInfo(mock func(compMntDir string, snapInfo *snap.Info, csi *snap.ComponentSideInfo) (*snap.ComponentInfo, error)) (restore func()) {
old := readComponentInfoAt
readComponentInfoAt = mock
return func() { readComponentInfoAt = old }
}
func MockMountPollInterval(intv time.Duration) (restore func()) {
old := mountPollInterval
mountPollInterval = intv
return func() { mountPollInterval = old }
}
func MockRevisionDate(mock func(info *snap.Info) time.Time) (restore func()) {
old := revisionDate
if mock == nil {
mock = revisionDateImpl
}
revisionDate = mock
return func() { revisionDate = old }
}
func MockOpenSnapFile(mock func(path string, si *snap.SideInfo) (*snap.Info, snap.Container, error)) (restore func()) {
prevOpenSnapFile := openSnapFile
openSnapFile = mock
return func() { openSnapFile = prevOpenSnapFile }
}
func MockPrerequisitesRetryTimeout(d time.Duration) (restore func()) {
old := prerequisitesRetryTimeout
prerequisitesRetryTimeout = d
return func() { prerequisitesRetryTimeout = old }
}
func MockOsutilEnsureSnapUserGroup(mock func(name string, id uint32, extraUsers bool) error) (restore func()) {
old := osutilEnsureSnapUserGroup
osutilEnsureSnapUserGroup = mock
return func() { osutilEnsureSnapUserGroup = old }
}
var (
CoreInfoInternal = coreInfo
CheckSnap = checkSnap
CanRemove = canRemove
CanDisable = canDisable
CachedStore = cachedStore
DefaultRefreshSchedule = defaultRefreshScheduleStr
DoInstallOrPreDownload = doInstallOrPreDownload
UserFromUserID = userFromUserID
ValidateFeatureFlags = validateFeatureFlags
ResolveChannel = resolveChannel
CurrentSnaps = currentSnaps
HasOtherInstances = hasOtherInstances
SafetyMarginDiskSpace = safetyMarginDiskSpace
AffectedByRefresh = affectedByRefresh
GetDirMigrationOpts = getDirMigrationOpts
WriteSeqFile = writeSeqFile
TriggeredMigration = triggeredMigration
TaskSetsByTypeForEssentialSnaps = taskSetsByTypeForEssentialSnaps
SetDefaultRestartBoundaries = setDefaultRestartBoundaries
DeviceModelBootBase = deviceModelBootBase
ReRefreshSummary = reRefreshSummary
MaybeFindTasksetForSnap = maybeFindTasksetForSnap
)
func PreviousSideInfo(snapst *SnapState) *snap.SideInfo {
return snapst.previousSideInfo()
}
// helpers
var (
InstallSize = installSize
ResealingTaskBlocked = resealingTaskBlocked
)
func ResealingTaskKinds() []string {
kinds := make([]string, 0, len(resealingTaskKindCheckers))
for kind := range resealingTaskKindCheckers {
kinds = append(kinds, kind)
}
return kinds
}
// aliases v2
var (
ApplyAliasesChange = applyAliasesChange
AutoAliasesDelta = autoAliasesDelta
RefreshAliases = refreshAliases
CheckAliasesConflicts = checkAliasesConflicts
DisableAliases = disableAliases
SwitchSummary = switchSummary
)
// dbus
var (
CheckDBusServiceConflicts = checkDBusServiceConflicts
)
// desktop-file-ids
var (
CheckDesktopFileIDsConflicts = checkDesktopFileIDsConflicts
)
// readme files
var (
WriteSnapReadme = writeSnapReadme
SnapReadme = snapReadme
)
// refreshes
var (
NewAutoRefresh = newAutoRefresh
NewRefreshHints = newRefreshHints
CanRefreshOnMeteredConnection = canRefreshOnMeteredConnection
NewCatalogRefresh = newCatalogRefresh
CatalogRefreshDelayBase = catalogRefreshDelayBase
CatalogRefreshDelayWithDelta = catalogRefreshDelayWithDelta
SoftCheckNothingRunningForRefresh = softCheckNothingRunningForRefresh
HardEnsureNothingRunningDuringRefresh = hardEnsureNothingRunningDuringRefresh
)
// cleanup
var (
CleanSnapDownloads = cleanSnapDownloads
CleanDownloads = cleanDownloads
)
func MockMaxUnusedDownloadRetention(t time.Duration) func() {
old := maxUnusedDownloadRetention
maxUnusedDownloadRetention = t
return func() {
maxUnusedDownloadRetention = old
}
}
func MockCleanDownloads(mock func(st *state.State) error) func() {
old := cleanDownloads
cleanDownloads = mock
return func() {
cleanDownloads = old
}
}
func MockCleanSnapDownloads(mock func(st *state.State, snapName string) error) func() {
old := cleanSnapDownloads
cleanSnapDownloads = mock
return func() {
cleanSnapDownloads = old
}
}
// install
var HasAllContentAttrs = hasAllContentAttrs
func MockNextRefresh(ar *autoRefresh, when time.Time) {
ar.nextRefresh = when
}
func (snapmgr *SnapManager) MockNextRefresh(when time.Time) {
snapmgr.autoRefresh.nextRefresh = when
}
func MockLastRefreshSchedule(ar *autoRefresh, schedule string) {
ar.lastRefreshSchedule = schedule
}
func MockCatalogRefreshNextRefresh(cr *catalogRefresh, when time.Time) {
cr.nextCatalogRefresh = when
}
func NextCatalogRefresh(cr *catalogRefresh) time.Time {
return cr.nextCatalogRefresh
}
func MockRefreshRetryDelay(d time.Duration) func() {
origRefreshRetryDelay := refreshRetryDelay
refreshRetryDelay = d
return func() {
refreshRetryDelay = origRefreshRetryDelay
}
}
func MockIsOnMeteredConnection(mock func() (bool, error)) func() {
old := IsOnMeteredConnection
IsOnMeteredConnection = mock
return func() {
IsOnMeteredConnection = old
}
}
func MockLocalInstallCleanupWait(d time.Duration) (restore func()) {
old := localInstallCleanupWait
localInstallCleanupWait = d
return func() {
localInstallCleanupWait = old
}
}
func MockLocalInstallLastCleanup(t time.Time) (restore func()) {
old := localInstallLastCleanup
localInstallLastCleanup = t
return func() {
localInstallLastCleanup = old
}
}
func MockAsyncPendingRefreshNotification(fn func(context.Context, *userclient.PendingSnapRefreshInfo)) (restore func()) {
old := asyncPendingRefreshNotification
asyncPendingRefreshNotification = fn
return func() {
asyncPendingRefreshNotification = old
}
}
func MockHasActiveConnection(fn func(st *state.State, iface string) (bool, error)) (restore func()) {
old := HasActiveConnection
HasActiveConnection = fn
return func() {
HasActiveConnection = old
}
}
func MockOnRefreshInhibitionTimeout(fn func(chg *state.Change, snapName string) error) (restore func()) {
old := onRefreshInhibitionTimeout
onRefreshInhibitionTimeout = fn
return func() {
onRefreshInhibitionTimeout = old
}
}
// re-refresh related
var (
RefreshedSnaps = refreshedSnaps
ReRefreshFilter = reRefreshFilter
UpdateManyFiltered = updateManyFiltered
MaybeRestoreValidationSetsAndRevertSnaps = maybeRestoreValidationSetsAndRevertSnaps
)
type UpdateFilter = updateFilter
func MockReRefreshUpdateMany(f func(context.Context, *state.State, []string, []*RevisionOptions, int, UpdateFilter, *Flags, string) ([]string, *UpdateTaskSets, error)) (restore func()) {
old := reRefreshUpdateMany
reRefreshUpdateMany = f
return func() {
reRefreshUpdateMany = old
}
}
func MockReRefreshRetryTimeout(d time.Duration) (restore func()) {
old := reRefreshRetryTimeout
reRefreshRetryTimeout = d
return func() {
reRefreshRetryTimeout = old
}
}
type DisabledServices = disabledServices
// link, misc handlers
var (
MissingDisabledServices = missingDisabledServices
)
func (m *SnapManager) MaybeUndoRemodelBootChanges(t *state.Task) (restartRequested, rebootRequired bool, err error) {
restartPoss, err := m.maybeUndoRemodelBootChanges(t)
if restartPoss != nil {
return true, restartPoss.RebootRequired, nil
}
return false, false, err
}
func MockEnsuredDesktopFilesUpdated(m *SnapManager, ensured bool) (restore func()) {
old := m.ensuredDesktopFilesUpdated
m.ensuredDesktopFilesUpdated = ensured
return func() {
m.ensuredDesktopFilesUpdated = old
}
}
func SetEnsuredDownloadsCleanedNext(m *SnapManager, next time.Time) {
m.ensuredDownloadsCleanedNext = next
}
func GetEnsuredDownloadsCleanedNext(m *SnapManager) time.Time {
return m.ensuredDownloadsCleanedNext
}
func MockPidsOfSnap(f func(instanceName string) (map[string][]int, error)) func() {
old := pidsOfSnap
pidsOfSnap = f
return func() {
pidsOfSnap = old
}
}
func MockCurrentSnaps(f func(st *state.State) ([]*store.CurrentSnap, error)) func() {
old := currentSnaps
currentSnaps = f
return func() {
currentSnaps = old
}
}
func MockInstallSize(f func(st *state.State, snaps []minimalInstallInfo, userID int, preqt PrereqTracker) (uint64, error)) func() {
old := installSize
installSize = f
return func() {
installSize = old
}
}
func MockGenerateSnapdWrappers(f func(snapInfo *snap.Info, opts *backend.GenerateSnapdWrappersOptions) error) func() {
old := generateSnapdWrappers
generateSnapdWrappers = f
return func() {
generateSnapdWrappers = old
}
}
var (
NotifyLinkParticipants = notifyLinkParticipants
)
// autorefresh
var (
InhibitRefresh = inhibitRefresh
MaxDuration = maxDuration
MaxInhibitionDuration = maxInhibitionDuration
MaybeAddRefreshInhibitNotice = maybeAddRefreshInhibitNotice
MaybeAsyncPendingRefreshNotification = maybeAsyncPendingRefreshNotification
)
type RefreshCandidate = refreshCandidate
type TimedBusySnapError = timedBusySnapError
func NewBusySnapError(info *snap.Info, pids []int, busyAppNames, busyHookNames []string) *BusySnapError {
return &BusySnapError{
SnapInfo: info,
pids: pids,
busyAppNames: busyAppNames,
busyHookNames: busyHookNames,
}
}
func MockRefreshAppsCheck(fn func(info *snap.Info) error) (restore func()) {
old := refreshAppsCheck
refreshAppsCheck = fn
return func() { refreshAppsCheck = old }
}
func (m *autoRefresh) EnsureRefreshHoldAtLeast(d time.Duration) error {
return m.ensureRefreshHoldAtLeast(d)
}
func MockSecurityProfilesDiscardLate(fn func(snapName string, rev snap.Revision, typ snap.Type) error) (restore func()) {
old := SecurityProfilesRemoveLate
SecurityProfilesRemoveLate = fn
return func() {
SecurityProfilesRemoveLate = old
}
}
type HoldState = holdState
var (
HoldDurationLeft = holdDurationLeft
LastRefreshed = lastRefreshed
PruneRefreshCandidates = pruneRefreshCandidates
UpdateRefreshCandidates = updateRefreshCandidates
ResetGatingForRefreshed = resetGatingForRefreshed
PruneGating = pruneGating
PruneSnapsHold = pruneSnapsHold
CreateGateAutoRefreshHooks = createGateAutoRefreshHooks
AutoRefreshPhase1 = autoRefreshPhase1
RefreshRetain = refreshRetain
RefreshCheck = refreshAppsCheck
AffectsRunningHooks = affectsRunningHooks
ShouldScheduleUpdateCertDBForRefresh = shouldScheduleUpdateCertDBForRefresh
ExcludeFromRefreshAppAwareness = excludeFromRefreshAppAwareness
)
func MockTimeNow(f func() time.Time) (restore func()) {
old := timeNow
timeNow = f
return func() {
timeNow = old
}
}
func MockHoldState(firstHeld string, holdUntil string) *HoldState {
first, err := time.Parse(time.RFC3339, firstHeld)
if err != nil {
panic(err)
}
var until time.Time
if holdUntil != "forever" {
var err error
until, err = time.Parse(time.RFC3339, holdUntil)
if err != nil {
panic(err)
}
} else {
until = first.Add(maxDuration)
}
return &holdState{
FirstHeld: first,
HoldUntil: until,
}
}
func MockSnapsToRefresh(f func(gatingTask *state.Task) ([]*refreshCandidate, error)) (restore func()) {
old := snapsToRefresh
snapsToRefresh = f
return func() {
snapsToRefresh = old
}
}
func MockExcludeFromRefreshAppAwareness(f func(t snap.Type) bool) (restore func()) {
r := testutil.Backup(&excludeFromRefreshAppAwareness)
excludeFromRefreshAppAwareness = f
return r
}
func MockAddCurrentTrackingToValidationSetsStack(f func(st *state.State) error) (restore func()) {
old := AddCurrentTrackingToValidationSetsStack
AddCurrentTrackingToValidationSetsStack = f
return func() {
AddCurrentTrackingToValidationSetsStack = old
}
}
func MockRestoreValidationSetsTracking(f func(*state.State) error) (restore func()) {
old := RestoreValidationSetsTracking
RestoreValidationSetsTracking = f
return func() {
RestoreValidationSetsTracking = old
}
}
func MockMaybeRestoreValidationSetsAndRevertSnaps(f func(st *state.State, refreshedSnaps []string, fromChange string) ([]*state.TaskSet, error)) (restore func()) {
old := maybeRestoreValidationSetsAndRevertSnaps
maybeRestoreValidationSetsAndRevertSnaps = f
return func() {
maybeRestoreValidationSetsAndRevertSnaps = old
}
}
func MockGetHiddenDirOptions(f func(*state.State, *SnapState, *SnapSetup) (*dirMigrationOptions, error)) (restore func()) {
old := getDirMigrationOpts
getDirMigrationOpts = f
return func() {
getDirMigrationOpts = old
}
}
func MockEnforcedValidationSets(f func(st *state.State, extraVss ...*asserts.ValidationSet) (*snapasserts.ValidationSets, error)) func() {
old := EnforcedValidationSets
EnforcedValidationSets = f
return func() {
EnforcedValidationSets = old
}
}
func MockEnforceValidationSets(f func(*state.State, map[string]*asserts.ValidationSet, map[string]int, []*snapasserts.InstalledSnap, map[string]bool, int) error) func() {
old := EnforceValidationSets
EnforceValidationSets = f
return func() {
EnforceValidationSets = old
}
}
func MockEnforceLocalValidationSets(f func(*state.State, map[string][]string, map[string]int, []*snapasserts.InstalledSnap, map[string]bool) error) func() {
old := EnforceLocalValidationSets
EnforceLocalValidationSets = f
return func() {
EnforceLocalValidationSets = old
}
}
func MockCgroupMonitorSnapEnded(f func(string, chan<- string) error) func() {
old := cgroupMonitorSnapEnded
cgroupMonitorSnapEnded = f
return func() {
cgroupMonitorSnapEnded = old
}
}
func SetRestoredMonitoring(snapmgr *SnapManager, value bool) {
snapmgr.autoRefresh.restoredMonitoring = value
}
func SetPreseed(snapmgr *SnapManager, value bool) {
snapmgr.preseed = value
}
func SetStoreCacheCleanNext(snapmgr *SnapManager, when time.Time) {
snapmgr.ensureStoreCacheCleanNext = when
}
func GetStoreCacheCleanNext(snapmgr *SnapManager) time.Time {
return snapmgr.ensureStoreCacheCleanNext
}
func SplitEssentialUpdates(deviceCtx DeviceContext, updates []SnapUpdate) (essential, nonEssential []SnapUpdate) {
return splitEssentialUpdates(deviceCtx, updates)
}
func MockAffectedSnapsByAttr(value map[string]AffectedSnapsFunc) (restore func()) {
old := affectedSnapsByAttr
affectedSnapsByAttr = value
return func() {
affectedSnapsByAttr = old
}
}
func MockAffectedSnapsByKind(value map[string]AffectedSnapsFunc) (restore func()) {
old := affectedSnapsByKind
affectedSnapsByKind = value
return func() {
affectedSnapsByKind = old
}
}
// CustomInstallGoal allows us to define custom implementations of installGoal
// to be used in tests.
type CustomInstallGoal struct {
ToInstall func(context.Context, *state.State, Options) ([]Target, error)
}
func (c *CustomInstallGoal) toInstall(ctx context.Context, st *state.State, opts Options) ([]Target, error) {
return c.ToInstall(ctx, st, opts)
}
func (sts *snapInstallTaskSet) TaskSet() *state.TaskSet {
return sts.ts
}
type SnapInstallTaskSet = snapInstallTaskSet
func NewSnapInstallTaskSetForTest(
snapsup *SnapSetup,
ts *state.TaskSet,
beforeLocalSystemModificationsTasks []*state.Task,
mountSnap *state.Task,
upToLinkSnapAndBeforeReboot, afterLinkSnapAndPostReboot []*state.Task,
) SnapInstallTaskSet {
return SnapInstallTaskSet{
ts: ts,
snapsup: snapsup,
beforeLocalSystemModificationsTasks: beforeLocalSystemModificationsTasks,
mountSnap: mountSnap,
upToLinkSnapAndBeforeReboot: upToLinkSnapAndBeforeReboot,
afterLinkSnapAndPostReboot: afterLinkSnapAndPostReboot,
}
}
var ArrangeRebootAndUpdateSeed = arrangeRebootAndUpdateSeed
func MockProcessDelayedSecurityBackendEffects(f func(st *state.State, lanes []int, joinLane int) (ts *state.TaskSet)) (restore func()) {
return testutil.Mock(&ProcessDelayedSecurityBackendEffects, f)
}
func MockGadgetSetFallbackDefaults(f func(values map[string]any)) (restore func()) {
return testutil.Mock(&gadgetSetFallbackDefaults, f)
}