github.com/meulengracht/snapd@v0.0.0-20210719210640-8bde69bcc84e/systemd/sdnotify_test.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2014-2015 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 systemd_test 21 22 import ( 23 "net" 24 "os" 25 "path/filepath" 26 27 . "gopkg.in/check.v1" 28 29 "github.com/snapcore/snapd/systemd" 30 ) 31 32 type sdNotifyTestSuite struct{} 33 34 var _ = Suite(&sdNotifyTestSuite{}) 35 36 func (sd *sdNotifyTestSuite) TestSdNotifyMissingNotifyState(c *C) { 37 c.Check(systemd.SdNotify(""), ErrorMatches, "cannot use empty notify state") 38 } 39 40 func (sd *sdNotifyTestSuite) TestSdNotifyWrongNotifySocket(c *C) { 41 for _, t := range []struct { 42 env string 43 errStr string 44 }{ 45 {"", "cannot find NOTIFY_SOCKET environment"}, 46 {"xxx", `cannot use NOTIFY_SOCKET "xxx"`}, 47 } { 48 os.Setenv("NOTIFY_SOCKET", t.env) 49 defer os.Unsetenv("NOTIFY_SOCKET") 50 51 c.Check(systemd.SdNotify("something"), ErrorMatches, t.errStr) 52 } 53 } 54 55 func (sd *sdNotifyTestSuite) TestSdNotifyIntegration(c *C) { 56 fakeEnv := map[string]string{} 57 restore := systemd.MockOsGetenv(func(k string) string { 58 return fakeEnv[k] 59 }) 60 defer restore() 61 62 for _, sockPath := range []string{ 63 filepath.Join(c.MkDir(), "socket"), 64 "@socket", 65 } { 66 fakeEnv["NOTIFY_SOCKET"] = sockPath 67 68 conn, err := net.ListenUnixgram("unixgram", &net.UnixAddr{ 69 Name: sockPath, 70 Net: "unixgram", 71 }) 72 c.Assert(err, IsNil) 73 defer conn.Close() 74 75 ch := make(chan string) 76 go func() { 77 var buf [128]byte 78 n, err := conn.Read(buf[:]) 79 c.Assert(err, IsNil) 80 ch <- string(buf[:n]) 81 }() 82 83 err = systemd.SdNotify("something") 84 c.Assert(err, IsNil) 85 c.Check(<-ch, Equals, "something") 86 } 87 }