Automatic cleanup change.
PiperOrigin-RevId: 245944657
diff --git a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD
index 21ba2c0..4a17308 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD
+++ b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/BUILD
@@ -9,6 +9,7 @@
deps = [
"//src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding",
"//src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/api",
+ "//src/test/java/com/google/devtools/build/lib:testutil",
"//third_party:guava",
"//third_party:junit4",
"//third_party:truth",
diff --git a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java
index cd17c5d..e55555e 100644
--- a/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java
+++ b/src/java_tools/junitrunner/java/com/google/testing/junit/runner/sharding/testing/ShardingFilterTestCase.java
@@ -15,6 +15,7 @@
package com.google.testing.junit.runner.sharding.testing;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.testing.junit.runner.sharding.api.ShardingFilterFactory;
import java.util.ArrayList;
@@ -122,10 +123,9 @@
}
protected static void assertThrowsExceptionForUnknownDescription(Filter filter) {
- try {
- filter.shouldRun(Description.createTestDescription(Object.class, "unknown"));
- fail("expected thrown exception");
- } catch (IllegalArgumentException expected) { }
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> filter.shouldRun(Description.createTestDescription(Object.class, "unknown")));
}
/**
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java
index 7bd9a10..315ab27 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/internal/junit4/CancellableRequestFactoryTest.java
@@ -15,7 +15,7 @@
package com.google.testing.junit.runner.internal.junit4;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import java.util.Arrays;
import java.util.concurrent.Callable;
@@ -95,15 +95,12 @@
cancellableRequestFactory.cancelRun();
testContinueLatch.countDown();
- try {
- future.get(10, TimeUnit.SECONDS);
- fail("exception expected");
- } catch (ExecutionException e) {
- Throwable runnerException = e.getCause();
+ ExecutionException e =
+ assertThrows(ExecutionException.class, () -> future.get(10, TimeUnit.SECONDS));
+ Throwable runnerException = e.getCause();
assertThat(runnerException).isInstanceOf(RuntimeException.class);
assertThat(runnerException).hasMessageThat().isEqualTo("Test run interrupted");
- assertThat(runnerException).hasCauseThat().isInstanceOf(StoppedByUserException.class);
- }
+ assertThat(runnerException).hasCauseThat().isInstanceOf(StoppedByUserException.class);
executor.shutdownNow();
}
@@ -124,13 +121,9 @@
cancellableRequestFactory.cancelRun();
JUnitCore core = new JUnitCore();
- try {
- core.run(request);
- fail("exception expected");
- } catch (RuntimeException e) {
- assertThat(e).hasMessageThat().isEqualTo("Test run interrupted");
- assertThat(e).hasCauseThat().isInstanceOf(StoppedByUserException.class);
- }
+ RuntimeException e = assertThrows(RuntimeException.class, () -> core.run(request));
+ assertThat(e).hasMessageThat().isEqualTo("Test run interrupted");
+ assertThat(e).hasCauseThat().isInstanceOf(StoppedByUserException.class);
assertThat(testRan.get()).isFalse();
}
diff --git a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java
index 0773428..18ac72a 100644
--- a/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java
+++ b/src/java_tools/junitrunner/javatests/com/google/testing/junit/runner/util/GoogleTestSecurityManagerTest.java
@@ -16,7 +16,7 @@
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import java.security.Permission;
import org.junit.After;
@@ -66,24 +66,14 @@
public void testExit() {
installTestSecurityManager();
- try {
- System.exit(1);
- fail("exit() have thrown exception; how come it didn't exit?!");
- } catch (SecurityException se) {
- // passed
- }
+ assertThrows(SecurityException.class, () -> System.exit(1));
}
@Test
public void testSetSecurityManager() {
installTestSecurityManager();
- try {
- System.setSecurityManager(new SecurityManager());
- fail("setSecurityManager() should have thrown exception.");
- } catch (SecurityException se) {
- // passed
- }
+ assertThrows(SecurityException.class, () -> System.setSecurityManager(new SecurityManager()));
}
/**
@@ -96,12 +86,7 @@
GoogleTestSecurityManager sm = new GoogleTestSecurityManager();
assertThat(sm.isEnabled()).isTrue();
- try {
- sm.checkExit(0);
- fail("GoogleTestSecurityManager allowed exit while enabled.");
- } catch (SecurityException ex) {
- // passed
- }
+ assertThrows(SecurityException.class, () -> sm.checkExit(0));
sm.setEnabled(false);
assertThat(!sm.isEnabled()).isTrue();
@@ -110,12 +95,7 @@
sm.setEnabled(true);
assertThat(sm.isEnabled()).isTrue();
- try {
- sm.checkExit(0);
- fail("GoogleTestSecurityManager allowed exit while enabled.");
- } catch (SecurityException ex) {
- // passed
- }
+ assertThrows(SecurityException.class, () -> sm.checkExit(0));
}
@Test
diff --git a/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java b/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java
index 511b99a..beab174 100644
--- a/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java
+++ b/src/java_tools/singlejar/javatests/com/google/devtools/build/zip/ZipWriterTest.java
@@ -15,8 +15,8 @@
package com.google.devtools.build.zip;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.fail;
import com.google.common.primitives.Bytes;
import com.google.devtools.build.zip.ZipFileEntry.Compression;
@@ -87,9 +87,8 @@
@Test public void testFileDataBeforeEntry() throws IOException {
try (ZipWriter writer = new ZipWriter(new FileOutputStream(test), UTF_8)) {
- writer.write(new byte[] { 0xf, 0xa, 0xb });
- fail("Expected ZipException");
- } catch (ZipException e) {
+ ZipException e =
+ assertThrows(ZipException.class, () -> writer.write(new byte[] {0xf, 0xa, 0xb}));
assertThat(e)
.hasMessageThat()
.contains(
@@ -312,8 +311,6 @@
thrown.expect(ZipException.class);
thrown.expectMessage("Cannot add a prefix file after the zip contents have been started.");
writer.startPrefixFile();
- writer.write("#!/bin/bash\necho 'hello world'\n".getBytes(UTF_8));
- writer.endPrefixFile();
}
}
@@ -322,8 +319,6 @@
writer.finish();
thrown.expect(IllegalStateException.class);
writer.startPrefixFile();
- writer.write("#!/bin/bash\necho 'hello world'\n".getBytes(UTF_8));
- writer.endPrefixFile();
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/BUILD b/src/test/java/com/google/devtools/build/lib/BUILD
index dee8b7c..27a3ab3 100644
--- a/src/test/java/com/google/devtools/build/lib/BUILD
+++ b/src/test/java/com/google/devtools/build/lib/BUILD
@@ -1452,6 +1452,7 @@
deps = [
":actions_testutil",
":guava_junit_truth",
+ ":testutil",
"//src/main/java/com/google/devtools/build/lib:build-base",
"//src/main/java/com/google/devtools/build/lib:events",
"//src/main/java/com/google/devtools/build/lib:proto-rules",
diff --git a/src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java b/src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java
index 87131c2..5be1d19 100644
--- a/src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/actions/cache/PersistentStringIndexerTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.actions.cache;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.devtools.build.lib.clock.Clock;
import com.google.devtools.build.lib.testutil.Scratch;
@@ -256,12 +256,11 @@
public void testCorruptedJournal() throws Exception {
FileSystemUtils.createDirectoryAndParents(journalPath.getParentDirectory());
FileSystemUtils.writeContentAsLatin1(journalPath, "bogus content");
- try {
- psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- fail();
- } catch (IOException e) {
- assertThat(e).hasMessageThat().contains("too short: Only 13 bytes");
- }
+ IOException e =
+ assertThrows(
+ IOException.class,
+ () -> psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock));
+ assertThat(e).hasMessageThat().contains("too short: Only 13 bytes");
journalPath.delete();
setupTestContent();
@@ -284,35 +283,27 @@
assertThat(dataPath.delete()).isTrue();
FileSystemUtils.writeContent(journalPath,
Arrays.copyOf(journalContent, journalContent.length - 1));
- try {
- psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- fail();
- } catch (EOFException e) {
- // Expected.
- }
+ assertThrows(
+ EOFException.class,
+ () -> psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock));
// Corrupt the journal with a negative size value.
byte[] journalCopy = journalContent.clone();
// Flip this bit to make the key size negative.
journalCopy[95] = -2;
FileSystemUtils.writeContent(journalPath, journalCopy);
- try {
- psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- fail();
- } catch (IOException e) {
- // Expected.
- assertThat(e).hasMessageThat().contains("corrupt key length");
- }
+ e =
+ assertThrows(
+ IOException.class,
+ () -> psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock));
+ assertThat(e).hasMessageThat().contains("corrupt key length");
// Now put back corrupted journal. We should get an error.
journalContent[journalContent.length - 13] = 100;
FileSystemUtils.writeContent(journalPath, journalContent);
- try {
- psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- fail();
- } catch (IOException e) {
- // Expected.
- }
+ assertThrows(
+ IOException.class,
+ () -> psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock));
}
@Test
@@ -345,13 +336,11 @@
content[content.length - 1] = content[content.length - 1] == 1 ? (byte) 2 : (byte) 1;
FileSystemUtils.writeContent(journalPath, content);
- try {
- psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock);
- fail();
- } catch (IOException e) {
- // Expected.
- assertThat(e).hasMessageThat().contains("Corrupted filename index has duplicate entry");
- }
+ IOException e =
+ assertThrows(
+ IOException.class,
+ () -> psi = PersistentStringIndexer.newPersistentStringIndexer(dataPath, clock));
+ assertThat(e).hasMessageThat().contains("Corrupted filename index has duplicate entry");
}
@Test
@@ -372,13 +361,7 @@
// Subsequent updates should succeed even though journaling is disabled at this point.
clock.advance(4);
assertIndex(10, "another record");
- try {
- // Save should actually save main data file but then return us deferred IO failure
- // from failed journal write.
- psi.save();
- fail();
- } catch(IOException e) {
- assertThat(e).hasMessageThat().contains(journalPath.getPathString() + " (Is a directory)");
- }
+ IOException e = assertThrows(IOException.class, () -> psi.save());
+ assertThat(e).hasMessageThat().contains(journalPath.getPathString() + " (Is a directory)");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/stringtemplate/TemplateExpanderTest.java b/src/test/java/com/google/devtools/build/lib/analysis/stringtemplate/TemplateExpanderTest.java
index d2740b6..74f0cea 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/stringtemplate/TemplateExpanderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/stringtemplate/TemplateExpanderTest.java
@@ -14,6 +14,7 @@
package com.google.devtools.build.lib.analysis.stringtemplate;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import static org.junit.Assert.fail;
import java.util.HashMap;
@@ -119,22 +120,25 @@
@Test
public void testFunctionExpansionThrows() throws Exception {
- try {
- TemplateExpander.expand("$(foo baz)", new TemplateContext() {
- @Override
- public String lookupVariable(String name) throws ExpansionException {
- throw new ExpansionException(name);
- }
+ ExpansionException e =
+ assertThrows(
+ ExpansionException.class,
+ () ->
+ TemplateExpander.expand(
+ "$(foo baz)",
+ new TemplateContext() {
+ @Override
+ public String lookupVariable(String name) throws ExpansionException {
+ throw new ExpansionException(name);
+ }
- @Override
- public String lookupFunction(String name, String param) throws ExpansionException {
- throw new ExpansionException(name + "(" + param + ")");
- }
- });
- fail();
- } catch (ExpansionException e) {
- assertThat(e).hasMessageThat().isEqualTo("foo(baz)");
- }
+ @Override
+ public String lookupFunction(String name, String param)
+ throws ExpansionException {
+ throw new ExpansionException(name + "(" + param + ")");
+ }
+ }));
+ assertThat(e).hasMessageThat().isEqualTo("foo(baz)");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/analysis/whitelisting/WhitelistCachingTest.java b/src/test/java/com/google/devtools/build/lib/analysis/whitelisting/WhitelistCachingTest.java
index 85b305b..ead3a02 100644
--- a/src/test/java/com/google/devtools/build/lib/analysis/whitelisting/WhitelistCachingTest.java
+++ b/src/test/java/com/google/devtools/build/lib/analysis/whitelisting/WhitelistCachingTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.analysis.whitelisting;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
import com.google.devtools.build.lib.analysis.ViewCreationFailedException;
@@ -43,12 +43,7 @@
scratch.file("x/BUILD", "rule_with_whitelist(name='x')");
reporter.removeHandler(failFastHandler);
- try {
- update("//x:x");
- fail();
- } catch (ViewCreationFailedException e) {
- // expected
- }
+ assertThrows(ViewCreationFailedException.class, () -> update("//x:x"));
assertContainsEvent("Dummy is not available.");
eventCollector.clear();
reporter.addHandler(failFastHandler);
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java
index 0e94452..60f1005 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/DecompressorValueTest.java
@@ -15,7 +15,7 @@
package com.google.devtools.build.lib.bazel.repository;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.devtools.build.lib.rules.repository.RepositoryFunction.RepositoryFunctionException;
import com.google.devtools.build.lib.vfs.FileSystem;
@@ -56,12 +56,11 @@
@Test
public void testUnknownFileExtensionsThrow() throws Exception {
Path zipPath = fs.getPath("/foo/.external-repositories/some-repo/bar.baz");
- try {
- DecompressorDescriptor.builder().setArchivePath(zipPath).build();
- fail(".baz isn't a valid suffix");
- } catch (RepositoryFunctionException expected) {
- assertThat(expected).hasMessageThat().contains("Expected a file with a .zip, .jar,");
- }
+ RepositoryFunctionException expected =
+ assertThrows(
+ RepositoryFunctionException.class,
+ () -> DecompressorDescriptor.builder().setArchivePath(zipPath).build());
+ assertThat(expected).hasMessageThat().contains("Expected a file with a .zip, .jar,");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
index c75bad7..0302311 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.bazel.rules.android;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider;
@@ -205,18 +205,17 @@
" name = 'androidndk',",
" path = '/ndk',",
")");
- try {
- // Invalidating configs re-runs AndroidNdkRepositoryFunction which results in a
- // RuntimeException. This way we can catch a checked exception instead.
- invalidatePackages(false);
- getTarget("@androidndk//:files");
- fail("android_ndk_repository should have failed due to missing NDK platforms dir.");
- } catch (BuildFileNotFoundException e) {
- assertThat(e)
- .hasMessageThat()
- .contains(
- "Expected directory at /ndk/platforms but it is not a directory or it does not "
- + "exist.");
- }
+ BuildFileNotFoundException e =
+ assertThrows(
+ BuildFileNotFoundException.class,
+ () -> {
+ invalidatePackages(false);
+ getTarget("@androidndk//:files");
+ });
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ "Expected directory at /ndk/platforms but it is not a directory or it does not "
+ + "exist.");
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/dynamic/DynamicSpawnStrategyTest.java b/src/test/java/com/google/devtools/build/lib/dynamic/DynamicSpawnStrategyTest.java
index 05c42df..0cc5116 100644
--- a/src/test/java/com/google/devtools/build/lib/dynamic/DynamicSpawnStrategyTest.java
+++ b/src/test/java/com/google/devtools/build/lib/dynamic/DynamicSpawnStrategyTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.dynamic;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
@@ -379,12 +379,10 @@
localStrategy.failsDuringExecution();
remoteStrategy.beforeExecutionWaitFor(countDownLatch);
- try {
- dynamicSpawnStrategy.exec(spawn, actionExecutionContext);
- fail("Expected dynamicSpawnStrategy to throw an ExecException");
- } catch (ExecException e) {
- assertThat(e).hasMessageThat().matches("MockLocalSpawnStrategy failed to execute the Spawn");
- }
+ ExecException e =
+ assertThrows(
+ ExecException.class, () -> dynamicSpawnStrategy.exec(spawn, actionExecutionContext));
+ assertThat(e).hasMessageThat().matches("MockLocalSpawnStrategy failed to execute the Spawn");
assertThat(localStrategy.getExecutedSpawn()).isEqualTo(spawn);
assertThat(localStrategy.succeeded()).isFalse();
@@ -404,12 +402,10 @@
remoteStrategy.beforeExecutionWaitFor(countDownLatch);
remoteStrategy.failsDuringExecution();
- try {
- dynamicSpawnStrategy.exec(spawn, actionExecutionContext);
- fail("Expected dynamicSpawnStrategy to throw an ExecException");
- } catch (ExecException e) {
- assertThat(e).hasMessageThat().matches("MockRemoteSpawnStrategy failed to execute the Spawn");
- }
+ ExecException e =
+ assertThrows(
+ ExecException.class, () -> dynamicSpawnStrategy.exec(spawn, actionExecutionContext));
+ assertThat(e).hasMessageThat().matches("MockRemoteSpawnStrategy failed to execute the Spawn");
assertThat(localStrategy.getExecutedSpawn()).isEqualTo(spawn);
assertThat(localStrategy.succeeded()).isFalse();
@@ -430,14 +426,12 @@
localStrategy.failsDuringExecution();
remoteStrategy.failsDuringExecution();
- try {
- dynamicSpawnStrategy.exec(spawn, actionExecutionContext);
- fail("Expected dynamicSpawnStrategy to throw an ExecException");
- } catch (ExecException e) {
- assertThat(e)
- .hasMessageThat()
- .matches("Mock(Local|Remote)SpawnStrategy failed to execute the Spawn");
- }
+ ExecException e =
+ assertThrows(
+ ExecException.class, () -> dynamicSpawnStrategy.exec(spawn, actionExecutionContext));
+ assertThat(e)
+ .hasMessageThat()
+ .matches("Mock(Local|Remote)SpawnStrategy failed to execute the Spawn");
assertThat(localStrategy.getExecutedSpawn()).isEqualTo(spawn);
assertThat(localStrategy.succeeded()).isFalse();
@@ -608,12 +602,10 @@
localStrategy.setExecute(execute);
remoteStrategy.setExecute(execute);
- try {
- dynamicSpawnStrategy.exec(spawn, actionExecutionContext);
- fail("Expected dynamicSpawnStrategy to throw an ExecException");
- } catch (ExecException e) {
- assertThat(e).hasMessageThat().matches("java.lang.IllegalStateException: " + message);
- }
+ ExecException e =
+ assertThrows(
+ ExecException.class, () -> dynamicSpawnStrategy.exec(spawn, actionExecutionContext));
+ assertThat(e).hasMessageThat().matches("java.lang.IllegalStateException: " + message);
Spawn executedSpawn = localStrategy.getExecutedSpawn();
executedSpawn = executedSpawn == null ? remoteStrategy.getExecutedSpawn() : executedSpawn;
diff --git a/src/test/java/com/google/devtools/build/lib/exec/local/LocalSpawnRunnerTest.java b/src/test/java/com/google/devtools/build/lib/exec/local/LocalSpawnRunnerTest.java
index 3a85428..a809f76 100644
--- a/src/test/java/com/google/devtools/build/lib/exec/local/LocalSpawnRunnerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/exec/local/LocalSpawnRunnerTest.java
@@ -16,8 +16,8 @@
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.matches;
@@ -617,13 +617,8 @@
FileOutErr fileOutErr = new FileOutErr(fs.getPath("/out/stdout"), fs.getPath("/out/stderr"));
SpawnExecutionContextForTesting policy = new SpawnExecutionContextForTesting(fileOutErr);
assertThat(fs.getPath("/execroot").createDirectory()).isTrue();
- try {
- runner.execAsync(SIMPLE_SPAWN, policy).get();
- fail();
- } catch (InterruptedException expected) {
- // Clear the interrupted status or subsequent tests in the same process will fail.
- Thread.interrupted();
- }
+ assertThrows(InterruptedException.class, () -> runner.execAsync(SIMPLE_SPAWN, policy).get());
+ Thread.interrupted();
assertThat(policy.lockOutputFilesCalled).isTrue();
}
diff --git a/src/test/java/com/google/devtools/build/lib/rules/filegroup/FilegroupConfiguredTargetTest.java b/src/test/java/com/google/devtools/build/lib/rules/filegroup/FilegroupConfiguredTargetTest.java
index 39e14f8..44626b7 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/filegroup/FilegroupConfiguredTargetTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/filegroup/FilegroupConfiguredTargetTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.rules.filegroup;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.devtools.build.lib.actions.util.ActionsTestUtil;
import com.google.devtools.build.lib.analysis.ConfiguredTarget;
@@ -177,15 +177,10 @@
String.format(
"filegroup(name='group', srcs=[':lib_a'], output_group='%s')",
OutputGroupInfo.HIDDEN_TOP_LEVEL));
- try {
- getConfiguredTarget("//pkg:group");
- fail("Should throw AssertionError");
- } catch (AssertionError e) {
- assertThat(e)
- .hasMessageThat()
- .contains(
- String.format(
- Filegroup.ILLEGAL_OUTPUT_GROUP_ERROR, OutputGroupInfo.HIDDEN_TOP_LEVEL));
- }
+ AssertionError e = assertThrows(AssertionError.class, () -> getConfiguredTarget("//pkg:group"));
+ assertThat(e)
+ .hasMessageThat()
+ .contains(
+ String.format(Filegroup.ILLEGAL_OUTPUT_GROUP_ERROR, OutputGroupInfo.HIDDEN_TOP_LEVEL));
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/rules/proto/ProtoCompileActionBuilderTest.java b/src/test/java/com/google/devtools/build/lib/rules/proto/ProtoCompileActionBuilderTest.java
index cc40ab7..331d969 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/proto/ProtoCompileActionBuilderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/proto/ProtoCompileActionBuilderTest.java
@@ -17,7 +17,7 @@
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.collect.nestedset.Order.STABLE_ORDER;
import static com.google.devtools.build.lib.rules.proto.ProtoCompileActionBuilder.createCommandLineFromToolchains;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import static org.mockito.Mockito.mock;
import com.google.common.collect.ImmutableList;
@@ -333,32 +333,33 @@
/* runtime= */ mock(TransitiveInfoCollection.class),
/* blacklistedProtos= */ NestedSetBuilder.emptySet(STABLE_ORDER));
- try {
- createCommandLineFromToolchains(
- ImmutableList.of(
- new ToolchainInvocation("pluginName", toolchain1, "outReplacement"),
- new ToolchainInvocation("pluginName", toolchain2, "outReplacement")),
- "bazel-out",
- protoInfo(
- /* directProtos */ ImmutableList.of(),
- /* transitiveProtos */ NestedSetBuilder.emptySet(STABLE_ORDER),
- /* transitiveProtoSourceRoots= */ NestedSetBuilder.emptySet(STABLE_ORDER),
- /* strictImportableProtoSourceRoots= */ NestedSetBuilder.emptySet(STABLE_ORDER),
- /* strictImportableProtos= */ NestedSetBuilder.emptySet(STABLE_ORDER),
- /* exportedProtos = */ NestedSetBuilder.emptySet(STABLE_ORDER)),
- Label.parseAbsoluteUnchecked("//foo:bar"),
- Deps.STRICT,
- Exports.DO_NOT_USE,
- Services.ALLOW,
- /* protocOpts= */ ImmutableList.of());
- fail("Expected an exception");
- } catch (IllegalStateException e) {
- assertThat(e)
- .hasMessageThat()
- .isEqualTo(
- "Invocation name pluginName appears more than once. "
- + "This could lead to incorrect proto-compiler behavior");
- }
+ IllegalStateException e =
+ assertThrows(
+ IllegalStateException.class,
+ () ->
+ createCommandLineFromToolchains(
+ ImmutableList.of(
+ new ToolchainInvocation("pluginName", toolchain1, "outReplacement"),
+ new ToolchainInvocation("pluginName", toolchain2, "outReplacement")),
+ "bazel-out",
+ protoInfo(
+ /* directProtos */ ImmutableList.of(),
+ /* transitiveProtos */ NestedSetBuilder.emptySet(STABLE_ORDER),
+ /* transitiveProtoSourceRoots= */ NestedSetBuilder.emptySet(STABLE_ORDER),
+ /* strictImportableProtoSourceRoots= */ NestedSetBuilder.emptySet(
+ STABLE_ORDER),
+ /* strictImportableProtos= */ NestedSetBuilder.emptySet(STABLE_ORDER),
+ /* exportedProtos = */ NestedSetBuilder.emptySet(STABLE_ORDER)),
+ Label.parseAbsoluteUnchecked("//foo:bar"),
+ Deps.STRICT,
+ Exports.DO_NOT_USE,
+ Services.ALLOW,
+ /* protocOpts= */ ImmutableList.of()));
+ assertThat(e)
+ .hasMessageThat()
+ .isEqualTo(
+ "Invocation name pluginName appears more than once. "
+ + "This could lead to incorrect proto-compiler behavior");
}
@Test
diff --git a/src/test/java/com/google/devtools/build/lib/server/GrpcServerTest.java b/src/test/java/com/google/devtools/build/lib/server/GrpcServerTest.java
index c8cd21b..bda3a39 100644
--- a/src/test/java/com/google/devtools/build/lib/server/GrpcServerTest.java
+++ b/src/test/java/com/google/devtools/build/lib/server/GrpcServerTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.server;
import static com.google.common.truth.Truth.assertThat;
-import static junit.framework.TestCase.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -210,17 +210,14 @@
public void testInterruptsCommandThreadOnCancellation() throws Exception {
final CountDownLatch safety = new CountDownLatch(1);
final AtomicBoolean interrupted = new AtomicBoolean(false);
- TestThread victim = new TestThread() {
- @Override
- public void runTest() throws Exception {
- try {
- safety.await();
- fail("Test thread finished unexpectedly");
- } catch (InterruptedException e) {
- interrupted.set(true);
- }
- }
- };
+ TestThread victim =
+ new TestThread() {
+ @Override
+ public void runTest() throws Exception {
+ assertThrows(InterruptedException.class, () -> safety.await());
+ interrupted.set(true);
+ }
+ };
victim.setDaemon(true);
victim.start();
diff --git a/src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java b/src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java
index 1a66d13..43b8ed4 100644
--- a/src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java
+++ b/src/test/java/com/google/devtools/build/lib/skylark/util/SkylarkTestCase.java
@@ -15,7 +15,7 @@
package com.google.devtools.build.lib.skylark.util;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
@@ -164,41 +164,28 @@
protected void checkError(SkylarkRuleContext ruleContext, String errorMsg, String... lines)
throws Exception {
- try {
- evalRuleContextCode(ruleContext, lines);
- fail();
- } catch (EvalException e) {
- assertThat(e).hasMessageThat().isEqualTo(errorMsg);
- }
+ EvalException e =
+ assertThrows(EvalException.class, () -> evalRuleContextCode(ruleContext, lines));
+ assertThat(e).hasMessageThat().isEqualTo(errorMsg);
}
protected void checkErrorStartsWith(
SkylarkRuleContext ruleContext, String errorMsg, String... lines) throws Exception {
- try {
- evalRuleContextCode(ruleContext, lines);
- fail();
- } catch (EvalException e) {
- assertThat(e).hasMessageThat().startsWith(errorMsg);
- }
+ EvalException e =
+ assertThrows(EvalException.class, () -> evalRuleContextCode(ruleContext, lines));
+ assertThat(e).hasMessageThat().startsWith(errorMsg);
}
protected void checkErrorContains(String errorMsg, String... lines) throws Exception {
ev.setFailFast(false);
- try {
- eval(lines);
- fail("checkErrorContains(String, String...): There was no error");
- } catch (EvalException e) {
- assertThat(e).hasMessageThat().contains(errorMsg);
- }
+ EvalException e = assertThrows(EvalException.class, () -> eval(lines));
+ assertThat(e).hasMessageThat().contains(errorMsg);
}
protected void checkErrorContains(
SkylarkRuleContext ruleContext, String errorMsg, String... lines) throws Exception {
- try {
- evalRuleContextCode(ruleContext, lines);
- fail("checkErrorContains(SkylarkRuleContext, String, String...): There was no error");
- } catch (EvalException e) {
- assertThat(e).hasMessageThat().contains(errorMsg);
- }
+ EvalException e =
+ assertThrows(EvalException.class, () -> evalRuleContextCode(ruleContext, lines));
+ assertThat(e).hasMessageThat().contains(errorMsg);
}
}
diff --git a/src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java b/src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java
index b6f24fd..049ef85 100644
--- a/src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java
+++ b/src/test/java/com/google/devtools/build/lib/standalone/StandaloneSpawnStrategyTest.java
@@ -15,7 +15,7 @@
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -199,14 +199,10 @@
@Test
public void testBinFalseYieldsException() throws Exception {
- try {
- run(createSpawn(getFalseCommand()));
- fail();
- } catch (ExecException e) {
- assertWithMessage("got: " + e.getMessage())
- .that(e.getMessage().startsWith("false failed: error executing command"))
- .isTrue();
- }
+ ExecException e = assertThrows(ExecException.class, () -> run(createSpawn(getFalseCommand())));
+ assertWithMessage("got: " + e.getMessage())
+ .that(e.getMessage().startsWith("false failed: error executing command"))
+ .isTrue();
}
private static String getFalseCommand() {
diff --git a/src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java b/src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java
index e09ccb8..073f730 100644
--- a/src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java
+++ b/src/test/java/com/google/devtools/build/lib/testutil/MoreAssertsTest.java
@@ -16,7 +16,7 @@
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertContainsSublist;
import static com.google.devtools.build.lib.testutil.MoreAsserts.assertDoesNotContainSublist;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import java.util.Arrays;
import java.util.List;
@@ -49,26 +49,14 @@
public void testAssertContainsSublistFailure() {
List<String> actual = Arrays.asList("a", "b", "c");
- try {
- assertContainsSublist(actual, "d");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().startsWith("Did not find [d] as a sublist of [a, b, c]");
- }
+ AssertionError e = assertThrows(AssertionError.class, () -> assertContainsSublist(actual, "d"));
+ assertThat(e).hasMessageThat().startsWith("Did not find [d] as a sublist of [a, b, c]");
- try {
- assertContainsSublist(actual, "a", "c");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().startsWith("Did not find [a, c] as a sublist of [a, b, c]");
- }
+ e = assertThrows(AssertionError.class, () -> assertContainsSublist(actual, "a", "c"));
+ assertThat(e).hasMessageThat().startsWith("Did not find [a, c] as a sublist of [a, b, c]");
- try {
- assertContainsSublist(actual, "b", "c", "d");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().startsWith("Did not find [b, c, d] as a sublist of [a, b, c]");
- }
+ e = assertThrows(AssertionError.class, () -> assertContainsSublist(actual, "b", "c", "d"));
+ assertThat(e).hasMessageThat().startsWith("Did not find [b, c, d] as a sublist of [a, b, c]");
}
@Test
@@ -84,46 +72,24 @@
List<String> actual = Arrays.asList("a", "b", "c");
// All single-string combinations.
- try {
- assertDoesNotContainSublist(actual, "a");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().isEqualTo("Found [a] as a sublist of [a, b, c]");
- }
- try {
- assertDoesNotContainSublist(actual, "b");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().isEqualTo("Found [b] as a sublist of [a, b, c]");
- }
- try {
- assertDoesNotContainSublist(actual, "c");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().isEqualTo("Found [c] as a sublist of [a, b, c]");
- }
+ AssertionError e =
+ assertThrows(AssertionError.class, () -> assertDoesNotContainSublist(actual, "a"));
+ assertThat(e).hasMessageThat().isEqualTo("Found [a] as a sublist of [a, b, c]");
+ e = assertThrows(AssertionError.class, () -> assertDoesNotContainSublist(actual, "b"));
+ assertThat(e).hasMessageThat().isEqualTo("Found [b] as a sublist of [a, b, c]");
+ e = assertThrows(AssertionError.class, () -> assertDoesNotContainSublist(actual, "c"));
+ assertThat(e).hasMessageThat().isEqualTo("Found [c] as a sublist of [a, b, c]");
// All two-string combinations.
- try {
- assertDoesNotContainSublist(actual, "a", "b");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().isEqualTo("Found [a, b] as a sublist of [a, b, c]");
- }
- try {
- assertDoesNotContainSublist(actual, "b", "c");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().isEqualTo("Found [b, c] as a sublist of [a, b, c]");
- }
+ e = assertThrows(AssertionError.class, () -> assertDoesNotContainSublist(actual, "a", "b"));
+ assertThat(e).hasMessageThat().isEqualTo("Found [a, b] as a sublist of [a, b, c]");
+ e = assertThrows(AssertionError.class, () -> assertDoesNotContainSublist(actual, "b", "c"));
+ assertThat(e).hasMessageThat().isEqualTo("Found [b, c] as a sublist of [a, b, c]");
// The whole list.
- try {
- assertDoesNotContainSublist(actual, "a", "b", "c");
- fail("no exception thrown");
- } catch (AssertionError e) {
- assertThat(e).hasMessageThat().isEqualTo("Found [a, b, c] as a sublist of [a, b, c]");
- }
+ e =
+ assertThrows(
+ AssertionError.class, () -> assertDoesNotContainSublist(actual, "a", "b", "c"));
+ assertThat(e).hasMessageThat().isEqualTo("Found [a, b, c] as a sublist of [a, b, c]");
}
-
}
diff --git a/src/test/java/com/google/devtools/build/lib/util/io/AsynchronousFileOutputStreamTest.java b/src/test/java/com/google/devtools/build/lib/util/io/AsynchronousFileOutputStreamTest.java
index 2d5cc77..fbe008b 100644
--- a/src/test/java/com/google/devtools/build/lib/util/io/AsynchronousFileOutputStreamTest.java
+++ b/src/test/java/com/google/devtools/build/lib/util/io/AsynchronousFileOutputStreamTest.java
@@ -14,7 +14,7 @@
package com.google.devtools.build.lib.util.io;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.common.io.ByteStreams;
import com.google.devtools.build.lib.runtime.commands.proto.BazelFlagsProto.FlagInfo;
@@ -172,12 +172,8 @@
};
AsynchronousFileOutputStream out = new AsynchronousFileOutputStream("", failingOutputStream);
out.write("bla");
- try {
- out.close();
- fail("Expected an IOException");
- } catch (IOException expected) {
- assertThat(expected).hasMessageThat().isEqualTo("foo");
- }
+ IOException expected = assertThrows(IOException.class, () -> out.close());
+ assertThat(expected).hasMessageThat().isEqualTo("foo");
}
@Test
@@ -193,12 +189,8 @@
};
AsynchronousFileOutputStream out = new AsynchronousFileOutputStream("", failingOutputStream);
out.write("bla");
- try {
- out.close();
- fail("Expected a RuntimeException");
- } catch (RuntimeException expected) {
- assertThat(expected).hasMessageThat().isEqualTo("foo");
- }
+ RuntimeException expected = assertThrows(RuntimeException.class, () -> out.close());
+ assertThat(expected).hasMessageThat().isEqualTo("foo");
}
@Test
@@ -215,12 +207,8 @@
AsynchronousFileOutputStream out = new AsynchronousFileOutputStream("", failingOutputStream);
out.write("bla");
out.write("blo");
- try {
- out.close();
- fail("Expected an IOException");
- } catch (IOException expected) {
- assertThat(expected).hasMessageThat().isEqualTo("foo");
- }
+ IOException expected = assertThrows(IOException.class, () -> out.close());
+ assertThat(expected).hasMessageThat().isEqualTo("foo");
}
@Test
@@ -237,12 +225,8 @@
AsynchronousFileOutputStream out = new AsynchronousFileOutputStream("", failingOutputStream);
out.write("bla");
out.write("blo");
- try {
- out.close();
- fail("Expected a RuntimeException");
- } catch (RuntimeException expected) {
- assertThat(expected).hasMessageThat().isEqualTo("foo");
- }
+ RuntimeException expected = assertThrows(RuntimeException.class, () -> out.close());
+ assertThat(expected).hasMessageThat().isEqualTo("foo");
}
@Test
@@ -252,11 +236,6 @@
out.write("bla");
out.close();
- try {
- out.write("blo");
- fail("Expected an IllegalStateException");
- } catch (IllegalStateException expected) {
- // Expected.
- }
+ assertThrows(IllegalStateException.class, () -> out.write("blo"));
}
}
diff --git a/src/test/java/com/google/devtools/common/options/testing/ConverterTesterMapTest.java b/src/test/java/com/google/devtools/common/options/testing/ConverterTesterMapTest.java
index 0265f13..a6f5c08 100644
--- a/src/test/java/com/google/devtools/common/options/testing/ConverterTesterMapTest.java
+++ b/src/test/java/com/google/devtools/common/options/testing/ConverterTesterMapTest.java
@@ -15,7 +15,7 @@
package com.google.devtools.common.options.testing;
import static com.google.common.truth.Truth.assertThat;
-import static org.junit.Assert.fail;
+import static com.google.devtools.build.lib.testutil.MoreAsserts.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.devtools.common.options.Converters;
@@ -108,13 +108,10 @@
.add(new ConverterTester(Converters.BooleanConverter.class))
.add(new ConverterTester(Converters.BooleanConverter.class));
- try {
- builder.build();
- fail("expected build() with duplicate to fail");
- } catch (IllegalArgumentException expected) {
- assertThat(expected)
- .hasMessageThat()
- .contains(Converters.BooleanConverter.class.getSimpleName());
- }
+ IllegalArgumentException expected =
+ assertThrows(IllegalArgumentException.class, () -> builder.build());
+ assertThat(expected)
+ .hasMessageThat()
+ .contains(Converters.BooleanConverter.class.getSimpleName());
}
}