github.com/coreos/mantle@v0.13.0/system/exec/exec_test.go (about)

     1  // Copyright 2015 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 exec
    16  
    17  import (
    18  	"context"
    19  	"os/exec"
    20  	"syscall"
    21  	"testing"
    22  )
    23  
    24  func TestExecCmdKill(t *testing.T) {
    25  	cmd := Command("sleep", "3600")
    26  	if err := cmd.Start(); err != nil {
    27  		t.Fatalf("Start failed: %v", err)
    28  	}
    29  
    30  	if err := cmd.Kill(); err != nil {
    31  		t.Errorf("Kill failed: %v", err)
    32  	}
    33  
    34  	if cmd.ProcessState == nil {
    35  		t.Fatalf("ProcessState is nil")
    36  	}
    37  
    38  	status := cmd.ProcessState.Sys().(syscall.WaitStatus)
    39  	if status.Signal() != syscall.SIGKILL {
    40  		t.Errorf("Unexpected state: %s", cmd.ProcessState)
    41  	}
    42  }
    43  
    44  func TestExecCmdCancel(t *testing.T) {
    45  	ctx, cancel := context.WithCancel(context.Background())
    46  	cmd := CommandContext(ctx, "sleep", "3600")
    47  	if err := cmd.Start(); err != nil {
    48  		t.Fatalf("Start failed: %v", err)
    49  	}
    50  
    51  	cancel()
    52  	if err := cmd.Wait(); err == nil {
    53  		t.Errorf("Killed without an error")
    54  	} else if state, ok := err.(*exec.ExitError); ok {
    55  		status := state.Sys().(syscall.WaitStatus)
    56  		if status.Signal() != syscall.SIGKILL {
    57  			t.Errorf("Unexpected state: %s", state)
    58  		}
    59  	} else {
    60  		t.Errorf("Unexpected error: %v", err)
    61  	}
    62  }