github.com/bazelbuild/bazel-watcher@v0.25.2/internal/ibazel/command/command_test.go (about)

     1  // Copyright 2017 The Bazel Authors. All rights reserved.
     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 command
    16  
    17  import (
    18  	"os/exec"
    19  	"testing"
    20  
    21  	"github.com/bazelbuild/bazel-watcher/internal/bazel"
    22  	"github.com/bazelbuild/bazel-watcher/internal/ibazel/log"
    23  	"github.com/bazelbuild/bazel-watcher/internal/ibazel/process_group"
    24  )
    25  
    26  var oldExecCommand = execCommand
    27  var oldBazelNew = bazel.New
    28  
    29  func assertKilled(t *testing.T, cmd *exec.Cmd) {
    30  	t.Helper()
    31  	if err := cmd.Wait(); err != nil {
    32  		if cmd.ProcessState.Success() {
    33  			t.Errorf("Subprocess terminated from \"natural\" causes, which means the job ran till its timeout then existed. The Run method should have killed it before then.")
    34  		}
    35  		if cmd.ProcessState == nil {
    36  			t.Errorf("Killable subprocess was never started. State: %v, Err: %v", cmd.ProcessState, err)
    37  		}
    38  	}
    39  }
    40  
    41  func TestSubprocessRunning(t *testing.T) {
    42  	log.SetLogger(t)
    43  
    44  	execCommand = func(name string, args ...string) process_group.ProcessGroup {
    45  		return oldExecCommand("ls") // Every system has ls.
    46  	}
    47  	defer func() { execCommand = oldExecCommand }()
    48  
    49  	if subprocessRunning(nil) {
    50  		t.Errorf("Nil subprocesses don't run")
    51  	}
    52  
    53  	cmd := exec.Command("sleep", ".1")
    54  
    55  	if subprocessRunning(cmd) {
    56  		t.Errorf("New subprocess shouldn't have been started yet. State: %v", cmd.ProcessState)
    57  	}
    58  
    59  	if err := cmd.Start(); err != nil {
    60  		t.Errorf("cmd.Start(): %v", err)
    61  	}
    62  
    63  	if !subprocessRunning(cmd) {
    64  		t.Errorf("New subprocess was never started. State: %v", cmd.ProcessState)
    65  	}
    66  
    67  	err := cmd.Wait()
    68  	if err != nil {
    69  		t.Errorf("Subprocess finished with error: %v State: %v", err, cmd.ProcessState)
    70  	} else if subprocessRunning(cmd) {
    71  		t.Errorf("Subprocess still running State: %v", cmd.ProcessState)
    72  	}
    73  }