...

Source file src/github.com/coreos/go-systemd/v22/daemon/sdnotify_test.go

Documentation: github.com/coreos/go-systemd/v22/daemon

     1  // Copyright 2016 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package daemon
    16  
    17  import (
    18  	"fmt"
    19  	"io/ioutil"
    20  	"net"
    21  	"os"
    22  	"testing"
    23  )
    24  
    25  // TestSdNotify
    26  func TestSdNotify(t *testing.T) {
    27  
    28  	testDir, e := ioutil.TempDir("/tmp/", "test-")
    29  	if e != nil {
    30  		panic(e)
    31  	}
    32  	defer os.RemoveAll(testDir)
    33  
    34  	notifySocket := testDir + "/notify-socket.sock"
    35  	laddr := net.UnixAddr{
    36  		Name: notifySocket,
    37  		Net:  "unixgram",
    38  	}
    39  	_, e = net.ListenUnixgram("unixgram", &laddr)
    40  	if e != nil {
    41  		panic(e)
    42  	}
    43  
    44  	tests := []struct {
    45  		unsetEnv  bool
    46  		envSocket string
    47  
    48  		wsent bool
    49  		werr  bool
    50  	}{
    51  		// (true, nil) - notification supported, data has been sent
    52  		{false, notifySocket, true, false},
    53  		// (false, err) - notification supported, but failure happened
    54  		{true, testDir + "/missing.sock", false, true},
    55  		// (false, nil) - notification not supported
    56  		{true, "", false, false},
    57  	}
    58  
    59  	for i, tt := range tests {
    60  		must(os.Unsetenv("NOTIFY_SOCKET"))
    61  		if tt.envSocket != "" {
    62  			must(os.Setenv("NOTIFY_SOCKET", tt.envSocket))
    63  		}
    64  		sent, err := SdNotify(tt.unsetEnv, fmt.Sprintf("TestSdNotify test message #%d", i))
    65  
    66  		if sent != tt.wsent {
    67  			t.Errorf("#%d: expected send result %t, got %t", i, tt.wsent, sent)
    68  		}
    69  		if tt.werr && err == nil {
    70  			t.Errorf("#%d: want non-nil err, got nil", i)
    71  		} else if !tt.werr && err != nil {
    72  			t.Errorf("#%d: want nil err, got %v", i, err)
    73  		}
    74  		if tt.unsetEnv && tt.envSocket != "" && os.Getenv("NOTIFY_SOCKET") != "" {
    75  			t.Errorf("#%d: environment variable not cleaned up", i)
    76  		}
    77  
    78  	}
    79  }
    80  

View as plain text