blob: f25e50a77c53ab5a9e501dafc7903f85897a2c32 [file]
// Copyright 2026 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.shell;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.shell.Consumers.OutErrConsumers;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.CountDownLatch;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Unit tests for {@link FutureCommandResult}. */
@RunWith(JUnit4.class)
public final class FutureCommandResultTest {
@After
public void clearInterruptStatus() {
Thread.interrupted();
}
@Test
public void get_killOnInterrupt_interruptedAfterProcessExit_throwsInterruptedException() {
FakeSubprocess subprocess =
new FakeSubprocess(
InputStream.nullInputStream(),
InputStream.nullInputStream(),
/* waitAction= */ () -> Thread.currentThread().interrupt());
FutureCommandResult future = createFuture(subprocess, Command.KILL_SUBPROCESS_ON_INTERRUPT);
assertThrows(InterruptedException.class, future::get);
assertThat(subprocess.destroyed).isFalse();
assertThat(Thread.interrupted()).isFalse();
assertThat(subprocess.closed).isTrue();
}
@Test
public void get_killOnInterrupt_secondInterruptAfterDestroy_throwsAndClearsInterrupt() {
// Simulate a second interrupt arriving as the destroyed subprocess exits.
FakeSubprocess subprocess =
new FakeSubprocess(
InputStream.nullInputStream(),
InputStream.nullInputStream(),
new InterruptOnceWaitAction(Thread.currentThread()::interrupt));
FutureCommandResult future = createFuture(subprocess, Command.KILL_SUBPROCESS_ON_INTERRUPT);
assertThrows(InterruptedException.class, future::get);
assertThat(subprocess.destroyed).isTrue();
assertThat(Thread.interrupted()).isFalse();
assertThat(subprocess.closed).isTrue();
}
@Test
public void get_continueOnInterrupt_interruptedAfterProcessExit_preservesInterruptAndOutput()
throws Exception {
FakeSubprocess subprocess =
new FakeSubprocess(
new ByteArrayInputStream("expected-stdout".getBytes(UTF_8)),
new ByteArrayInputStream("expected-stderr".getBytes(UTF_8)),
/* waitAction= */ () -> Thread.currentThread().interrupt());
FutureCommandResult future = createFuture(subprocess, Command.CONTINUE_SUBPROCESS_ON_INTERRUPT);
CommandResult result = future.get();
assertThat(result.terminationStatus().success()).isTrue();
assertThat(new String(result.getStdout(), UTF_8)).isEqualTo("expected-stdout");
assertThat(new String(result.getStderr(), UTF_8)).isEqualTo("expected-stderr");
assertThat(subprocess.destroyed).isFalse();
assertThat(Thread.interrupted()).isTrue();
assertThat(subprocess.closed).isTrue();
}
@Test
public void get_continueOnInterrupt_interruptedDuringWait_waitsForFullOutput() throws Exception {
CountDownLatch stdoutReadStarted = new CountDownLatch(1);
CountDownLatch stderrReadStarted = new CountDownLatch(1);
CountDownLatch releaseOutput = new CountDownLatch(1);
// Release output after the interrupt has been swallowed so consumers drain before completion.
FakeSubprocess subprocess =
new FakeSubprocess(
new GatedInputStream("expected-stdout", stdoutReadStarted, releaseOutput),
new GatedInputStream("expected-stderr", stderrReadStarted, releaseOutput),
new InterruptOnceWaitAction(releaseOutput::countDown));
FutureCommandResult future = createFuture(subprocess, Command.CONTINUE_SUBPROCESS_ON_INTERRUPT);
assertThat(stdoutReadStarted.await(5, SECONDS)).isTrue();
assertThat(stderrReadStarted.await(5, SECONDS)).isTrue();
CommandResult result = future.get();
assertThat(result.terminationStatus().success()).isTrue();
assertThat(new String(result.getStdout(), UTF_8)).isEqualTo("expected-stdout");
assertThat(new String(result.getStderr(), UTF_8)).isEqualTo("expected-stderr");
assertThat(subprocess.destroyed).isFalse();
assertThat(Thread.interrupted()).isTrue();
assertThat(subprocess.closed).isTrue();
}
private static FutureCommandResult createFuture(
FakeSubprocess subprocess, boolean killSubprocessOnInterrupt) {
OutErrConsumers consumers = Consumers.createAccumulatingConsumers();
consumers.registerInputs(
subprocess.getInputStream(), subprocess.getErrorStream(), /* closeStreams= */ false);
return new FutureCommandResult(
new Command(ImmutableList.of("fake-cmd"), ImmutableMap.of()),
subprocess,
consumers,
killSubprocessOnInterrupt);
}
@FunctionalInterface
private interface WaitAction {
void run() throws InterruptedException;
}
private static final class InterruptOnceWaitAction implements WaitAction {
private final Runnable afterInterrupt;
private boolean firstCall = true;
InterruptOnceWaitAction(Runnable afterInterrupt) {
this.afterInterrupt = afterInterrupt;
}
@Override
public void run() throws InterruptedException {
if (firstCall) {
firstCall = false;
throw new InterruptedException();
}
afterInterrupt.run();
}
}
private static final class GatedInputStream extends FilterInputStream {
private final CountDownLatch readStarted;
private final CountDownLatch releaseOutput;
GatedInputStream(String content, CountDownLatch readStarted, CountDownLatch releaseOutput) {
super(new ByteArrayInputStream(content.getBytes(UTF_8)));
this.readStarted = readStarted;
this.releaseOutput = releaseOutput;
}
private boolean awaitRelease() throws IOException {
readStarted.countDown();
try {
if (!releaseOutput.await(5, SECONDS)) {
throw new IOException("Timed out waiting to release test output");
}
return true;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
}
}
@Override
public int read() throws IOException {
return awaitRelease() ? super.read() : -1;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return awaitRelease() ? super.read(b, off, len) : -1;
}
}
private static final class FakeSubprocess implements Subprocess {
private final InputStream stdout;
private final InputStream stderr;
private final WaitAction waitAction;
boolean destroyed;
boolean closed;
FakeSubprocess(InputStream stdout, InputStream stderr, WaitAction waitAction) {
this.stdout = stdout;
this.stderr = stderr;
this.waitAction = waitAction;
}
@Override
public boolean destroy() {
destroyed = true;
return true;
}
@Override
public int exitValue() {
return 0;
}
@Override
public boolean finished() {
return true;
}
@Override
public boolean isAlive() {
return false;
}
@Override
public boolean timedout() {
return false;
}
@Override
public void waitFor() throws InterruptedException {
waitAction.run();
}
@Override
public OutputStream getOutputStream() {
return OutputStream.nullOutputStream();
}
@Override
public InputStream getInputStream() {
return stdout;
}
@Override
public InputStream getErrorStream() {
return stderr;
}
@Override
public long getProcessId() {
return 1;
}
@Override
public void close() {
closed = true;
}
}
}