github.com/Lephar/snapd@v0.0.0-20210825215435-c7fba9cef4d2/systemd/systemdtest/systemdtest.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2021 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 systemdtest 21 22 import ( 23 "fmt" 24 25 "github.com/snapcore/snapd/osutil" 26 ) 27 28 type ServiceState struct { 29 ActiveState string 30 UnitFileState string 31 } 32 33 // HandleMockAllUnitsActiveOutput returns the output for systemctl in the case 34 // where units have the state as described by states. 35 // If `cmd` is the command issued by systemd.Status(), this function returns 36 // the output to be produced by the command so that the queried services will 37 // appear having the ActiveState and UnitFileState according to the data 38 // passed in the `states` map. 39 func HandleMockAllUnitsActiveOutput(cmd []string, states map[string]ServiceState) []byte { 40 osutil.MustBeTestBinary("mocking systemctl output can only be done from tests") 41 if cmd[0] != "show" || 42 cmd[1] != "--property=Id,ActiveState,UnitFileState,Type" { 43 return nil 44 } 45 var output []byte 46 for _, unit := range cmd[2:] { 47 if len(output) > 0 { 48 output = append(output, byte('\n')) 49 } 50 state, ok := states[unit] 51 if !ok { 52 state = ServiceState{"active", "enabled"} 53 } 54 output = append(output, []byte(fmt.Sprintf(`Id=%s 55 ActiveState=%s 56 UnitFileState=%s 57 Type=simple 58 `, unit, state.ActiveState, state.UnitFileState))...) 59 } 60 return output 61 }