github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/utils/testing/runprocess.go (about)

     1  /*
     2  Copyright 2018 Mirantis
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package testing
    18  
    19  import (
    20  	"os/exec"
    21  	"testing"
    22  )
    23  
    24  type TestCommand struct {
    25  	t       *testing.T
    26  	Command *exec.Cmd
    27  }
    28  
    29  // RunProcess runs a background process with specified args and
    30  // appending env to the current environment.
    31  func RunProcess(t *testing.T, command string, args []string, env []string) *TestCommand {
    32  	cmd := exec.Command(command, args...)
    33  	if env != nil {
    34  		cmd.Env = env
    35  	}
    36  	if err := cmd.Start(); err != nil {
    37  		t.Fatalf("Error when starting the command %q: %v", command, err)
    38  	}
    39  	return &TestCommand{t, cmd}
    40  }
    41  
    42  func (tc *TestCommand) Stop() {
    43  	if err := tc.Command.Process.Kill(); err != nil {
    44  		tc.t.Errorf("failed to kill the child process: %v", err)
    45  	}
    46  
    47  	err := tc.Command.Wait()
    48  	if err == nil {
    49  		return
    50  	}
    51  	if _, ok := err.(*exec.ExitError); ok {
    52  		return
    53  	}
    54  	tc.t.Errorf("Wait() failed: %v", err)
    55  }
    56  
    57  func (tc *TestCommand) Pid() int {
    58  	return tc.Command.Process.Pid
    59  }