github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/overlord/hookstate/ctlcmd/export_test.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2016 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package ctlcmd 21 22 import ( 23 "fmt" 24 25 "github.com/snapcore/snapd/overlord/hookstate" 26 "github.com/snapcore/snapd/overlord/servicestate" 27 "github.com/snapcore/snapd/overlord/state" 28 "github.com/snapcore/snapd/snap" 29 ) 30 31 var AttributesTask = attributesTask 32 33 func MockServicestateControlFunc(f func(*state.State, []*snap.AppInfo, *servicestate.Instruction, *hookstate.Context) ([]*state.TaskSet, error)) (restore func()) { 34 old := servicestateControl 35 servicestateControl = f 36 return func() { servicestateControl = old } 37 } 38 39 func AddMockCommand(name string) *MockCommand { 40 return addMockCmd(name, false) 41 } 42 43 func AddHiddenMockCommand(name string) *MockCommand { 44 return addMockCmd(name, true) 45 } 46 47 func addMockCmd(name string, hidden bool) *MockCommand { 48 mockCommand := NewMockCommand() 49 cmd := addCommand(name, "", "", func() command { return mockCommand }) 50 cmd.hidden = hidden 51 return mockCommand 52 } 53 54 func RemoveCommand(name string) { 55 delete(commands, name) 56 } 57 58 type MockCommand struct { 59 baseCommand 60 61 ExecuteError bool 62 FakeStdout string 63 FakeStderr string 64 65 Args []string 66 } 67 68 func NewMockCommand() *MockCommand { 69 return &MockCommand{ 70 ExecuteError: false, 71 } 72 } 73 74 func (c *MockCommand) Execute(args []string) error { 75 c.Args = args 76 77 if c.FakeStdout != "" { 78 c.printf(c.FakeStdout) 79 } 80 81 if c.FakeStderr != "" { 82 c.errorf(c.FakeStderr) 83 } 84 85 if c.ExecuteError { 86 return fmt.Errorf("failed at user request") 87 } 88 89 return nil 90 }