blob: 9c1f7cdf6f206f0381293fa756542a3f27e150aa [file] [log] [blame]
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// found in the LICENSE file.
package main
import (
"context"
"math/rand"
"strconv"
"testing"
"time"
)
const (
successExitCode = 0
)
var (
sigTermExitCode = rand.Int()%50 + 1
failCode = rand.Int()%50 + 51
)
func constructMockCmd(fail bool) []string {
failureExitCode := -1
if fail {
failureExitCode = failCode
}
return []string{
"./mock.sh",
strconv.Itoa(failureExitCode),
strconv.Itoa(sigTermExitCode),
}
}
func checkExitCode(t *testing.T, actual int, expected int) {
if actual != expected {
t.Errorf("Expected exit code: %d Actual %d", expected, actual)
}
}
// Test that runSubprocess propagates success code.
func TestSuccessfulSubprocess(t *testing.T) {
cmd := constructMockCmd(false)
exitCode := runSubprocess(context.Background(), cmd)
checkExitCode(t, exitCode, successExitCode)
}
// Test that runSubprocess propagates failure code.
func TestFailingSubprocess(t *testing.T) {
cmd := constructMockCmd(true)
exitCode := runSubprocess(context.Background(), cmd)
checkExitCode(t, exitCode, failCode)
}
// Test that sigterms are propagated to running subprocesses on context cancel.
func TestSigtermRunningSubprocess(t *testing.T) {
cmd := constructMockCmd(false)
subprocessCtx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(2 * time.Second)
cancel()
}()
exitCode := runSubprocess(subprocessCtx, cmd)
checkExitCode(t, exitCode, sigTermExitCode)
}
// Test that sigterms sent after the subprocess is done running do not get propagated.
func TestSigtermDoneSubprocess(t *testing.T) {
cmd := constructMockCmd(false)
subprocessCtx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(7 * time.Second)
cancel()
}()
exitCode := runSubprocess(subprocessCtx, cmd)
checkExitCode(t, exitCode, successExitCode)
}