gopkg.in/hugelgupf/u-root.v2@v2.0.0-20180831055005-3f8fdb0ce09d/cmds/shutdown/shutdown_test.go (about)

     1  // Copyright 2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"os"
     9  	"os/exec"
    10  	"syscall"
    11  	"testing"
    12  
    13  	"golang.org/x/sys/unix"
    14  )
    15  
    16  var tests = []struct {
    17  	args    []string
    18  	retCode int
    19  }{
    20  	// Too many args is an error.
    21  	{[]string{"halt", "police"}, 1},
    22  	{[]string{"halt"}, 2},
    23  	{[]string{"-h"}, 2},
    24  	// No args means halt.
    25  	{[]string{}, 2},
    26  	{[]string{"reboot"}, 3},
    27  	{[]string{"-r"}, 3},
    28  	{[]string{"suspend"}, 4},
    29  	{[]string{"-s"}, 4},
    30  }
    31  
    32  func TestShutdown(t *testing.T) {
    33  	for i, tt := range tests {
    34  		var retCode int
    35  		c := exec.Command(os.Args[0], append([]string{"-test.run=TestHelperProcess", "--"}, tt.args...)...)
    36  		c.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
    37  		t.Logf("Run %v", c)
    38  		_, err := c.Output()
    39  		t.Logf("err %v", err)
    40  		if err != nil {
    41  			exitErr, ok := err.(*exec.ExitError)
    42  			if !ok {
    43  				t.Errorf("%d. Error running shutdown: %v", i, err)
    44  				continue
    45  			}
    46  			retCode = exitErr.Sys().(syscall.WaitStatus).ExitStatus()
    47  		}
    48  		if retCode != tt.retCode {
    49  			t.Errorf("%d. Want: %d; Got: %d", i, tt.retCode, retCode)
    50  		}
    51  	}
    52  }
    53  
    54  func TestHelperProcess(t *testing.T) {
    55  	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
    56  		t.Logf("just a helper")
    57  		return
    58  	}
    59  
    60  	reboot = func(i int) error {
    61  		xval := 1
    62  		switch uint32(i) {
    63  		case unix.LINUX_REBOOT_CMD_POWER_OFF:
    64  			xval = 2
    65  		case unix.LINUX_REBOOT_CMD_RESTART:
    66  			xval = 3
    67  		case unix.LINUX_REBOOT_CMD_SW_SUSPEND:
    68  			xval = 4
    69  		}
    70  
    71  		t.Logf("Exit with %#x", i)
    72  		os.Exit(xval)
    73  		return nil
    74  	}
    75  
    76  	os.Args = append([]string{"shutdown"}, os.Args[3:]...)
    77  	main()
    78  }