...

Source file src/github.com/godbus/dbus/v5/exec_command_test.go

Documentation: github.com/godbus/dbus/v5

     1  package dbus
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"strconv"
     8  	"testing"
     9  )
    10  
    11  // How to mock exec.Command for unit tests
    12  // https://stackoverflow.com/q/45789101/10513533
    13  
    14  var mockedExitStatus = 0
    15  var mockedStdout string
    16  
    17  func fakeExecCommand(command string, args ...string) *exec.Cmd {
    18  	cs := []string{"-test.run=TestExecCommandHelper", "--", command}
    19  	cs = append(cs, args...)
    20  	cmd := exec.Command(os.Args[0], cs...)
    21  	es := strconv.Itoa(mockedExitStatus)
    22  	cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1",
    23  		"STDOUT=" + mockedStdout,
    24  		"EXIT_STATUS=" + es}
    25  	return cmd
    26  }
    27  
    28  func TestExecCommandHelper(t *testing.T) {
    29  	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
    30  		return
    31  	}
    32  
    33  	fmt.Fprintf(os.Stdout, os.Getenv("STDOUT"))
    34  	i, _ := strconv.Atoi(os.Getenv("EXIT_STATUS"))
    35  	os.Exit(i)
    36  }
    37  
    38  func TestDbusLaunchMultilineResponse(t *testing.T) {
    39  	mockedExitStatus = 0
    40  	mockedStdout = `process 7616: D-Bus library appears to be incorrectly set up; failed to read machine uuid: UUID file '/etc/machine-id' should contain a hex string of length 32, not length 0, with no other text
    41  See the manual page for dbus-uuidgen to correct this issue.
    42  DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-0SO9YZUBGA,guid=ac22f2f3b9d228496b4d4b935cae3417
    43  DBUS_SESSION_BUS_PID=7620
    44  DBUS_SESSION_BUS_WINDOWID=16777217`
    45  	execCommand = fakeExecCommand
    46  	defer func() { execCommand = exec.Command }()
    47  	expOut := ""
    48  	expErr := "dbus: couldn't determine address of session bus"
    49  
    50  	out, err := getSessionBusPlatformAddress()
    51  	if out != expOut {
    52  		t.Errorf("Expected %q, got %q", expOut, out)
    53  	}
    54  	if err == nil {
    55  		t.Error("Excepted error, got none")
    56  	} else {
    57  		if err.Error() != expErr {
    58  			t.Errorf("Expected error to be %q, got %q", expErr, err.Error())
    59  		}
    60  	}
    61  }
    62  

View as plain text