diff options
author | 2017-05-29 11:00:40 +0200 | |
---|---|---|
committer | 2017-05-29 14:08:41 +0200 | |
commit | bf6ef0f6051e7c8d9e87c42dd55b8a3a36044a78 (patch) | |
tree | 185f4340f22c2cdfa20dd71e4f7f2e10b0fde3c6 /src/test/java/com | |
parent | 506fb1a07fb8fac54ef649b050156e13f6098f46 (diff) |
Migrate tests to Truth.
RELNOTES: None.
PiperOrigin-RevId: 157378037
Diffstat (limited to 'src/test/java/com')
36 files changed, 910 insertions, 930 deletions
diff --git a/src/test/java/com/google/devtools/build/android/BUILD b/src/test/java/com/google/devtools/build/android/BUILD index d500d3b2f3..70b6fb6fae 100644 --- a/src/test/java/com/google/devtools/build/android/BUILD +++ b/src/test/java/com/google/devtools/build/android/BUILD @@ -140,6 +140,7 @@ java_test( "//src/tools/android/java/com/google/devtools/build/android:android_builder_lib", "//third_party:guava", "//third_party:junit4", + "//third_party:truth", ], ) diff --git a/src/test/java/com/google/devtools/build/android/DensitySpecificManifestProcessorTest.java b/src/test/java/com/google/devtools/build/android/DensitySpecificManifestProcessorTest.java index 9d02a28ef8..b62717dba7 100644 --- a/src/test/java/com/google/devtools/build/android/DensitySpecificManifestProcessorTest.java +++ b/src/test/java/com/google/devtools/build/android/DensitySpecificManifestProcessorTest.java @@ -18,7 +18,6 @@ import static com.google.devtools.build.android.DensitySpecificManifestProcessor import static com.google.devtools.build.android.DensitySpecificManifestProcessor.SCREEN_SIZES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.base.Joiner; @@ -225,19 +224,20 @@ public class DensitySpecificManifestProcessorTest { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(Files.newInputStream(manifest)); NodeList compatibleScreensNodes = doc.getElementsByTagName("compatible-screens"); - assertEquals(1, compatibleScreensNodes.getLength()); + assertThat(compatibleScreensNodes.getLength()).isEqualTo(1); Node compatibleScreens = compatibleScreensNodes.item(0); NodeList screens = doc.getElementsByTagName("screen"); - assertEquals(densities.size() * SCREEN_SIZES.size(), - screens.getLength()); + assertThat(screens.getLength()).isEqualTo(densities.size() * SCREEN_SIZES.size()); for (int i = 0; i < screens.getLength(); i++) { Node s = screens.item(i); - assertTrue(s.getParentNode().isSameNode(compatibleScreens)); + assertThat(s.getParentNode().isSameNode(compatibleScreens)).isTrue(); if (s.getNodeType() == Node.ELEMENT_NODE) { Element screen = (Element) s; - assertTrue(sizeDensities.remove( - screen.getAttribute("android:screenSize") - + screen.getAttribute("android:screenDensity"))); + assertThat( + sizeDensities.remove( + screen.getAttribute("android:screenSize") + + screen.getAttribute("android:screenDensity"))) + .isTrue(); } } assertThat(sizeDensities).isEmpty(); @@ -247,9 +247,9 @@ public class DensitySpecificManifestProcessorTest { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = db.parse(Files.newInputStream(manifest)); NodeList compatibleScreensNodes = doc.getElementsByTagName("compatible-screens"); - assertEquals(0, compatibleScreensNodes.getLength()); + assertThat(compatibleScreensNodes.getLength()).isEqualTo(0); NodeList screens = doc.getElementsByTagName("screen"); - assertEquals(0, screens.getLength()); + assertThat(screens.getLength()).isEqualTo(0); } } diff --git a/src/test/java/com/google/devtools/build/android/DensitySpecificResourceFilterTest.java b/src/test/java/com/google/devtools/build/android/DensitySpecificResourceFilterTest.java index a7b1383051..5c60d4dc0a 100644 --- a/src/test/java/com/google/devtools/build/android/DensitySpecificResourceFilterTest.java +++ b/src/test/java/com/google/devtools/build/android/DensitySpecificResourceFilterTest.java @@ -13,7 +13,7 @@ // limitations under the License. package com.google.devtools.build.android; -import static org.junit.Assert.assertArrayEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; @@ -241,7 +241,7 @@ public class DensitySpecificResourceFilterTest { String[] actual = filteredResources.build().toArray(new String[0]); Arrays.sort(expected); Arrays.sort(actual); - assertArrayEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } @Before @@ -281,6 +281,6 @@ public class DensitySpecificResourceFilterTest { Arrays.sort(expected); Arrays.sort(actual); - assertArrayEquals(expected, actual); + assertThat(actual).isEqualTo(expected); } } diff --git a/src/test/java/com/google/devtools/build/android/ManifestMergerActionTest.java b/src/test/java/com/google/devtools/build/android/ManifestMergerActionTest.java index 61d77dd128..1f16f5bc7b 100644 --- a/src/test/java/com/google/devtools/build/android/ManifestMergerActionTest.java +++ b/src/test/java/com/google/devtools/build/android/ManifestMergerActionTest.java @@ -58,7 +58,7 @@ public class ManifestMergerActionTest { final File expectedManifestDirectory = manifestData.resolve("expected").toFile(); final File[] expectedManifestDirectoryManifests = expectedManifestDirectory.listFiles(new PatternFilenameFilter(".*AndroidManifest\\.xml$")); - assertThat(expectedManifestDirectoryManifests.length).isEqualTo(1); + assertThat(expectedManifestDirectoryManifests).hasLength(1); final Path expectedManifest = expectedManifestDirectoryManifests[0].toPath(); Files.createDirectories(working.resolve("output")); diff --git a/src/test/java/com/google/devtools/build/android/ziputils/BufferedFileTest.java b/src/test/java/com/google/devtools/build/android/ziputils/BufferedFileTest.java index e5bc7a4c45..e4836871cb 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/BufferedFileTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/BufferedFileTest.java @@ -14,20 +14,16 @@ package com.google.devtools.build.android.ziputils; import static com.google.common.truth.Truth.assertWithMessage; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -/** - * Unit tests for {@link BufferedFile}. - */ +/** Unit tests for {@link BufferedFile}. */ @RunWith(JUnit4.class) public class BufferedFileTest { @@ -215,7 +211,7 @@ public class BufferedFileTest { assertWithMessage(msg + " - capacity, ").that(buf.capacity()).isAtLeast(expectLimit); assertWithMessage(msg + " - capacity, ").that(buf.capacity()).isAtMost(capacityBound); if (len > 0 && expectLimit > 0) { - assertEquals(msg + " - value, ", (byte) off, buf.get(0)); + assertWithMessage(msg + " - value, ").that(buf.get(0)).isEqualTo((byte) off); } } diff --git a/src/test/java/com/google/devtools/build/android/ziputils/CentralDirectoryTest.java b/src/test/java/com/google/devtools/build/android/ziputils/CentralDirectoryTest.java index 29ff27d309..b005f4701b 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/CentralDirectoryTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/CentralDirectoryTest.java @@ -13,19 +13,16 @@ // limitations under the License. package com.google.devtools.build.android.ziputils; +import static com.google.common.truth.Truth.assertWithMessage; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENTIM; -import static org.junit.Assert.assertEquals; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -/** - * Unit tests for {@link CentralDirectory}. - */ +/** Unit tests for {@link CentralDirectory}. */ @RunWith(JUnit4.class) public class CentralDirectoryTest { @@ -44,10 +41,10 @@ public class CentralDirectoryTest { int expPos = 0; int expLimit = 90; // expect the buffer to have been reset to 0 (CentralDirectory does NOT slice). - assertEquals("View not at position 0", expPos, view.buffer.position()); - assertEquals("Buffer not at position 0", expPos, buffer.position()); - assertEquals("Buffer limit changed", expLimit, view.buffer.limit()); - assertEquals("Buffer limit changed", expLimit, buffer.limit()); + assertWithMessage("View not at position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Buffer not at position 0").that(buffer.position()).isEqualTo(expPos); + assertWithMessage("Buffer limit changed").that(view.buffer.limit()).isEqualTo(expLimit); + assertWithMessage("Buffer limit changed").that(buffer.limit()).isEqualTo(expLimit); } /** @@ -73,12 +70,12 @@ public class CentralDirectoryTest { } // Parse the entries. CentralDirectory cdir = CentralDirectory.viewOf(inputBuffer).at(0).parse(); - assertEquals("Count", 20, cdir.getCount()); - assertEquals("Position after parse", expSize, cdir.buffer.position()); - assertEquals("Limit after parse", 10000, cdir.buffer.limit()); + assertWithMessage("Count").that(cdir.getCount()).isEqualTo(20); + assertWithMessage("Position after parse").that(cdir.buffer.position()).isEqualTo(expSize); + assertWithMessage("Limit after parse").that(cdir.buffer.limit()).isEqualTo(10000); cdir.buffer.flip(); - assertEquals("Position after finish", 0, cdir.buffer.position()); - assertEquals("Limit after finish", expSize, cdir.buffer.limit()); + assertWithMessage("Position after finish").that(cdir.buffer.position()).isEqualTo(0); + assertWithMessage("Limit after finish").that(cdir.buffer.limit()).isEqualTo(expSize); } /** @@ -105,20 +102,20 @@ public class CentralDirectoryTest { extra = new byte[extra.length + 1]; comment = comment + "," + i; } - assertEquals("Count", 20, cdir.getCount()); - assertEquals("Position after build", expSize, cdir.buffer.position()); - assertEquals("Limit after build", 10000, cdir.buffer.limit()); + assertWithMessage("Count").that(cdir.getCount()).isEqualTo(20); + assertWithMessage("Position after build").that(cdir.buffer.position()).isEqualTo(expSize); + assertWithMessage("Limit after build").that(cdir.buffer.limit()).isEqualTo(10000); cdir.buffer.flip(); - assertEquals("Position after finish build", 0, cdir.buffer.position()); - assertEquals("Limit after finish build", expSize, cdir.buffer.limit()); + assertWithMessage("Position after finish build").that(cdir.buffer.position()).isEqualTo(0); + assertWithMessage("Limit after finish build").that(cdir.buffer.limit()).isEqualTo(expSize); // now try to parse the directory we just created. cdir.at(0).parse(); - assertEquals("Count", 20, cdir.getCount()); - assertEquals("Position after re-parse", expSize, cdir.buffer.position()); - assertEquals("Limit after re-parse", expSize, cdir.buffer.limit()); + assertWithMessage("Count").that(cdir.getCount()).isEqualTo(20); + assertWithMessage("Position after re-parse").that(cdir.buffer.position()).isEqualTo(expSize); + assertWithMessage("Limit after re-parse").that(cdir.buffer.limit()).isEqualTo(expSize); cdir.buffer.flip(); - assertEquals("Position after finish parse", 0, cdir.buffer.position()); - assertEquals("Limit after finish parse", expSize, cdir.buffer.limit()); + assertWithMessage("Position after finish parse").that(cdir.buffer.position()).isEqualTo(0); + assertWithMessage("Limit after finish parse").that(cdir.buffer.limit()).isEqualTo(expSize); } } diff --git a/src/test/java/com/google/devtools/build/android/ziputils/DataDescriptorTest.java b/src/test/java/com/google/devtools/build/android/ziputils/DataDescriptorTest.java index ffb6f64870..567f2919a6 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/DataDescriptorTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/DataDescriptorTest.java @@ -13,24 +13,20 @@ // limitations under the License. package com.google.devtools.build.android.ziputils; +import static com.google.common.truth.Truth.assertWithMessage; import static com.google.devtools.build.android.ziputils.DataDescriptor.EXTCRC; import static com.google.devtools.build.android.ziputils.DataDescriptor.EXTLEN; import static com.google.devtools.build.android.ziputils.DataDescriptor.EXTSIG; import static com.google.devtools.build.android.ziputils.DataDescriptor.EXTSIZ; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.zip.ZipInputStream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -/** - * Unit tests for {@link DataDescriptor}. - */ +/** Unit tests for {@link DataDescriptor}. */ @RunWith(JUnit4.class) public class DataDescriptorTest { @@ -53,10 +49,18 @@ public class DataDescriptorTest { int expSize = marker == DataDescriptor.SIGNATURE ? ZipInputStream.EXTHDR : ZipInputStream.EXTHDR - 4; int expPos = 0; - assertEquals("not based at current position[" + marker + "]", expMark, view.get(EXTSIG)); - assertEquals("Not slice with position 0[" + marker + "]", expPos, view.buffer.position()); - assertEquals("Not sized with comment[" + marker + "]", expSize, view.getSize()); - assertEquals("Not limited to size[" + marker + "]", expSize, view.buffer.limit()); + assertWithMessage("not based at current position[" + marker + "]") + .that(view.get(EXTSIG)) + .isEqualTo(expMark); + assertWithMessage("Not slice with position 0[" + marker + "]") + .that(view.buffer.position()) + .isEqualTo(expPos); + assertWithMessage("Not sized with comment[" + marker + "]") + .that(view.getSize()) + .isEqualTo(expSize); + assertWithMessage("Not limited to size[" + marker + "]") + .that(view.buffer.limit()) + .isEqualTo(expSize); } } @@ -69,11 +73,11 @@ public class DataDescriptorTest { int expSize = ZipInputStream.EXTHDR; int expPos = 0; int expMarker = (int) ZipInputStream.EXTSIG; - assertTrue("no marker", view.hasMarker()); - assertEquals("No marker", expMarker, view.get(EXTSIG)); - assertEquals("Not at position 0", expPos, view.buffer.position()); - assertEquals("Not sized correctly", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); + assertWithMessage("no marker").that(view.hasMarker()).isTrue(); + assertWithMessage("No marker").that(view.get(EXTSIG)).isEqualTo(expMarker); + assertWithMessage("Not at position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized correctly").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); } /** @@ -90,10 +94,10 @@ public class DataDescriptorTest { int expMark = (int) ZipInputStream.EXTSIG; int expSize = ZipInputStream.EXTHDR; int expPos = 0; - assertEquals("not based at current position", expMark, view.get(EXTSIG)); - assertEquals("Not slice with position 0", expPos, view.buffer.position()); - assertEquals("Not sized with comment", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); + assertWithMessage("not based at current position").that(view.get(EXTSIG)).isEqualTo(expMark); + assertWithMessage("Not slice with position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized with comment").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); } /** @@ -105,10 +109,10 @@ public class DataDescriptorTest { DataDescriptor view = DataDescriptor.allocate(); view.copy(buffer); int expSize = view.getSize(); - assertEquals("buffer not advanced as expected", expSize, buffer.position()); + assertWithMessage("buffer not advanced as expected").that(buffer.position()).isEqualTo(expSize); buffer.position(0); DataDescriptor clone = DataDescriptor.viewOf(buffer); - assertEquals("Fail to copy mark", view.get(EXTSIG), clone.get(EXTSIG)); + assertWithMessage("Fail to copy mark").that(clone.get(EXTSIG)).isEqualTo(view.get(EXTSIG)); } /** @@ -123,8 +127,8 @@ public class DataDescriptorTest { .set(EXTCRC, crc) .set(EXTSIZ, compressed) .set(EXTLEN, uncompressed); - assertEquals("CRC", crc, view.get(EXTCRC)); - assertEquals("Compressed size", compressed, view.get(EXTSIZ)); - assertEquals("Uncompressed size", uncompressed, view.get(EXTLEN)); + assertWithMessage("CRC").that(view.get(EXTCRC)).isEqualTo(crc); + assertWithMessage("Compressed size").that(view.get(EXTSIZ)).isEqualTo(compressed); + assertWithMessage("Uncompressed size").that(view.get(EXTLEN)).isEqualTo(uncompressed); } } diff --git a/src/test/java/com/google/devtools/build/android/ziputils/DirectoryEntryTest.java b/src/test/java/com/google/devtools/build/android/ziputils/DirectoryEntryTest.java index 6452dcbd12..4fa7c5409c 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/DirectoryEntryTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/DirectoryEntryTest.java @@ -13,6 +13,7 @@ // limitations under the License. package com.google.devtools.build.android.ziputils; +import static com.google.common.truth.Truth.assertWithMessage; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENATT; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENATX; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENCRC; @@ -27,20 +28,15 @@ import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENTIM; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENVEM; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENVER; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.zip.ZipInputStream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -/** - * Unit tests for {@link DirectoryEntry}. - */ +/** Unit tests for {@link DirectoryEntry}. */ @RunWith(JUnit4.class) public class DirectoryEntryTest { @@ -67,10 +63,10 @@ public class DirectoryEntryTest { int expMark = (int) ZipInputStream.CENSIG; int expSize = ZipInputStream.CENHDR + filenameLength + extraLength + commentLength; int expPos = 0; - assertEquals("not based at current position", expMark, view.get(CENSIG)); - assertEquals("Not slice with position 0", expPos, view.buffer.position()); - assertEquals("Not sized with comment", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); + assertWithMessage("not based at current position").that(view.get(CENSIG)).isEqualTo(expMark); + assertWithMessage("Not slice with position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized with comment").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); } /** @@ -85,12 +81,12 @@ public class DirectoryEntryTest { + extraData.length + comment.getBytes(UTF_8).length; int expPos = 0; DirectoryEntry view = DirectoryEntry.allocate(filename, extraData, comment); - assertEquals("Incorrect filename", filename, view.getFilename()); - Assert.assertArrayEquals("Incorrect extra data", extraData, view.getExtraData()); - assertEquals("Incorrect comment", comment, view.getComment()); - assertEquals("Not at position 0", expPos, view.buffer.position()); - assertEquals("Not sized correctly", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); + assertWithMessage("Incorrect filename").that(view.getFilename()).isEqualTo(filename); + assertWithMessage("Incorrect extra data").that(view.getExtraData()).isEqualTo(extraData); + assertWithMessage("Incorrect comment").that(view.getComment()).isEqualTo(comment); + assertWithMessage("Not at position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized correctly").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); } /** @@ -112,13 +108,13 @@ public class DirectoryEntryTest { + comment.getBytes(UTF_8).length; int expPos = 0; DirectoryEntry view = DirectoryEntry.view(buffer, filename, extraData, comment); - assertEquals("not based at current position", expMark, view.get(CENSIG)); - assertEquals("Not slice with position 0", expPos, view.buffer.position()); - assertEquals("Not sized with filename", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); - assertEquals("Incorrect filename", filename, view.getFilename()); - Assert.assertArrayEquals("Incorrect extra data", extraData, view.getExtraData()); - assertEquals("Incorrect comment", comment, view.getComment()); + assertWithMessage("not based at current position").that(view.get(CENSIG)).isEqualTo(expMark); + assertWithMessage("Not slice with position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized with filename").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); + assertWithMessage("Incorrect filename").that(view.getFilename()).isEqualTo(filename); + assertWithMessage("Incorrect extra data").that(view.getExtraData()).isEqualTo(extraData); + assertWithMessage("Incorrect comment").that(view.getComment()).isEqualTo(comment); } /** @@ -133,13 +129,17 @@ public class DirectoryEntryTest { DirectoryEntry view = DirectoryEntry.allocate(filename, extraData, comment); view.copy(buffer); int expSize = view.getSize(); - assertEquals("buffer not advanced as expected", expSize, buffer.position()); + assertWithMessage("buffer not advanced as expected").that(buffer.position()).isEqualTo(expSize); buffer.position(0); DirectoryEntry clone = DirectoryEntry.viewOf(buffer); - assertEquals("Fail to copy mark", view.get(CENSIG), clone.get(CENSIG)); - assertEquals("Fail to copy comment", view.getFilename(), clone.getFilename()); - Assert.assertArrayEquals("Fail to copy comment", view.getExtraData(), clone.getExtraData()); - assertEquals("Fail to copy comment", view.getComment(), clone.getComment()); + assertWithMessage("Fail to copy mark").that(clone.get(CENSIG)).isEqualTo(view.get(CENSIG)); + assertWithMessage("Fail to copy comment") + .that(clone.getFilename()) + .isEqualTo(view.getFilename()); + assertWithMessage("Fail to copy comment") + .that(clone.getExtraData()) + .isEqualTo(view.getExtraData()); + assertWithMessage("Fail to copy comment").that(clone.getComment()).isEqualTo(view.getComment()); } /** @@ -172,17 +172,17 @@ public class DirectoryEntryTest { .set(CENATX, extAttr) .set(CENATT, intAttr) .set(CENOFF, offset); - assertEquals("CRC", crc, view.get(CENCRC)); - assertEquals("Compressed size", compressed, view.get(CENSIZ)); - assertEquals("Uncompressed size", uncompressed, view.get(CENLEN)); - assertEquals("Flags", flags, view.get(CENFLG)); - assertEquals("Method", method, view.get(CENHOW)); - assertEquals("Modified time", time, view.get(CENTIM)); - assertEquals("Version needed", version, view.get(CENVER)); - assertEquals("Version made by", versionMadeBy, view.get(CENVEM)); - assertEquals("Disk", disk, view.get(CENDSK)); - assertEquals("External attributes", extAttr, view.get(CENATX)); - assertEquals("Internal attributes", intAttr, view.get(CENATT)); - assertEquals("Offset", offset, view.get(CENOFF)); + assertWithMessage("CRC").that(view.get(CENCRC)).isEqualTo(crc); + assertWithMessage("Compressed size").that(view.get(CENSIZ)).isEqualTo(compressed); + assertWithMessage("Uncompressed size").that(view.get(CENLEN)).isEqualTo(uncompressed); + assertWithMessage("Flags").that(view.get(CENFLG)).isEqualTo(flags); + assertWithMessage("Method").that(view.get(CENHOW)).isEqualTo(method); + assertWithMessage("Modified time").that(view.get(CENTIM)).isEqualTo(time); + assertWithMessage("Version needed").that(view.get(CENVER)).isEqualTo(version); + assertWithMessage("Version made by").that(view.get(CENVEM)).isEqualTo(versionMadeBy); + assertWithMessage("Disk").that(view.get(CENDSK)).isEqualTo(disk); + assertWithMessage("External attributes").that(view.get(CENATX)).isEqualTo(extAttr); + assertWithMessage("Internal attributes").that(view.get(CENATT)).isEqualTo(intAttr); + assertWithMessage("Offset").that(view.get(CENOFF)).isEqualTo(offset); } } diff --git a/src/test/java/com/google/devtools/build/android/ziputils/EndOfCentralDirectoryTest.java b/src/test/java/com/google/devtools/build/android/ziputils/EndOfCentralDirectoryTest.java index edd6115088..7f0534cf38 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/EndOfCentralDirectoryTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/EndOfCentralDirectoryTest.java @@ -13,6 +13,7 @@ // limitations under the License. package com.google.devtools.build.android.ziputils; +import static com.google.common.truth.Truth.assertWithMessage; import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.ENDDCD; import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.ENDDSK; import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.ENDOFF; @@ -21,19 +22,15 @@ import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.E import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.ENDSUB; import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.ENDTOT; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.zip.ZipInputStream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -/** - * Unit tests for {@link EndOfCentralDirectory}. - */ +/** Unit tests for {@link EndOfCentralDirectory}. */ @RunWith(JUnit4.class) public class EndOfCentralDirectoryTest { @Test @@ -52,10 +49,10 @@ public class EndOfCentralDirectoryTest { int expMark = (int) ZipInputStream.ENDSIG; int expSize = ZipInputStream.ENDHDR + comLength; // fixed + comment int expPos = 0; - assertEquals("not based at current position", expMark, view.get(ENDSIG)); - assertEquals("Not slice with position 0", expPos, view.buffer.position()); - assertEquals("Not sized with comment", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); + assertWithMessage("not based at current position").that(view.get(ENDSIG)).isEqualTo(expMark); + assertWithMessage("Not slice with position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized with comment").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); } @Test @@ -66,12 +63,12 @@ public class EndOfCentralDirectoryTest { String expComment = comment != null ? comment : ""; EndOfCentralDirectory view = EndOfCentralDirectory.allocate(comment); String commentResult = view.getComment(); - assertEquals("Incorrect comment", expComment, commentResult); + assertWithMessage("Incorrect comment").that(commentResult).isEqualTo(expComment); int expSize = ZipInputStream.ENDHDR + (comment != null ? comment.getBytes(UTF_8).length : 0); int expPos = 0; - assertEquals("Not at position 0", expPos, view.buffer.position()); - assertEquals("Not sized correctly", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); + assertWithMessage("Not at position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized correctly").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); } } @@ -88,11 +85,11 @@ public class EndOfCentralDirectoryTest { int expMark = (int) ZipInputStream.ENDSIG; int expSize = ZipInputStream.ENDHDR + comment.length(); int expPos = 0; - assertEquals("not based at current position", expMark, view.get(ENDSIG)); - assertEquals("Not slice with position 0", expPos, view.buffer.position()); - assertEquals("Not sized with comment", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); - assertEquals("Incorrect comment", comment, view.getComment()); + assertWithMessage("not based at current position").that(view.get(ENDSIG)).isEqualTo(expMark); + assertWithMessage("Not slice with position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized with comment").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); + assertWithMessage("Incorrect comment").that(view.getComment()).isEqualTo(comment); } @Test @@ -101,11 +98,11 @@ public class EndOfCentralDirectoryTest { EndOfCentralDirectory view = EndOfCentralDirectory.allocate("comment"); view.copy(buffer); int expSize = view.getSize(); - assertEquals("buffer not advanced as expected", expSize, buffer.position()); + assertWithMessage("buffer not advanced as expected").that(buffer.position()).isEqualTo(expSize); buffer.position(0); EndOfCentralDirectory clone = EndOfCentralDirectory.viewOf(buffer); - assertEquals("Fail to copy mark", view.get(ENDSIG), clone.get(ENDSIG)); - assertEquals("Fail to copy comment", view.getComment(), clone.getComment()); + assertWithMessage("Fail to copy mark").that(clone.get(ENDSIG)).isEqualTo(view.get(ENDSIG)); + assertWithMessage("Fail to copy comment").that(clone.getComment()).isEqualTo(view.getComment()); } @Test @@ -123,11 +120,13 @@ public class EndOfCentralDirectoryTest { .set(ENDDSK, disk) .set(ENDSUB, local) .set(ENDTOT, total); - assertEquals("Central directory start disk", cdDisk, view.get(ENDDCD)); - assertEquals("Central directory file offset", cdOffset, view.get(ENDOFF)); - assertEquals("Central directory size", cdSize, view.get(ENDSIZ)); - assertEquals("This disk number", disk, view.get(ENDDSK)); - assertEquals("Number of records on this disk", local, view.get(ENDSUB)); - assertEquals("Total number of central directory records", total, view.get(ENDTOT)); + assertWithMessage("Central directory start disk").that(view.get(ENDDCD)).isEqualTo(cdDisk); + assertWithMessage("Central directory file offset").that(view.get(ENDOFF)).isEqualTo(cdOffset); + assertWithMessage("Central directory size").that(view.get(ENDSIZ)).isEqualTo(cdSize); + assertWithMessage("This disk number").that(view.get(ENDDSK)).isEqualTo(disk); + assertWithMessage("Number of records on this disk").that(view.get(ENDSUB)).isEqualTo(local); + assertWithMessage("Total number of central directory records") + .that(view.get(ENDTOT)) + .isEqualTo(total); } } diff --git a/src/test/java/com/google/devtools/build/android/ziputils/LocalFileHeaderTest.java b/src/test/java/com/google/devtools/build/android/ziputils/LocalFileHeaderTest.java index 7791f2d8ba..4c347b854a 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/LocalFileHeaderTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/LocalFileHeaderTest.java @@ -13,6 +13,7 @@ // limitations under the License. package com.google.devtools.build.android.ziputils; +import static com.google.common.truth.Truth.assertWithMessage; import static com.google.devtools.build.android.ziputils.LocalFileHeader.LOCCRC; import static com.google.devtools.build.android.ziputils.LocalFileHeader.LOCFLG; import static com.google.devtools.build.android.ziputils.LocalFileHeader.LOCHOW; @@ -22,20 +23,15 @@ import static com.google.devtools.build.android.ziputils.LocalFileHeader.LOCSIZ; import static com.google.devtools.build.android.ziputils.LocalFileHeader.LOCTIM; import static com.google.devtools.build.android.ziputils.LocalFileHeader.LOCVER; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.zip.ZipInputStream; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -/** - * Unit tests for {@link LocalFileHeader}. - */ +/** Unit tests for {@link LocalFileHeader}. */ @RunWith(JUnit4.class) public class LocalFileHeaderTest { @@ -57,10 +53,10 @@ public class LocalFileHeaderTest { int expMark = (int) ZipInputStream.LOCSIG; int expSize = ZipInputStream.LOCHDR + filenameLength + extraLength; // fixed + comment int expPos = 0; - assertEquals("not based at current position", expMark, view.get(LOCSIG)); - assertEquals("Not slice with position 0", expPos, view.buffer.position()); - assertEquals("Not sized with comment", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); + assertWithMessage("not based at current position").that(view.get(LOCSIG)).isEqualTo(expMark); + assertWithMessage("Not slice with position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized with comment").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); } @Test @@ -71,11 +67,11 @@ public class LocalFileHeaderTest { + extraData.length; int expPos = 0; LocalFileHeader view = LocalFileHeader.allocate(filename, extraData); - assertEquals("Incorrect filename", filename, view.getFilename()); - Assert.assertArrayEquals("Incorrect extra data", extraData, view.getExtraData()); - assertEquals("Not at position 0", expPos, view.buffer.position()); - assertEquals("Not sized correctly", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); + assertWithMessage("Incorrect filename").that(view.getFilename()).isEqualTo(filename); + assertWithMessage("Incorrect extra data").that(view.getExtraData()).isEqualTo(extraData); + assertWithMessage("Not at position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized correctly").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); } @Test @@ -91,11 +87,11 @@ public class LocalFileHeaderTest { int expSize = ZipInputStream.LOCHDR + filename.getBytes(UTF_8).length; int expPos = 0; LocalFileHeader view = LocalFileHeader.view(buffer, filename, null); - assertEquals("not based at current position", expMark, view.get(LOCSIG)); - assertEquals("Not slice with position 0", expPos, view.buffer.position()); - assertEquals("Not sized with filename", expSize, view.getSize()); - assertEquals("Not limited to size", expSize, view.buffer.limit()); - assertEquals("Incorrect filename", filename, view.getFilename()); + assertWithMessage("not based at current position").that(view.get(LOCSIG)).isEqualTo(expMark); + assertWithMessage("Not slice with position 0").that(view.buffer.position()).isEqualTo(expPos); + assertWithMessage("Not sized with filename").that(view.getSize()).isEqualTo(expSize); + assertWithMessage("Not limited to size").that(view.buffer.limit()).isEqualTo(expSize); + assertWithMessage("Incorrect filename").that(view.getFilename()).isEqualTo(filename); } @Test @@ -104,11 +100,13 @@ public class LocalFileHeaderTest { LocalFileHeader view = LocalFileHeader.allocate("pkg/foo.class", null); view.copy(buffer); int expSize = view.getSize(); - assertEquals("buffer not advanced as expected", expSize, buffer.position()); + assertWithMessage("buffer not advanced as expected").that(buffer.position()).isEqualTo(expSize); buffer.position(0); LocalFileHeader clone = LocalFileHeader.viewOf(buffer); - assertEquals("Fail to copy mark", view.get(LOCSIG), view.get(LOCSIG)); - assertEquals("Fail to copy comment", view.getFilename(), clone.getFilename()); + assertWithMessage("Fail to copy mark").that(view.get(LOCSIG)).isEqualTo(view.get(LOCSIG)); + assertWithMessage("Fail to copy comment") + .that(clone.getFilename()) + .isEqualTo(view.getFilename()); } @Test @@ -128,12 +126,12 @@ public class LocalFileHeaderTest { .set(LOCHOW, method) .set(LOCTIM, time) .set(LOCVER, version); - assertEquals("CRC", crc, view.get(LOCCRC)); - assertEquals("Compressed size", compressed, view.get(LOCSIZ)); - assertEquals("Uncompressed size", uncompressed, view.get(LOCLEN)); - assertEquals("Flags", flags, view.get(LOCFLG)); - assertEquals("Method", method, view.get(LOCHOW)); - assertEquals("Modified time", time, view.get(LOCTIM)); - assertEquals("Version needed", version, view.get(LOCVER)); + assertWithMessage("CRC").that(view.get(LOCCRC)).isEqualTo(crc); + assertWithMessage("Compressed size").that(view.get(LOCSIZ)).isEqualTo(compressed); + assertWithMessage("Uncompressed size").that(view.get(LOCLEN)).isEqualTo(uncompressed); + assertWithMessage("Flags").that(view.get(LOCFLG)).isEqualTo(flags); + assertWithMessage("Method").that(view.get(LOCHOW)).isEqualTo(method); + assertWithMessage("Modified time").that(view.get(LOCTIM)).isEqualTo(time); + assertWithMessage("Version needed").that(view.get(LOCVER)).isEqualTo(version); } } diff --git a/src/test/java/com/google/devtools/build/android/ziputils/SplitZipTest.java b/src/test/java/com/google/devtools/build/android/ziputils/SplitZipTest.java index 5d6f861159..87cc5ce6d8 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/SplitZipTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/SplitZipTest.java @@ -14,26 +14,21 @@ package com.google.devtools.build.android.ziputils; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertWithMessage; import static org.junit.Assert.fail; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableSet; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Date; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; -/** - * Unit tests for {@link SplitZip}. - */ +/** Unit tests for {@link SplitZip}. */ @RunWith(JUnit4.class) public class SplitZipTest { private FakeFileSystem fileSystem; @@ -59,7 +54,9 @@ public class SplitZipTest { instance.addOutput((String) null); fail("should have failed"); } catch (Exception ex) { - assertTrue("NullPointerException expected", ex instanceof NullPointerException); + assertWithMessage("NullPointerException expected") + .that(ex instanceof NullPointerException) + .isTrue(); } try { SplitZip result = instance @@ -67,7 +64,7 @@ public class SplitZipTest { "out/shard1.jar")) .addOutput(new ZipOut(fileSystem.getOutputChannel("out/shard2.jar", false), "out/shard2.jar")); - assertSame(instance, result); + assertThat(result).isSameAs(instance); } catch (IOException ex) { fail("Unexpected exception: " + ex); } @@ -78,7 +75,7 @@ public class SplitZipTest { SplitZip instance = new SplitZip(); String res = "res"; SplitZip result = instance.setResourceFile(res); - assertSame(instance, result); + assertThat(result).isSameAs(instance); } @Test @@ -93,9 +90,9 @@ public class SplitZipTest { public void testSetMainClassListFile() { SplitZip instance = new SplitZip(); SplitZip result = instance.setMainClassListFile((String) null); - assertSame(instance, result); + assertThat(result).isSameAs(instance); result = instance.setMainClassListFile("no format checks"); - assertSame(instance, result); + assertThat(result).isSameAs(instance); } @Test @@ -113,7 +110,7 @@ public class SplitZipTest { public void testSetEntryDate() { SplitZip instance = new SplitZip(); SplitZip result = instance.setEntryDate(null); - assertSame(instance, result); + assertThat(result).isSameAs(instance); } @Test @@ -122,7 +119,7 @@ public class SplitZipTest { Date now = new Date(); instance.setEntryDate(now); Date result = instance.getEntryDate(); - assertSame(result, now); + assertThat(now).isSameAs(result); instance.setEntryDate(null); assertThat(instance.getEntryDate()).isNull(); } @@ -131,7 +128,7 @@ public class SplitZipTest { public void testUseDefaultEntryDate() { SplitZip instance = new SplitZip(); SplitZip result = instance.useDefaultEntryDate(); - assertSame(instance, result); + assertThat(result).isSameAs(instance); Date date = instance.getEntryDate(); assertThat(date).isEqualTo(DosTime.DOS_EPOCH); } @@ -144,7 +141,9 @@ public class SplitZipTest { instance.addInput(noexists); fail("should not be able to add non existing file: " + noexists); } catch (IOException ex) { - assertTrue("FileNotFoundException expected", ex instanceof FileNotFoundException); + assertWithMessage("FileNotFoundException expected") + .that(ex instanceof FileNotFoundException) + .isTrue(); } } @@ -156,7 +155,9 @@ public class SplitZipTest { instance.addInputs(Arrays.asList(noexists)); fail("should not be able to add non existing file: " + noexists); } catch (IOException ex) { - assertTrue("FileNotFoundException expected", ex instanceof FileNotFoundException); + assertWithMessage("FileNotFoundException expected") + .that(ex instanceof FileNotFoundException) + .isTrue(); } } diff --git a/src/test/java/com/google/devtools/build/android/ziputils/ViewTest.java b/src/test/java/com/google/devtools/build/android/ziputils/ViewTest.java index 91fbdb691a..17915270dc 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/ViewTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/ViewTest.java @@ -13,23 +13,17 @@ // limitations under the License. package com.google.devtools.build.android.ziputils; +import static com.google.common.truth.Truth.assertWithMessage; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; -import org.junit.Assert; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; - -/** - * Unit tests for {@link View}. - */ +/** Unit tests for {@link View}. */ @RunWith(JUnit4.class) public class ViewTest { @@ -44,10 +38,10 @@ public class ViewTest { buffer.putInt(12345678); int fromBuf = buffer.getInt(0); int fromView = instance.getInt(0); - assertEquals("must assume buffer ownership", fromBuf, fromView); + assertWithMessage("must assume buffer ownership").that(fromView).isEqualTo(fromBuf); int posBuf = buffer.position(); int posView = instance.buffer.position(); - assertEquals("must assume buffer ownership", posBuf, posView); + assertWithMessage("must assume buffer ownership").that(posView).isEqualTo(posBuf); } @Test @@ -56,10 +50,10 @@ public class ViewTest { ByteBuffer buffer = ByteBuffer.allocate(100); TestView instance = new TestView(buffer); View<TestView> result = instance.at(fileOffset); - assertSame("didn't return this", instance, result); + assertWithMessage("didn't return this").that(result).isSameAs(instance); long resultValue = instance.fileOffset(); - assertEquals("didn't return set value", fileOffset, resultValue); + assertWithMessage("didn't return set value").that(resultValue).isEqualTo(fileOffset); } @Test @@ -68,7 +62,7 @@ public class ViewTest { TestView instance = new TestView(buffer); long expResult = -1L; long result = instance.fileOffset(); - assertEquals("default file offset should be -1", expResult, result); + assertWithMessage("default file offset should be -1").that(result).isEqualTo(expResult); } @Test @@ -77,18 +71,18 @@ public class ViewTest { TestView instance = new TestView(buffer); int limit = instance.buffer.limit(); int pos = instance.buffer.position(); - assertEquals("initial limit", 100, limit); - assertEquals("initial position", 0, pos); + assertWithMessage("initial limit").that(limit).isEqualTo(100); + assertWithMessage("initial position").that(pos).isEqualTo(0); instance.putInt(1234); limit = instance.buffer.limit(); pos = instance.buffer.position(); - assertEquals("limit unchanged", 100, limit); - assertEquals("position advanced", 4, pos); + assertWithMessage("limit unchanged").that(limit).isEqualTo(100); + assertWithMessage("position advanced").that(pos).isEqualTo(4); instance.buffer.flip(); int finishedLimit = instance.buffer.limit(); int finishedPos = instance.buffer.position(); - assertEquals("must set limit to position", pos, finishedLimit); - assertEquals("must set position to 0", 0, finishedPos); + assertWithMessage("must set limit to position").that(finishedLimit).isEqualTo(pos); + assertWithMessage("must set position to 0").that(finishedPos).isEqualTo(0); } @Test @@ -101,9 +95,9 @@ public class ViewTest { instance.buffer.rewind(); int result = file.write(instance.buffer); file.close(); - assertEquals("incorrect number of bytes written", expResult, result); + assertWithMessage("incorrect number of bytes written").that(result).isEqualTo(expResult); byte[] bytesWritten = fileSystem.toByteArray("hello"); - Assert.assertArrayEquals("incorrect bytes written", bytes, bytesWritten); + assertWithMessage("incorrect bytes written").that(bytesWritten).isEqualTo(bytes); } @Test @@ -115,7 +109,7 @@ public class ViewTest { TestView instance = new TestView(buffer); byte[] expResult = "lo wo".getBytes(UTF_8); byte[] result = instance.getBytes(off, len); - assertArrayEquals("incorrect bytes returned", expResult, result); + assertWithMessage("incorrect bytes returned").that(result).isEqualTo(expResult); try { instance.getBytes(bytes.length - len + 1, len); fail("expected Exception"); @@ -139,7 +133,7 @@ public class ViewTest { TestView instance = new TestView(buffer); String expResult = "world"; String result = instance.getString(off, len); - assertEquals("didn't return this", expResult, result); + assertWithMessage("didn't return this").that(result).isEqualTo(expResult); try { instance.getString(off + 1, len); fail("expected Exception"); @@ -160,7 +154,7 @@ public class ViewTest { TestView instance = new TestView(ByteBuffer.wrap(bytes)); int expValue = 0x08070605; int value = instance.getInt(4); - assertEquals("Byte order incorrect", expValue, value); + assertWithMessage("Byte order incorrect").that(value).isEqualTo(expValue); } static class TestView extends View<TestView> { diff --git a/src/test/java/com/google/devtools/build/android/ziputils/ZipInTest.java b/src/test/java/com/google/devtools/build/android/ziputils/ZipInTest.java index c29fc864c9..17b6108387 100644 --- a/src/test/java/com/google/devtools/build/android/ziputils/ZipInTest.java +++ b/src/test/java/com/google/devtools/build/android/ziputils/ZipInTest.java @@ -13,6 +13,8 @@ // limitations under the License. package com.google.devtools.build.android.ziputils; +import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENHOW; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENLEN; import static com.google.devtools.build.android.ziputils.DirectoryEntry.CENOFF; @@ -23,10 +25,6 @@ import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.E import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.ENDSUB; import static com.google.devtools.build.android.ziputils.EndOfCentralDirectory.ENDTOT; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import com.google.devtools.build.android.ziputils.ZipIn.ZipEntry; @@ -87,7 +85,7 @@ public class ZipInTest { fileSystem.addFile(filename, bytes); zipIn = newZipIn(filename); result = zipIn.endOfCentralDirectory(); - assertNotNull(subcase + "found", result); + assertWithMessage(subcase + "found").that(result).isNotNull(); subcase = " EOCD not there at all, "; bytes = new byte[]{ @@ -108,7 +106,9 @@ public class ZipInTest { zipIn.endOfCentralDirectory(); fail(subcase + "expected IllegalStateException"); } catch (Exception ex) { - assertSame(subcase + "caught exception", IllegalStateException.class, ex.getClass()); + assertWithMessage(subcase + "caught exception") + .that(ex.getClass()) + .isSameAs(IllegalStateException.class); } // If we can't read it, it's not there @@ -131,7 +131,9 @@ public class ZipInTest { zipIn.endOfCentralDirectory(); fail(subcase + "expected IndexOutOfBoundsException"); } catch (Exception ex) { - assertSame(subcase + "caught exception", IndexOutOfBoundsException.class, ex.getClass()); + assertWithMessage(subcase + "caught exception") + .that(ex.getClass()) + .isSameAs(IndexOutOfBoundsException.class); } // Current implementation doesn't know to scan past a bad EOCD record. @@ -155,7 +157,9 @@ public class ZipInTest { zipIn.endOfCentralDirectory(); fail(subcase + "expected IndexOutOfBoundsException"); } catch (Exception ex) { - assertSame(subcase + "caught exception", IndexOutOfBoundsException.class, ex.getClass()); + assertWithMessage(subcase + "caught exception") + .that(ex.getClass()) + .isSameAs(IndexOutOfBoundsException.class); } // Minimal format checking here, assuming the EndOfDirectoryTest class @@ -176,7 +180,9 @@ public class ZipInTest { zipIn.endOfCentralDirectory(); fail(subcase + "expected IllegalArgumentException"); } catch (Exception ex) { - assertSame(subcase + "caught exception", IllegalArgumentException.class, ex.getClass()); + assertWithMessage(subcase + "caught exception") + .that(ex.getClass()) + .isSameAs(IllegalArgumentException.class); } subcase = " EOCD no comment, "; @@ -190,9 +196,11 @@ public class ZipInTest { fileSystem.addFile(filename, bytes); zipIn = newZipIn(filename); result = zipIn.endOfCentralDirectory(); - assertNotNull(subcase + "found", result); - assertEquals(subcase + "comment", "", result.getComment()); - assertEquals(subcase + "marker", ZipInputStream.ENDSIG, (int) result.get(ENDSIG)); + assertWithMessage(subcase + "found").that(result).isNotNull(); + assertWithMessage(subcase + "comment").that(result.getComment()).isEqualTo(""); + assertWithMessage(subcase + "marker") + .that((int) result.get(ENDSIG)) + .isEqualTo(ZipInputStream.ENDSIG); subcase = " EOCD comment, "; bytes = new byte[100]; @@ -202,14 +210,17 @@ public class ZipInTest { offset = bytes.length - ZipInputStream.ENDHDR - commentLen; buffer.position(offset); EndOfCentralDirectory.view(buffer, comment); - assertEquals(subcase + "setup", comment, - new String(bytes, bytes.length - commentLen, commentLen, UTF_8)); + assertWithMessage(subcase + "setup") + .that(new String(bytes, bytes.length - commentLen, commentLen, UTF_8)) + .isEqualTo(comment); fileSystem.addFile(filename, bytes); zipIn = newZipIn(filename); result = zipIn.endOfCentralDirectory(); - assertNotNull(subcase + "found", result); - assertEquals(subcase + "comment", comment, result.getComment()); - assertEquals(subcase + "marker", ZipInputStream.ENDSIG, (int) result.get(ENDSIG)); + assertWithMessage(subcase + "found").that(result).isNotNull(); + assertWithMessage(subcase + "comment").that(result.getComment()).isEqualTo(comment); + assertWithMessage(subcase + "marker") + .that((int) result.get(ENDSIG)) + .isEqualTo(ZipInputStream.ENDSIG); subcase = " EOCD extra data, "; bytes = new byte[100]; @@ -222,9 +233,11 @@ public class ZipInTest { fileSystem.addFile(filename, bytes); zipIn = newZipIn(filename); result = zipIn.endOfCentralDirectory(); - assertNotNull(subcase + "found", result); - assertEquals(subcase + "comment", "", result.getComment()); - assertEquals(subcase + "marker", ZipInputStream.ENDSIG, (int) result.get(ENDSIG)); + assertWithMessage(subcase + "found").that(result).isNotNull(); + assertWithMessage(subcase + "comment").that(result.getComment()).isEqualTo(""); + assertWithMessage(subcase + "marker") + .that((int) result.get(ENDSIG)) + .isEqualTo(ZipInputStream.ENDSIG); } /** @@ -274,11 +287,13 @@ public class ZipInTest { fileSystem.addFile(filename, bytes); zipIn = newZipIn(filename); CentralDirectory result = zipIn.centralDirectory(); - assertNotNull(subcase + "found", result); + assertWithMessage(subcase + "found").that(result).isNotNull(); List<DirectoryEntry> list = result.list(); - assertEquals(subcase + "size", count, list.size()); + assertWithMessage(subcase + "size").that(list.size()).isEqualTo(count); for (int i = 0; i < list.size(); i++) { - assertEquals(subcase + "offset check[" + i + "]", i, list.get(i).get(CENOFF)); + assertWithMessage(subcase + "offset check[" + i + "]") + .that(list.get(i).get(CENOFF)) + .isEqualTo(i); } } @@ -297,18 +312,21 @@ public class ZipInTest { builder.create(filename); final ZipIn zipIn = newZipIn(filename); - zipIn.scanEntries(new EntryHandler() { - int count = 0; - @Override - public void handle(ZipIn in, LocalFileHeader header, DirectoryEntry dirEntry, - ByteBuffer data) throws IOException { - assertSame(zipIn, in); - String filename = "pkg/f" + count + ".class"; - assertEquals(filename, header.getFilename()); - assertEquals(filename, dirEntry.getFilename()); - count++; - } - }); + zipIn.scanEntries( + new EntryHandler() { + int count = 0; + + @Override + public void handle( + ZipIn in, LocalFileHeader header, DirectoryEntry dirEntry, ByteBuffer data) + throws IOException { + assertThat(in).isSameAs(zipIn); + String filename = "pkg/f" + count + ".class"; + assertThat(header.getFilename()).isEqualTo(filename); + assertThat(dirEntry.getFilename()).isEqualTo(filename); + count++; + } + }); } /** @@ -332,12 +350,12 @@ public class ZipInTest { header = zipIn.nextHeaderFrom(offset); String name = "pkg/f" + count + ".class"; if (header != null) { - assertEquals(name, header.getFilename()); + assertThat(header.getFilename()).isEqualTo(name); count++; offset = (int) header.fileOffset() + 4; } } while(header != null); - assertEquals(ENTRY_COUNT, count); + assertThat(count).isEqualTo(ENTRY_COUNT); } /** @@ -360,12 +378,12 @@ public class ZipInTest { LocalFileHeader header = zipIn.nextHeaderFrom(null); for (DirectoryEntry dirEntry : list) { name = "pkg/f" + count + ".class"; - assertEquals(name, dirEntry.getFilename()); - assertEquals(name, header.getFilename()); + assertThat(dirEntry.getFilename()).isEqualTo(name); + assertThat(header.getFilename()).isEqualTo(name); header = zipIn.nextHeaderFrom(dirEntry); count++; } - assertNull(header); + assertThat(header).isNull(); } /** @@ -389,8 +407,8 @@ public class ZipInTest { for (DirectoryEntry dirEntry : list) { name = "pkg/f" + count + ".class"; header = zipIn.localHeaderFor(dirEntry); - assertEquals(name, dirEntry.getFilename()); - assertEquals(name, header.getFilename()); + assertThat(dirEntry.getFilename()).isEqualTo(name); + assertThat(header.getFilename()).isEqualTo(name); count++; } } @@ -416,8 +434,8 @@ public class ZipInTest { for (DirectoryEntry dirEntry : list) { name = "pkg/f" + count + ".class"; header = zipIn.localHeaderAt(dirEntry.get(CENOFF)); - assertEquals(name, dirEntry.getFilename()); - assertEquals(name, header.getFilename()); + assertThat(dirEntry.getFilename()).isEqualTo(name); + assertThat(header.getFilename()).isEqualTo(name); count++; } } @@ -443,15 +461,15 @@ public class ZipInTest { zipEntry = zipIn.nextFrom(offset); String name = "pkg/f" + count + ".class"; if (zipEntry.getCode() != ZipEntry.Status.ENTRY_NOT_FOUND) { - assertNotNull(zipEntry.getHeader()); - assertNotNull(zipEntry.getDirEntry()); - assertEquals(name, zipEntry.getHeader().getFilename()); - assertEquals(name, zipEntry.getDirEntry().getFilename()); + assertThat(zipEntry.getHeader()).isNotNull(); + assertThat(zipEntry.getDirEntry()).isNotNull(); + assertThat(zipEntry.getHeader().getFilename()).isEqualTo(name); + assertThat(zipEntry.getDirEntry().getFilename()).isEqualTo(name); count++; offset = (int) zipEntry.getHeader().fileOffset() + 4; } } while(zipEntry.getCode() != ZipEntry.Status.ENTRY_NOT_FOUND); - assertEquals(ENTRY_COUNT, count); + assertThat(count).isEqualTo(ENTRY_COUNT); } /** @@ -477,14 +495,14 @@ public class ZipInTest { break; } name = "pkg/f" + count + ".class"; - assertNotNull(zipEntry.getHeader()); - assertNotNull(zipEntry.getDirEntry()); - assertEquals(name, zipEntry.getHeader().getFilename()); - assertEquals(name, zipEntry.getDirEntry().getFilename()); + assertThat(zipEntry.getHeader()).isNotNull(); + assertThat(zipEntry.getDirEntry()).isNotNull(); + assertThat(zipEntry.getHeader().getFilename()).isEqualTo(name); + assertThat(zipEntry.getDirEntry().getFilename()).isEqualTo(name); zipEntry = zipIn.nextFrom(dirEntry); count++; } - assertEquals(ENTRY_COUNT, count); + assertThat(count).isEqualTo(ENTRY_COUNT); } /** @@ -508,13 +526,13 @@ public class ZipInTest { for (DirectoryEntry dirEntry : list) { zipEntry = zipIn.entryAt(dirEntry.get(CENOFF)); name = "pkg/f" + count + ".class"; - assertNotNull(zipEntry.getHeader()); - assertNotNull(zipEntry.getDirEntry()); - assertEquals(name, zipEntry.getHeader().getFilename()); - assertEquals(name, zipEntry.getDirEntry().getFilename()); + assertThat(zipEntry.getHeader()).isNotNull(); + assertThat(zipEntry.getDirEntry()).isNotNull(); + assertThat(zipEntry.getHeader().getFilename()).isEqualTo(name); + assertThat(zipEntry.getDirEntry().getFilename()).isEqualTo(name); count++; } - assertEquals(ENTRY_COUNT, count); + assertThat(count).isEqualTo(ENTRY_COUNT); } /** @@ -539,16 +557,16 @@ public class ZipInTest { String name = "pkg/f" + count + ".class"; if (header != null) { ZipEntry zipEntry = zipIn.entryWith(header); - assertNotNull(zipEntry.getDirEntry()); - assertSame(header, zipEntry.getHeader()); - assertEquals(name, zipEntry.getHeader().getFilename()); - assertEquals(name, zipEntry.getDirEntry().getFilename()); - assertEquals(name, header.getFilename()); + assertThat(zipEntry.getDirEntry()).isNotNull(); + assertThat(zipEntry.getHeader()).isSameAs(header); + assertThat(zipEntry.getHeader().getFilename()).isEqualTo(name); + assertThat(zipEntry.getDirEntry().getFilename()).isEqualTo(name); + assertThat(header.getFilename()).isEqualTo(name); count++; offset = (int) header.fileOffset() + 4; } } while(header != null); - assertEquals(ENTRY_COUNT, count); + assertThat(count).isEqualTo(ENTRY_COUNT); } private ZipIn newZipIn(String filename) throws IOException { diff --git a/src/test/java/com/google/devtools/build/lib/analysis/AnalysisUtilsTest.java b/src/test/java/com/google/devtools/build/lib/analysis/AnalysisUtilsTest.java index 821140001f..4c6f2e4e58 100644 --- a/src/test/java/com/google/devtools/build/lib/analysis/AnalysisUtilsTest.java +++ b/src/test/java/com/google/devtools/build/lib/analysis/AnalysisUtilsTest.java @@ -19,7 +19,6 @@ import static com.google.devtools.build.lib.analysis.AnalysisUtils.checkProvider import static org.junit.Assert.fail; import com.google.auto.value.AutoValue; - import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @@ -38,7 +37,7 @@ public class AnalysisUtilsTest { checkProvider(AutoValue_AnalysisUtilsTest_AutoValuedClass.class); fail("Expected IllegalArgumentException, but nothing was thrown."); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).contains("generated by @AutoValue"); + assertThat(e).hasMessageThat().contains("generated by @AutoValue"); } } diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnectorMultiplexerTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnectorMultiplexerTest.java index dedf316868..1928144add 100644 --- a/src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnectorMultiplexerTest.java +++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/HttpConnectorMultiplexerTest.java @@ -157,7 +157,7 @@ public class HttpConnectorMultiplexerTest { multiplexer.connect(asList(URL1, URL2, URL3), ""); fail("Expected IOException"); } catch (IOException e) { - assertThat(e.getMessage()).contains("All mirrors are down"); + assertThat(e).hasMessageThat().contains("All mirrors are down"); } verify(connector, times(3)).connect(any(URL.class), any(ImmutableMap.class)); verify(sleeper, times(2)).sleepMillis(anyLong()); diff --git a/src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/ProxyHelperTest.java b/src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/ProxyHelperTest.java index 8da2e6e0ef..5aa7d107cf 100644 --- a/src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/ProxyHelperTest.java +++ b/src/test/java/com/google/devtools/build/lib/bazel/repository/downloader/ProxyHelperTest.java @@ -15,7 +15,6 @@ package com.google.devtools.build.lib.bazel.repository.downloader; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableMap; @@ -65,40 +64,40 @@ public class ProxyHelperTest { public void testNoProxy() throws Exception { // Empty address. Proxy proxy = ProxyHelper.createProxy(null); - assertEquals(Proxy.NO_PROXY, proxy); + assertThat(proxy).isEqualTo(Proxy.NO_PROXY); proxy = ProxyHelper.createProxy(""); - assertEquals(Proxy.NO_PROXY, proxy); + assertThat(proxy).isEqualTo(Proxy.NO_PROXY); Map<String, String> env = ImmutableMap.of(); ProxyHelper helper = new ProxyHelper(env); proxy = helper.createProxyIfNeeded(new URL("https://www.something.com")); - assertEquals(Proxy.NO_PROXY, proxy); + assertThat(proxy).isEqualTo(Proxy.NO_PROXY); } @Test public void testProxyDefaultPort() throws Exception { Proxy proxy = ProxyHelper.createProxy("http://my.example.com"); - assertEquals(Proxy.Type.HTTP, proxy.type()); + assertThat(proxy.type()).isEqualTo(Proxy.Type.HTTP); assertThat(proxy.toString()).endsWith(":80"); - assertEquals("my.example.com", System.getProperty("http.proxyHost")); - assertEquals("80", System.getProperty("http.proxyPort")); + assertThat(System.getProperty("http.proxyHost")).isEqualTo("my.example.com"); + assertThat(System.getProperty("http.proxyPort")).isEqualTo("80"); proxy = ProxyHelper.createProxy("https://my.example.com"); assertThat(proxy.toString()).endsWith(":443"); - assertEquals("my.example.com", System.getProperty("https.proxyHost")); - assertEquals("443", System.getProperty("https.proxyPort")); + assertThat(System.getProperty("https.proxyHost")).isEqualTo("my.example.com"); + assertThat(System.getProperty("https.proxyPort")).isEqualTo("443"); } @Test public void testProxyExplicitPort() throws Exception { Proxy proxy = ProxyHelper.createProxy("http://my.example.com:12345"); assertThat(proxy.toString()).endsWith(":12345"); - assertEquals("my.example.com", System.getProperty("http.proxyHost")); - assertEquals("12345", System.getProperty("http.proxyPort")); + assertThat(System.getProperty("http.proxyHost")).isEqualTo("my.example.com"); + assertThat(System.getProperty("http.proxyPort")).isEqualTo("12345"); proxy = ProxyHelper.createProxy("https://my.example.com:12345"); assertThat(proxy.toString()).endsWith(":12345"); - assertEquals("my.example.com", System.getProperty("https.proxyHost")); - assertEquals("12345", System.getProperty("https.proxyPort")); + assertThat(System.getProperty("https.proxyHost")).isEqualTo("my.example.com"); + assertThat(System.getProperty("https.proxyPort")).isEqualTo("12345"); } @Test @@ -107,7 +106,7 @@ public class ProxyHelperTest { ProxyHelper.createProxy("my.example.com"); fail("Expected protocol error"); } catch (IOException e) { - assertThat(e.getMessage()).contains("Proxy address my.example.com is not a valid URL"); + assertThat(e).hasMessageThat().contains("Proxy address my.example.com is not a valid URL"); } } @@ -117,7 +116,9 @@ public class ProxyHelperTest { ProxyHelper.createProxy("my.example.com:12345"); fail("Expected protocol error"); } catch (IOException e) { - assertThat(e.getMessage()).contains("Proxy address my.example.com:12345 is not a valid URL"); + assertThat(e) + .hasMessageThat() + .contains("Proxy address my.example.com:12345 is not a valid URL"); } } @@ -127,7 +128,8 @@ public class ProxyHelperTest { ProxyHelper.createProxy("http://my.example.com:foo"); fail("Should have thrown an error for invalid port"); } catch (IOException e) { - assertThat(e.getMessage()) + assertThat(e) + .hasMessageThat() .contains("Proxy address http://my.example.com:foo is not a valid URL"); } } @@ -135,30 +137,30 @@ public class ProxyHelperTest { @Test public void testProxyAuth() throws Exception { Proxy proxy = ProxyHelper.createProxy("http://foo:barbaz@my.example.com"); - assertEquals(Proxy.Type.HTTP, proxy.type()); + assertThat(proxy.type()).isEqualTo(Proxy.Type.HTTP); assertThat(proxy.toString()).endsWith(":80"); - assertEquals("my.example.com", System.getProperty("http.proxyHost")); - assertEquals("80", System.getProperty("http.proxyPort")); - assertEquals("foo", System.getProperty("http.proxyUser")); - assertEquals("barbaz", System.getProperty("http.proxyPassword")); + assertThat(System.getProperty("http.proxyHost")).isEqualTo("my.example.com"); + assertThat(System.getProperty("http.proxyPort")).isEqualTo("80"); + assertThat(System.getProperty("http.proxyUser")).isEqualTo("foo"); + assertThat(System.getProperty("http.proxyPassword")).isEqualTo("barbaz"); proxy = ProxyHelper.createProxy("https://biz:bat@my.example.com"); assertThat(proxy.toString()).endsWith(":443"); - assertEquals("my.example.com", System.getProperty("https.proxyHost")); - assertEquals("443", System.getProperty("https.proxyPort")); - assertEquals("biz", System.getProperty("https.proxyUser")); - assertEquals("bat", System.getProperty("https.proxyPassword")); + assertThat(System.getProperty("https.proxyHost")).isEqualTo("my.example.com"); + assertThat(System.getProperty("https.proxyPort")).isEqualTo("443"); + assertThat(System.getProperty("https.proxyUser")).isEqualTo("biz"); + assertThat(System.getProperty("https.proxyPassword")).isEqualTo("bat"); } @Test public void testEncodedProxyAuth() throws Exception { Proxy proxy = ProxyHelper.createProxy("http://foo:b%40rb%40z@my.example.com"); - assertEquals(Proxy.Type.HTTP, proxy.type()); + assertThat(proxy.type()).isEqualTo(Proxy.Type.HTTP); assertThat(proxy.toString()).endsWith(":80"); - assertEquals("my.example.com", System.getProperty("http.proxyHost")); - assertEquals("80", System.getProperty("http.proxyPort")); - assertEquals("foo", System.getProperty("http.proxyUser")); - assertEquals("b@rb@z", System.getProperty("http.proxyPassword")); + assertThat(System.getProperty("http.proxyHost")).isEqualTo("my.example.com"); + assertThat(System.getProperty("http.proxyPort")).isEqualTo("80"); + assertThat(System.getProperty("http.proxyUser")).isEqualTo("foo"); + assertThat(System.getProperty("http.proxyPassword")).isEqualTo("b@rb@z"); } @Test @@ -167,27 +169,27 @@ public class ProxyHelperTest { ProxyHelper.createProxy("http://foo@my.example.com"); fail("Should have thrown an error for invalid auth"); } catch (IOException e) { - assertThat(e.getMessage()).contains("No password given for proxy"); + assertThat(e).hasMessageThat().contains("No password given for proxy"); } } @Test public void testNoProxyAuth() throws Exception { Proxy proxy = ProxyHelper.createProxy("http://localhost:3128/"); - assertEquals(Proxy.Type.HTTP, proxy.type()); + assertThat(proxy.type()).isEqualTo(Proxy.Type.HTTP); assertThat(proxy.toString()).endsWith(":3128"); - assertEquals("localhost", System.getProperty("http.proxyHost")); - assertEquals("3128", System.getProperty("http.proxyPort")); + assertThat(System.getProperty("http.proxyHost")).isEqualTo("localhost"); + assertThat(System.getProperty("http.proxyPort")).isEqualTo("3128"); } @Test public void testTrailingSlash() throws Exception { Proxy proxy = ProxyHelper.createProxy("http://foo:bar@example.com:8000/"); - assertEquals(Proxy.Type.HTTP, proxy.type()); + assertThat(proxy.type()).isEqualTo(Proxy.Type.HTTP); assertThat(proxy.toString()).endsWith(":8000"); - assertEquals("example.com", System.getProperty("http.proxyHost")); - assertEquals("8000", System.getProperty("http.proxyPort")); - assertEquals("foo", System.getProperty("http.proxyUser")); - assertEquals("bar", System.getProperty("http.proxyPassword")); + assertThat(System.getProperty("http.proxyHost")).isEqualTo("example.com"); + assertThat(System.getProperty("http.proxyPort")).isEqualTo("8000"); + assertThat(System.getProperty("http.proxyUser")).isEqualTo("foo"); + assertThat(System.getProperty("http.proxyPassword")).isEqualTo("bar"); } } diff --git a/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java b/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java index 8f99efca83..c7ef2181a7 100644 --- a/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java +++ b/src/test/java/com/google/devtools/build/lib/buildeventstream/transports/BinaryFormatFileTransportTest.java @@ -15,8 +15,6 @@ package com.google.devtools.build.lib.buildeventstream.transports; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import com.google.devtools.build.lib.buildeventstream.ArtifactGroupNamer; @@ -103,7 +101,7 @@ public class BinaryFormatFileTransportTest { // Get a file that doesn't exist by creating a new file and immediately deleting it. File output = tmp.newFile(); String path = output.getAbsolutePath(); - assertTrue(output.delete()); + assertThat(output.delete()).isTrue(); BuildEventStreamProtos.BuildEvent started = BuildEventStreamProtos.BuildEvent.newBuilder() @@ -135,7 +133,7 @@ public class BinaryFormatFileTransportTest { // Close the file. transport.ch.close(); - assertFalse(transport.ch.isOpen()); + assertThat(transport.ch.isOpen()).isFalse(); // This should not throw an exception. transport.sendBuildEvent(buildEvent, artifactGroupNamer); @@ -166,7 +164,7 @@ public class BinaryFormatFileTransportTest { transport.sendBuildEvent(buildEvent, artifactGroupNamer); closeFuture.get(); - assertFalse(transport.ch.isOpen()); + assertThat(transport.ch.isOpen()).isFalse(); // There should have only been one write. try (InputStream in = new FileInputStream(output)) { diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/BuildFileModificationTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/BuildFileModificationTest.java index 1633111cea..60c056f42b 100644 --- a/src/test/java/com/google/devtools/build/lib/pkgcache/BuildFileModificationTest.java +++ b/src/test/java/com/google/devtools/build/lib/pkgcache/BuildFileModificationTest.java @@ -13,11 +13,7 @@ // limitations under the License. package com.google.devtools.build.lib.pkgcache; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableList; @@ -145,7 +141,7 @@ public class BuildFileModificationTest extends FoundationTestCase { Path build = scratch.file( "a/BUILD", "cc_library(name='a', feet='stinky')".getBytes(StandardCharsets.ISO_8859_1)); Package a1 = getPackage("a"); - assertTrue(a1.containsErrors()); + assertThat(a1.containsErrors()).isTrue(); assertContainsEvent("//a:a: no such attribute 'feet'"); eventCollector.clear(); // writeContent updates mtime and ctime. Note that we keep the content length exactly the same. @@ -155,8 +151,8 @@ public class BuildFileModificationTest extends FoundationTestCase { invalidatePackages(); Package a2 = getPackage("a"); - assertNotSame(a1, a2); - assertFalse(a2.containsErrors()); + assertThat(a2).isNotSameAs(a1); + assertThat(a2.containsErrors()).isFalse(); assertNoEvents(); } @@ -170,13 +166,14 @@ public class BuildFileModificationTest extends FoundationTestCase { clock.advanceMillis(1); FileSystemUtils.writeContent( path, "cc_library(name = 'bar')\n".getBytes(StandardCharsets.ISO_8859_1)); - assertSame(oldPkg, getPackage("pkg")); // Change only becomes visible after invalidatePackages. + assertThat(getPackage("pkg")) + .isSameAs(oldPkg); // Change only becomes visible after invalidatePackages. invalidatePackages(); Package newPkg = getPackage("pkg"); - assertNotSame(oldPkg, newPkg); - assertNotNull(newPkg.getTarget("bar")); + assertThat(newPkg).isNotSameAs(oldPkg); + assertThat(newPkg.getTarget("bar")).isNotNull(); } @Test @@ -193,7 +190,7 @@ public class BuildFileModificationTest extends FoundationTestCase { invalidatePackages(); Package a2 = getPackage("a"); - assertNotSame(a1, a2); + assertThat(a2).isNotSameAs(a1); assertNoEvents(); } @@ -206,11 +203,11 @@ public class BuildFileModificationTest extends FoundationTestCase { // Change ctime to 1. clock.advanceMillis(1); path.setLastModifiedTime(1001); - assertSame(oldPkg, getPackage("pkg")); // change not yet visible + assertThat(getPackage("pkg")).isSameAs(oldPkg); // change not yet visible invalidatePackages(); Package newPkg = getPackage("pkg"); - assertNotSame(oldPkg, newPkg); + assertThat(newPkg).isNotSameAs(oldPkg); } } diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/CompileOneDependencyTransformerTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/CompileOneDependencyTransformerTest.java index 7ac30babb6..d421e9229c 100644 --- a/src/test/java/com/google/devtools/build/lib/pkgcache/CompileOneDependencyTransformerTest.java +++ b/src/test/java/com/google/devtools/build/lib/pkgcache/CompileOneDependencyTransformerTest.java @@ -14,7 +14,6 @@ package com.google.devtools.build.lib.pkgcache; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import com.google.devtools.build.lib.cmdline.Label; @@ -106,7 +105,7 @@ public class CompileOneDependencyTransformerTest extends PackageLoadingTestCase } private static Set<Target> getFailFast(ResolvedTargets<Target> result) { - assertFalse(result.hasError()); + assertThat(result.hasError()).isFalse(); return result.getTargets(); } diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/IOExceptionsTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/IOExceptionsTest.java index 6472f01279..3cbcf24a36 100644 --- a/src/test/java/com/google/devtools/build/lib/pkgcache/IOExceptionsTest.java +++ b/src/test/java/com/google/devtools/build/lib/pkgcache/IOExceptionsTest.java @@ -13,8 +13,7 @@ // limitations under the License. package com.google.devtools.build.lib.pkgcache; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static com.google.common.truth.Truth.assertThat; import com.google.common.base.Function; import com.google.devtools.build.lib.cmdline.Label; @@ -105,7 +104,7 @@ public class IOExceptionsTest extends PackageLoadingTestCase { return null; } }; - assertFalse(visitTransitively(Label.parseAbsolute("//pkg:x"))); + assertThat(visitTransitively(Label.parseAbsolute("//pkg:x"))).isFalse(); scratch.overwriteFile("pkg/BUILD", "# another comment to force reload", "sh_library(name = 'x')"); @@ -113,7 +112,7 @@ public class IOExceptionsTest extends PackageLoadingTestCase { syncPackages(); eventCollector.clear(); reporter.addHandler(failFastHandler); - assertTrue(visitTransitively(Label.parseAbsolute("//pkg:x"))); + assertThat(visitTransitively(Label.parseAbsolute("//pkg:x"))).isTrue(); assertNoEvents(); } @@ -134,7 +133,7 @@ public class IOExceptionsTest extends PackageLoadingTestCase { return null; } }; - assertFalse(visitTransitively(Label.parseAbsolute("//top:top"))); + assertThat(visitTransitively(Label.parseAbsolute("//top:top"))).isFalse(); assertContainsEvent("no such package 'pkg'"); // The traditional label visitor does not propagate the original IOException message. // assertContainsEvent("custom crash"); @@ -148,7 +147,7 @@ public class IOExceptionsTest extends PackageLoadingTestCase { syncPackages(); eventCollector.clear(); reporter.addHandler(failFastHandler); - assertTrue(visitTransitively(Label.parseAbsolute("//top:top"))); + assertThat(visitTransitively(Label.parseAbsolute("//top:top"))).isTrue(); assertNoEvents(); } @@ -167,6 +166,6 @@ public class IOExceptionsTest extends PackageLoadingTestCase { return null; } }; - assertFalse(visitTransitively(Label.parseAbsolute("//top/pkg:x"))); + assertThat(visitTransitively(Label.parseAbsolute("//top/pkg:x"))).isFalse(); } } diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/PackageCacheTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/PackageCacheTest.java index 3b7908e74d..aad829ecd1 100644 --- a/src/test/java/com/google/devtools/build/lib/pkgcache/PackageCacheTest.java +++ b/src/test/java/com/google/devtools/build/lib/pkgcache/PackageCacheTest.java @@ -14,11 +14,6 @@ package com.google.devtools.build.lib.pkgcache; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.base.Predicates; @@ -192,7 +187,7 @@ public class PackageCacheTest extends FoundationTestCase { getPackage(packageName); fail(); } catch (NoSuchPackageException e) { - assertThat(e.getMessage()).contains(expectedMessage); + assertThat(e).hasMessageThat().contains(expectedMessage); } } @@ -200,11 +195,10 @@ public class PackageCacheTest extends FoundationTestCase { public void testGetPackage() throws Exception { createPkg1(); Package pkg1 = getPackage("pkg1"); - assertEquals("pkg1", pkg1.getName()); - assertEquals("/workspace/pkg1/BUILD", - pkg1.getFilename().toString()); - assertSame(pkg1, getPackageManager().getPackage(reporter, - PackageIdentifier.createInMainRepo("pkg1"))); + assertThat(pkg1.getName()).isEqualTo("pkg1"); + assertThat(pkg1.getFilename().toString()).isEqualTo("/workspace/pkg1/BUILD"); + assertThat(getPackageManager().getPackage(reporter, PackageIdentifier.createInMainRepo("pkg1"))) + .isSameAs(pkg1); } @Test @@ -234,7 +228,7 @@ public class PackageCacheTest extends FoundationTestCase { createPkg1(); Label label = Label.parseAbsolute("//pkg1:foo"); Target target = getTarget(label); - assertEquals(label, target.getLabel()); + assertThat(target.getLabel()).isEqualTo(label); } @Test @@ -278,7 +272,7 @@ public class PackageCacheTest extends FoundationTestCase { // Found: Package missing = getPackage("missing"); - assertEquals("missing", missing.getName()); + assertThat(missing.getName()).isEqualTo("missing"); } /** @@ -305,7 +299,7 @@ public class PackageCacheTest extends FoundationTestCase { getPackage("broken"); fail(); } catch (BuildFileContainsErrorsException e) { - assertThat(e.getMessage()).contains("/workspace/broken/BUILD (Permission denied)"); + assertThat(e).hasMessageThat().contains("/workspace/broken/BUILD (Permission denied)"); } eventCollector.clear(); @@ -316,7 +310,7 @@ public class PackageCacheTest extends FoundationTestCase { invalidatePackages(); // resets cache of failures Package broken = getPackage("broken"); - assertEquals("broken", broken.getName()); + assertThat(broken.getName()).isEqualTo("broken"); assertNoEvents(); } @@ -329,17 +323,17 @@ public class PackageCacheTest extends FoundationTestCase { setOptions("--package_path=/workspace:/otherroot"); Package oldPkg = getPackage("pkg"); - assertSame(oldPkg, getPackage("pkg")); // change not yet visible - assertEquals(buildFile1, oldPkg.getFilename()); - assertEquals(rootDirectory, oldPkg.getSourceRoot()); + assertThat(getPackage("pkg")).isSameAs(oldPkg); // change not yet visible + assertThat(oldPkg.getFilename()).isEqualTo(buildFile1); + assertThat(oldPkg.getSourceRoot()).isEqualTo(rootDirectory); buildFile1.delete(); invalidatePackages(); Package newPkg = getPackage("pkg"); - assertNotSame(oldPkg, newPkg); - assertEquals(buildFile2, newPkg.getFilename()); - assertEquals(scratch.dir("/otherroot"), newPkg.getSourceRoot()); + assertThat(newPkg).isNotSameAs(oldPkg); + assertThat(newPkg.getFilename()).isEqualTo(buildFile2); + assertThat(newPkg.getSourceRoot()).isEqualTo(scratch.dir("/otherroot")); // TODO(bazel-team): (2009) test BUILD file moves in the other direction too. } @@ -412,7 +406,7 @@ public class PackageCacheTest extends FoundationTestCase { private void assertPackageLoadingFails(String pkgName, String expectedError) throws Exception { Package pkg = getPackage(pkgName); - assertTrue(pkg.containsErrors()); + assertThat(pkg.containsErrors()).isTrue(); assertContainsEvent(expectedError); } @@ -425,7 +419,7 @@ public class PackageCacheTest extends FoundationTestCase { reporter.removeHandler(failFastHandler); List<Event> events = getPackage("e").getEvents(); assertThat(events).hasSize(1); - assertEquals(2, events.get(0).getLocation().getStartLineAndColumn().getLine()); + assertThat(events.get(0).getLocation().getStartLineAndColumn().getLine()).isEqualTo(2); } /** Static tests (i.e. no changes to filesystem, nor calls to sync). */ @@ -501,8 +495,7 @@ public class PackageCacheTest extends FoundationTestCase { // root. It's as if we've merged c and c/d in the first root. // c/d is still a subpackage--found in the second root: - assertEquals(rootDir2.getRelative("c/d/BUILD"), - getPackage("c/d").getFilename()); + assertThat(getPackage("c/d").getFilename()).isEqualTo(rootDir2.getRelative("c/d/BUILD")); // Subpackage labels are still valid... assertLabelValidity(true, "//c/d:foo.txt"); @@ -512,14 +505,14 @@ public class PackageCacheTest extends FoundationTestCase { "Label '//c:d/x' crosses boundary of subpackage 'c/d' (have you deleted c/d/BUILD? " + "If so, use the --deleted_packages=c/d option)"); - assertTrue(getPackageManager().isPackage( - reporter, PackageIdentifier.createInMainRepo("c/d"))); + assertThat(getPackageManager().isPackage(reporter, PackageIdentifier.createInMainRepo("c/d"))) + .isTrue(); setOptions("--deleted_packages=c/d"); invalidatePackages(); - assertFalse(getPackageManager().isPackage( - reporter, PackageIdentifier.createInMainRepo("c/d"))); + assertThat(getPackageManager().isPackage(reporter, PackageIdentifier.createInMainRepo("c/d"))) + .isFalse(); // c/d is no longer a subpackage--even though there's a BUILD file in the // second root: @@ -557,6 +550,6 @@ public class PackageCacheTest extends FoundationTestCase { "outs = ['y/z.h'],", "cmd = '')"); Package p = getPackage("x"); - assertTrue(p.containsErrors()); + assertThat(p.containsErrors()).isTrue(); } } diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/PathPackageLocatorTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/PathPackageLocatorTest.java index 5cf6ada07b..f7d1aa44db 100644 --- a/src/test/java/com/google/devtools/build/lib/pkgcache/PathPackageLocatorTest.java +++ b/src/test/java/com/google/devtools/build/lib/pkgcache/PathPackageLocatorTest.java @@ -14,9 +14,6 @@ package com.google.devtools.build.lib.pkgcache; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; @@ -182,54 +179,58 @@ public class PathPackageLocatorTest extends FoundationTestCase { @Test public void testGetPackageBuildFile() throws Exception { AtomicReference<? extends UnixGlob.FilesystemCalls> cache = UnixGlob.DEFAULT_SYSCALLS_REF; - assertEquals(buildFile_1A, locator.getPackageBuildFile( - PackageIdentifier.createInMainRepo("A"))); - assertEquals(buildFile_1A, locator.getPackageBuildFileNullable( - PackageIdentifier.createInMainRepo("A"), cache)); - assertEquals(buildFile_1B, locator.getPackageBuildFile( - PackageIdentifier.createInMainRepo("B"))); - assertEquals(buildFile_1B, locator.getPackageBuildFileNullable( - PackageIdentifier.createInMainRepo("B"), cache)); - assertEquals(buildFile_2C, locator.getPackageBuildFile( - PackageIdentifier.createInMainRepo("C"))); - assertEquals(buildFile_2C, locator.getPackageBuildFileNullable( - PackageIdentifier.createInMainRepo("C"), cache)); - assertEquals(buildFile_2CD, locator.getPackageBuildFile( - PackageIdentifier.createInMainRepo("C/D"))); - assertEquals(buildFile_2CD, locator.getPackageBuildFileNullable( - PackageIdentifier.createInMainRepo("C/D"), cache)); + assertThat(locator.getPackageBuildFile(PackageIdentifier.createInMainRepo("A"))) + .isEqualTo(buildFile_1A); + assertThat(locator.getPackageBuildFileNullable(PackageIdentifier.createInMainRepo("A"), cache)) + .isEqualTo(buildFile_1A); + assertThat(locator.getPackageBuildFile(PackageIdentifier.createInMainRepo("B"))) + .isEqualTo(buildFile_1B); + assertThat(locator.getPackageBuildFileNullable(PackageIdentifier.createInMainRepo("B"), cache)) + .isEqualTo(buildFile_1B); + assertThat(locator.getPackageBuildFile(PackageIdentifier.createInMainRepo("C"))) + .isEqualTo(buildFile_2C); + assertThat(locator.getPackageBuildFileNullable(PackageIdentifier.createInMainRepo("C"), cache)) + .isEqualTo(buildFile_2C); + assertThat(locator.getPackageBuildFile(PackageIdentifier.createInMainRepo("C/D"))) + .isEqualTo(buildFile_2CD); + assertThat( + locator.getPackageBuildFileNullable(PackageIdentifier.createInMainRepo("C/D"), cache)) + .isEqualTo(buildFile_2CD); checkFails("C/E", "no such package 'C/E': BUILD file not found on package path"); - assertNull(locator.getPackageBuildFileNullable( - PackageIdentifier.createInMainRepo("C/E"), cache)); - assertEquals(buildFile_2F, - locator.getPackageBuildFile(PackageIdentifier.createInMainRepo("F"))); + assertThat( + locator.getPackageBuildFileNullable(PackageIdentifier.createInMainRepo("C/E"), cache)) + .isNull(); + assertThat(locator.getPackageBuildFile(PackageIdentifier.createInMainRepo("F"))) + .isEqualTo(buildFile_2F); checkFails("F/G", "no such package 'F/G': BUILD file not found on package path"); - assertNull(locator.getPackageBuildFileNullable( - PackageIdentifier.createInMainRepo("F/G"), cache)); - assertEquals(buildFile_2FGH, locator.getPackageBuildFile( - PackageIdentifier.createInMainRepo("F/G/H"))); - assertEquals(buildFile_2FGH, locator.getPackageBuildFileNullable( - PackageIdentifier.createInMainRepo("F/G/H"), cache)); + assertThat( + locator.getPackageBuildFileNullable(PackageIdentifier.createInMainRepo("F/G"), cache)) + .isNull(); + assertThat(locator.getPackageBuildFile(PackageIdentifier.createInMainRepo("F/G/H"))) + .isEqualTo(buildFile_2FGH); + assertThat( + locator.getPackageBuildFileNullable(PackageIdentifier.createInMainRepo("F/G/H"), cache)) + .isEqualTo(buildFile_2FGH); checkFails("I", "no such package 'I': BUILD file not found on package path"); } @Test public void testGetPackageBuildFileWithSymlinks() throws Exception { - assertEquals(buildFile_3A, locatorWithSymlinks.getPackageBuildFile( - PackageIdentifier.createInMainRepo("A"))); - assertEquals(buildFile_3B, locatorWithSymlinks.getPackageBuildFile( - PackageIdentifier.createInMainRepo("B"))); - assertEquals(buildFile_3CI, locatorWithSymlinks.getPackageBuildFile( - PackageIdentifier.createInMainRepo("C/I"))); + assertThat(locatorWithSymlinks.getPackageBuildFile(PackageIdentifier.createInMainRepo("A"))) + .isEqualTo(buildFile_3A); + assertThat(locatorWithSymlinks.getPackageBuildFile(PackageIdentifier.createInMainRepo("B"))) + .isEqualTo(buildFile_3B); + assertThat(locatorWithSymlinks.getPackageBuildFile(PackageIdentifier.createInMainRepo("C/I"))) + .isEqualTo(buildFile_3CI); checkFails( locatorWithSymlinks, "C/D", "no such package 'C/D': BUILD file not found on package path"); } @Test public void testGetWorkspaceFile() throws Exception { - assertEquals(rootDir1WorkspaceFile, locator.getWorkspaceFile()); + assertThat(locator.getWorkspaceFile()).isEqualTo(rootDir1WorkspaceFile); } private Path setLocator(String root) { @@ -286,11 +287,11 @@ public class PathPackageLocatorTest extends FoundationTestCase { // No warning if workspace == cwd. PathPackageLocator.create(null, ImmutableList.of("./foo"), reporter, workspace, workspace); - assertSame(0, eventCollector.count()); + assertThat(eventCollector.count()).isSameAs(0); PathPackageLocator.create( null, ImmutableList.of("./foo"), reporter, workspace, workspace.getRelative("foo")); - assertSame(1, eventCollector.count()); + assertThat(eventCollector.count()).isSameAs(1); assertContainsEvent("The package path element './foo' will be taken relative"); } diff --git a/src/test/java/com/google/devtools/build/lib/pkgcache/TargetPatternEvaluatorTest.java b/src/test/java/com/google/devtools/build/lib/pkgcache/TargetPatternEvaluatorTest.java index da003add73..7f7376c5f3 100644 --- a/src/test/java/com/google/devtools/build/lib/pkgcache/TargetPatternEvaluatorTest.java +++ b/src/test/java/com/google/devtools/build/lib/pkgcache/TargetPatternEvaluatorTest.java @@ -15,10 +15,6 @@ package com.google.devtools.build.lib.pkgcache; import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.build.lib.pkgcache.FilteringPolicies.FILTER_TESTS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; @@ -36,15 +32,13 @@ import com.google.devtools.build.lib.util.Pair; import com.google.devtools.build.lib.vfs.ModifiedFileSet; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; - +import java.util.Arrays; +import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.Arrays; -import java.util.Set; - /** Tests for {@link TargetPatternEvaluator}. */ @RunWith(JUnit4.class) public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTest { @@ -170,7 +164,7 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe throws TargetParsingException, InterruptedException { ResolvedTargets<Target> result = parseTargetPatternList(parser, parsingListener, Arrays.asList(patterns), true); - assertTrue(result.hasError()); + assertThat(result.hasError()).isTrue(); return targetsToLabels(result.getTargets()); } @@ -188,7 +182,7 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe } private static Set<Target> getFailFast(ResolvedTargets<Target> result) { - assertFalse(result.hasError()); + assertThat(result.hasError()).isFalse(); return result.getTargets(); } @@ -198,7 +192,7 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe parser.parseTargetPattern(parsingListener, target, false); fail("target='" + target + "', expected error: " + expectedError); } catch (TargetParsingException e) { - assertThat(e.getMessage()).contains(expectedError); + assertThat(e).hasMessageThat().contains(expectedError); } } @@ -224,14 +218,13 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe @Test public void testParsingStandardLabel() throws Exception { - assertEquals("//foo:foo1", - parseIndividualTarget("//foo:foo1").toString()); + assertThat(parseIndividualTarget("//foo:foo1").toString()).isEqualTo("//foo:foo1"); } @Test public void testAbsolutePatternEndsWithSlashAll() throws Exception { scratch.file("foo/all/BUILD", "cc_library(name = 'all')"); - assertEquals("//foo/all:all", parseIndividualTarget("//foo/all").toString()); + assertThat(parseIndividualTarget("//foo/all").toString()).isEqualTo("//foo/all:all"); assertNoEvents(); } @@ -249,8 +242,8 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe } private void assertWildcardConflict(String label, String suffix) throws Exception { - assertEquals(label, parseIndividualTarget(label).toString()); - assertSame(1, eventCollector.count()); + assertThat(parseIndividualTarget(label).toString()).isEqualTo(label); + assertThat(eventCollector.count()).isSameAs(1); assertContainsEvent(String.format("The target pattern '%s' is ambiguous: '%s' is both " + "a wildcard, and the name of an existing cc_library rule; " + "using the latter interpretation", label, suffix)); @@ -262,13 +255,13 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe parseIndividualTarget("//missing:foo1"); fail("TargetParsingException expected"); } catch (TargetParsingException e) { - assertThat(e.getMessage()).startsWith("no such package"); + assertThat(e).hasMessageThat().startsWith("no such package"); } } @Test public void testParsingStandardLabelWithRelativeParser() throws Exception { - assertEquals("//foo:foo1", parseIndividualTargetRelative("//foo:foo1").toString()); + assertThat(parseIndividualTargetRelative("//foo:foo1").toString()).isEqualTo("//foo:foo1"); } @Test @@ -277,19 +270,18 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe parseIndividualTarget("//foo:missing"); fail("TargetParsingException expected"); } catch (TargetParsingException e) { - assertThat(e.getMessage()).startsWith("no such target"); + assertThat(e).hasMessageThat().startsWith("no such target"); } } @Test public void testParsingStandardLabelShorthand() throws Exception { - assertEquals("//foo:foo1", - parseIndividualTarget("foo:foo1").toString()); + assertThat(parseIndividualTarget("foo:foo1").toString()).isEqualTo("//foo:foo1"); } @Test public void testParsingStandardLabelShorthandRelative() throws Exception { - assertEquals("//foo:foo1", parseIndividualTargetRelative(":foo1").toString()); + assertThat(parseIndividualTargetRelative(":foo1").toString()).isEqualTo("//foo:foo1"); } @Test @@ -477,8 +469,10 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe public void testDefaultPackage() throws Exception { scratch.file("experimental/BUILD", "cc_library(name = 'experimental', srcs = [ 'experimental.cc' ])"); - assertEquals("//experimental:experimental", parseIndividualTarget("//experimental").toString()); - assertEquals("//experimental:experimental", parseIndividualTarget("experimental").toString()); + assertThat(parseIndividualTarget("//experimental").toString()) + .isEqualTo("//experimental:experimental"); + assertThat(parseIndividualTarget("experimental").toString()) + .isEqualTo("//experimental:experimental"); assertNoEvents(); } @@ -491,28 +485,26 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe scratch.file("sub/dir/BUILD", "exports_files(['dir2'])"); scratch.file("sub/dir/dir/BUILD", "exports_files(['dir'])"); // sub/dir/dir is a package - assertEquals("//sub/dir/dir:dir", parseIndividualTarget("sub/dir/dir").toString()); + assertThat(parseIndividualTarget("sub/dir/dir").toString()).isEqualTo("//sub/dir/dir:dir"); // sub/dir is a package but not sub/dir/dir2 - assertEquals("//sub/dir:dir2", parseIndividualTarget("sub/dir/dir2").toString()); + assertThat(parseIndividualTarget("sub/dir/dir2").toString()).isEqualTo("//sub/dir:dir2"); // sub is a package but not sub/dir2 - assertEquals("//sub:dir2/dir2", parseIndividualTarget("sub/dir2/dir2").toString()); + assertThat(parseIndividualTarget("sub/dir2/dir2").toString()).isEqualTo("//sub:dir2/dir2"); } @Test public void testFindsLongestPlausiblePackageName() throws Exception { - assertEquals("//foo/bar:baz", - parseIndividualTarget("foo/bar/baz").toString()); - assertEquals("//foo/bar:baz/bang", - parseIndividualTarget("foo/bar/baz/bang").toString()); - assertEquals("//foo:baz/bang", - parseIndividualTarget("foo/baz/bang").toString()); + assertThat(parseIndividualTarget("foo/bar/baz").toString()).isEqualTo("//foo/bar:baz"); + assertThat(parseIndividualTarget("foo/bar/baz/bang").toString()) + .isEqualTo("//foo/bar:baz/bang"); + assertThat(parseIndividualTarget("foo/baz/bang").toString()).isEqualTo("//foo:baz/bang"); } @Test public void testParsesIterableOfLabels() throws Exception { Set<Label> labels = Sets.newHashSet(Label.parseAbsolute("//foo/bar:bar1"), Label.parseAbsolute("//foo:foo1")); - assertEquals(labels, parseList("//foo/bar:bar1", "//foo:foo1")); + assertThat(parseList("//foo/bar:bar1", "//foo:foo1")).isEqualTo(labels); parsingListener.assertEmpty(); } @@ -520,24 +512,23 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe public void testParseAbsoluteWithRelativeParser() throws Exception { Set<Label> labels = Sets.newHashSet(Label.parseAbsolute("//foo/bar:bar1"), Label.parseAbsolute("//foo:foo1")); - assertEquals(labels, parseListRelative("//foo/bar:bar1", "//foo:foo1")); + assertThat(parseListRelative("//foo/bar:bar1", "//foo:foo1")).isEqualTo(labels); parsingListener.assertEmpty(); } @Test public void testMultisegmentLabelsWithNoSlashSlash() throws Exception { - assertEquals("//foo/bar:wiz/bang", - parseIndividualTarget("foo/bar:wiz/bang").toString()); - assertEquals("//foo/bar:wiz/all", - parseIndividualTarget("foo/bar:wiz/all").toString()); + assertThat(parseIndividualTarget("foo/bar:wiz/bang").toString()) + .isEqualTo("//foo/bar:wiz/bang"); + assertThat(parseIndividualTarget("foo/bar:wiz/all").toString()).isEqualTo("//foo/bar:wiz/all"); } @Test public void testMultisegmentLabelsWithNoSlashSlashRelative() throws Exception { - assertEquals("//foo/bar:wiz/bang", - parseIndividualTargetRelative("bar:wiz/bang").toString()); - assertEquals("//foo/bar:wiz/all", - parseIndividualTargetRelative("bar:wiz/all").toString()); + assertThat(parseIndividualTargetRelative("bar:wiz/bang").toString()) + .isEqualTo("//foo/bar:wiz/bang"); + assertThat(parseIndividualTargetRelative("bar:wiz/all").toString()) + .isEqualTo("//foo/bar:wiz/all"); } /** Regression test for a bug. */ @@ -546,8 +537,7 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe scratch.file("x/y/BUILD", "cc_library(name='y')"); scratch.file("x/z/BUILD", "cc_library(name='z')"); setDeletedPackages(Sets.newHashSet(PackageIdentifier.createInMainRepo("x/y"))); - assertEquals(Sets.newHashSet(Label.parseAbsolute("//x/z")), - parseList("x/...")); + assertThat(parseList("x/...")).isEqualTo(Sets.newHashSet(Label.parseAbsolute("//x/z"))); } @Test @@ -557,8 +547,9 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe setDeletedPackages(Sets.newHashSet(PackageIdentifier.createInMainRepo("x/y"))); parser.updateOffset(PathFragment.create("x")); - assertEquals(Sets.newHashSet(Label.parseAbsolute("//x/z")), - targetsToLabels(getFailFast(parser.parseTargetPattern(parsingListener, "...", false)))); + assertThat( + targetsToLabels(getFailFast(parser.parseTargetPattern(parsingListener, "...", false)))) + .isEqualTo(Sets.newHashSet(Label.parseAbsolute("//x/z"))); } @Test @@ -566,15 +557,15 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe scratch.file("x/y/BUILD", "cc_library(name='y')"); scratch.file("x/z/BUILD", "cc_library(name='z')"); - assertEquals(Sets.newHashSet(Label.parseAbsolute("//x/y"), Label.parseAbsolute("//x/z")), - parseList("x/...")); + assertThat(parseList("x/...")).containsExactly( + Label.parseAbsolute("//x/y"), Label.parseAbsolute("//x/z")); setDeletedPackages(Sets.newHashSet(PackageIdentifier.createInMainRepo("x/y"))); - assertEquals(Sets.newHashSet(Label.parseAbsolute("//x/z")), parseList("x/...")); + assertThat(parseList("x/...")).containsExactly(Label.parseAbsolute("//x/z")); setDeletedPackages(ImmutableSet.<PackageIdentifier>of()); - assertEquals(Sets.newHashSet(Label.parseAbsolute("//x/y"), Label.parseAbsolute("//x/z")), - parseList("x/...")); + assertThat(parseList("x/...")).containsExactly( + Label.parseAbsolute("//x/y"), Label.parseAbsolute("//x/z")); } @Test @@ -784,10 +775,10 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe @Test public void testSetOffset() throws Exception { - assertEquals("//foo:foo1", parseIndividualTarget("foo:foo1").toString()); + assertThat(parseIndividualTarget("foo:foo1").toString()).isEqualTo("//foo:foo1"); parser.updateOffset(PathFragment.create("foo")); - assertEquals("//foo:foo1", parseIndividualTarget(":foo1").toString()); + assertThat(parseIndividualTarget(":foo1").toString()).isEqualTo("//foo:foo1"); } @Test @@ -847,7 +838,7 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe assertThat(result.first) .containsExactlyElementsIn( Sets.newHashSet(Label.parseAbsolute("//x/y:a"), Label.parseAbsolute("//x/y:b"))); - assertFalse(result.second); + assertThat(result.second).isFalse(); } @Test @@ -883,7 +874,7 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe // Even though there was a loading error in the package, parsing the target pattern was // successful. - assertFalse(result.second); + assertThat(result.second).isFalse(); } @Test @@ -901,7 +892,7 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe /*keepGoing=*/false); fail(); } catch (TargetParsingException e) { - assertThat(e.getMessage()).contains("no such target"); + assertThat(e).hasMessageThat().contains("no such target"); } } @@ -910,13 +901,12 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe ResolvedTargets<Target> result = parseTargetPatternList(parser, parsingListener, Arrays.asList("//foo/bar/BUILD"), false); - assertFalse(result.hasError()); + assertThat(result.hasError()).isFalse(); assertThat(result.getTargets()).hasSize(1); Label label = Iterables.getOnlyElement(result.getTargets()).getLabel(); - assertEquals("BUILD", label.getName()); - assertEquals("foo/bar", label.getPackageName()); - + assertThat(label.getName()).isEqualTo("BUILD"); + assertThat(label.getPackageName()).isEqualTo("foo/bar"); } /** @@ -933,9 +923,9 @@ public class TargetPatternEvaluatorTest extends AbstractTargetPatternEvaluatorTe "genrule(name='c', outs=['c.out'])"); Pair<Set<Label>, Boolean> result = parseListKeepGoing("//loading:y"); - assertEquals(Label.parseAbsolute("//loading:y"), Iterables.getOnlyElement(result.first)); + assertThat(result.first).containsExactly(Label.parseAbsolute("//loading:y")); assertContainsEvent("missing value for mandatory attribute"); - assertFalse(result.second); + assertThat(result.second).isFalse(); } private void assertKeepGoing(Set<Label> expectedLabels, String expectedEvent, String... toParse) diff --git a/src/test/java/com/google/devtools/build/lib/profiler/ProfilerChartTest.java b/src/test/java/com/google/devtools/build/lib/profiler/ProfilerChartTest.java index 1c343b27bd..7292378a2a 100644 --- a/src/test/java/com/google/devtools/build/lib/profiler/ProfilerChartTest.java +++ b/src/test/java/com/google/devtools/build/lib/profiler/ProfilerChartTest.java @@ -14,9 +14,6 @@ package com.google.devtools.build.lib.profiler; import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; import com.google.devtools.build.lib.profiler.Profiler.ProfiledTaskKinds; import com.google.devtools.build.lib.profiler.chart.AggregatingChartCreator; @@ -36,16 +33,12 @@ import com.google.devtools.build.lib.testutil.Suite; import com.google.devtools.build.lib.testutil.TestSpec; import com.google.devtools.build.lib.util.BlazeClock; import com.google.devtools.build.lib.vfs.Path; - +import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.List; - -/** - * Unit tests for the profiler chart generation. - */ +/** Unit tests for the profiler chart generation. */ @TestSpec(size = Suite.MEDIUM_TESTS) @RunWith(JUnit4.class) public class ProfilerChartTest extends FoundationTestCase { @@ -67,13 +60,13 @@ public class ProfilerChartTest extends FoundationTestCase { ProfileInfo info = createProfileInfo(run, threads - 1); ChartCreator aggregatingCreator = new AggregatingChartCreator(info, true); Chart aggregatedChart = aggregatingCreator.create(); - assertEquals(threads, aggregatedChart.getRowCount()); + assertThat(aggregatedChart.getRowCount()).isEqualTo(threads); assertThat(aggregatedChart.getSortedRows().get(0).getBars()).hasSize(1); ChartCreator detailedCreator = new DetailedChartCreator(info); Chart detailedChart = detailedCreator.create(); assertThat(detailedChart.getSortedTypes()).hasSize(COMMON_CHART_TYPES + DETAILED_CHART_TYPES); - assertEquals(threads, detailedChart.getRowCount()); + assertThat(detailedChart.getRowCount()).isEqualTo(threads); assertThat(detailedChart.getSortedRows().get(0).getBars()).hasSize(1); } @@ -123,18 +116,18 @@ public class ProfilerChartTest extends FoundationTestCase { ChartBarType type1 = chart.createType("name1", Color.BLACK); List<ChartBarType> types = chart.getSortedTypes(); assertThat(types).hasSize(3); - assertEquals(type1.getName(), types.get(0).getName()); - assertEquals(type1.getColor(), types.get(0).getColor()); - assertEquals(type2.getName(), types.get(1).getName()); - assertEquals(type2.getColor(), types.get(1).getColor()); - assertEquals(type3.getName(), types.get(2).getName()); - assertEquals(type3.getColor(), types.get(2).getColor()); - - assertSame(type3, chart.lookUpType("name3")); - assertSame(type2, chart.lookUpType("name2")); - assertSame(type1, chart.lookUpType("name1")); - - assertSame(Chart.UNKNOWN_TYPE, chart.lookUpType("wergl")); + assertThat(types.get(0).getName()).isEqualTo(type1.getName()); + assertThat(types.get(0).getColor()).isEqualTo(type1.getColor()); + assertThat(types.get(1).getName()).isEqualTo(type2.getName()); + assertThat(types.get(1).getColor()).isEqualTo(type2.getColor()); + assertThat(types.get(2).getName()).isEqualTo(type3.getName()); + assertThat(types.get(2).getColor()).isEqualTo(type3.getColor()); + + assertThat(chart.lookUpType("name3")).isSameAs(type3); + assertThat(chart.lookUpType("name2")).isSameAs(type2); + assertThat(chart.lookUpType("name1")).isSameAs(type1); + + assertThat(chart.lookUpType("wergl")).isSameAs(Chart.UNKNOWN_TYPE); types = chart.getSortedTypes(); assertThat(types).hasSize(4); @@ -145,8 +138,8 @@ public class ProfilerChartTest extends FoundationTestCase { chart.addBar(3, 4, 5, type3, "label5"); chart.addBar(3, 5, 6, type3, "label6"); - assertEquals(6, chart.getMaxStop()); - assertEquals(3, chart.getRowCount()); + assertThat(chart.getMaxStop()).isEqualTo(6); + assertThat(chart.getRowCount()).isEqualTo(3); List<ChartRow> rows = chart.getSortedRows(); assertThat(rows).hasSize(3); @@ -155,10 +148,10 @@ public class ProfilerChartTest extends FoundationTestCase { assertThat(rows.get(2).getBars()).hasSize(3); ChartBar bar = rows.get(0).getBars().get(0); - assertEquals(2, bar.getStart()); - assertEquals(3, bar.getStop()); - assertSame(type1, bar.getType()); - assertEquals("label1", bar.getLabel()); + assertThat(bar.getStart()).isEqualTo(2); + assertThat(bar.getStop()).isEqualTo(3); + assertThat(bar.getType()).isSameAs(type1); + assertThat(bar.getLabel()).isEqualTo("label1"); } @Test @@ -167,19 +160,19 @@ public class ProfilerChartTest extends FoundationTestCase { ChartRow row2 = new ChartRow("2", 1); ChartRow row3 = new ChartRow("3", 1); - assertEquals("1", row1.getId()); - assertEquals(0, row1.getIndex()); + assertThat(row1.getId()).isEqualTo("1"); + assertThat(row1.getIndex()).isEqualTo(0); - assertEquals(-1, row1.compareTo(row2)); - assertEquals(1, row2.compareTo(row1)); - assertEquals(0, row2.compareTo(row3)); + assertThat(row1.compareTo(row2)).isEqualTo(-1); + assertThat(row2.compareTo(row1)).isEqualTo(1); + assertThat(row2.compareTo(row3)).isEqualTo(0); row1.addBar(new ChartBar(row1, 1, 2, new ChartBarType("name1", Color.BLACK), false, "label1")); row1.addBar(new ChartBar(row1, 2, 3, new ChartBarType("name2", Color.RED), false, "label2")); assertThat(row1.getBars()).hasSize(2); - assertEquals("label1", row1.getBars().get(0).getLabel()); - assertEquals("label2", row1.getBars().get(1).getLabel()); + assertThat(row1.getBars().get(0).getLabel()).isEqualTo("label1"); + assertThat(row1.getBars().get(1).getLabel()).isEqualTo("label2"); } @Test @@ -188,17 +181,17 @@ public class ProfilerChartTest extends FoundationTestCase { ChartBarType type2 = new ChartBarType("name2", Color.RED); ChartBarType type3 = new ChartBarType("name2", Color.GREEN); - assertEquals(-1, type1.compareTo(type2)); - assertEquals(1, type2.compareTo(type1)); - assertEquals(0, type2.compareTo(type3)); + assertThat(type1.compareTo(type2)).isEqualTo(-1); + assertThat(type2.compareTo(type1)).isEqualTo(1); + assertThat(type2.compareTo(type3)).isEqualTo(0); - assertEquals(type3, type2); - assertFalse(type1.equals(type3)); - assertFalse(type1.equals(type2)); + assertThat(type2).isEqualTo(type3); + assertThat(type1.equals(type3)).isFalse(); + assertThat(type1.equals(type2)).isFalse(); - assertEquals(type3.hashCode(), type2.hashCode()); - assertFalse(type1.hashCode() == type2.hashCode()); - assertFalse(type1.hashCode() == type3.hashCode()); + assertThat(type2.hashCode()).isEqualTo(type3.hashCode()); + assertThat(type1.hashCode() == type2.hashCode()).isFalse(); + assertThat(type1.hashCode() == type3.hashCode()).isFalse(); } @Test @@ -206,11 +199,11 @@ public class ProfilerChartTest extends FoundationTestCase { ChartRow row1 = new ChartRow("1", 0); ChartBarType type = new ChartBarType("name1", Color.BLACK); ChartBar bar1 = new ChartBar(row1, 1, 2, type, false, "label1"); - assertEquals(row1, bar1.getRow()); - assertEquals(1, bar1.getStart()); - assertEquals(2, bar1.getStop()); - assertSame(type, bar1.getType()); - assertEquals("label1", bar1.getLabel()); + assertThat(bar1.getRow()).isEqualTo(row1); + assertThat(bar1.getStart()).isEqualTo(1); + assertThat(bar1.getStop()).isEqualTo(2); + assertThat(bar1.getType()).isSameAs(type); + assertThat(bar1.getLabel()).isEqualTo("label1"); } @Test @@ -228,12 +221,12 @@ public class ProfilerChartTest extends FoundationTestCase { TestingChartVisitor visitor = new TestingChartVisitor(); chart.accept(visitor); - assertEquals(1, visitor.beginChartCount); - assertEquals(1, visitor.endChartCount); - assertEquals(3, visitor.rowCount); - assertEquals(6, visitor.barCount); - assertEquals(0, visitor.columnCount); - assertEquals(0, visitor.lineCount); + assertThat(visitor.beginChartCount).isEqualTo(1); + assertThat(visitor.endChartCount).isEqualTo(1); + assertThat(visitor.rowCount).isEqualTo(3); + assertThat(visitor.barCount).isEqualTo(6); + assertThat(visitor.columnCount).isEqualTo(0); + assertThat(visitor.lineCount).isEqualTo(0); } private ProfileInfo createProfileInfo(Runnable runnable, int noOfRows) throws Exception { diff --git a/src/test/java/com/google/devtools/build/lib/profiler/ProfilerTest.java b/src/test/java/com/google/devtools/build/lib/profiler/ProfilerTest.java index e6175a890c..0666d1f156 100644 --- a/src/test/java/com/google/devtools/build/lib/profiler/ProfilerTest.java +++ b/src/test/java/com/google/devtools/build/lib/profiler/ProfilerTest.java @@ -15,9 +15,6 @@ package com.google.devtools.build.lib.profiler; import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.ISO_8859_1; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.devtools.build.lib.profiler.Profiler.ProfiledTaskKinds; @@ -59,13 +56,13 @@ public class ProfilerTest extends FoundationTestCase { @Test public void testProfilerActivation() throws Exception { Path cacheFile = cacheDir.getRelative("profile1.dat"); - assertFalse(profiler.isActive()); + assertThat(profiler.isActive()).isFalse(); profiler.start(ProfiledTaskKinds.ALL, cacheFile.getOutputStream(), "basic test", false, BlazeClock.instance(), BlazeClock.instance().nanoTime()); - assertTrue(profiler.isActive()); + assertThat(profiler.isActive()).isTrue(); profiler.stop(); - assertFalse(profiler.isActive()); + assertThat(profiler.isActive()).isFalse(); } @Test @@ -81,14 +78,14 @@ public class ProfilerTest extends FoundationTestCase { info.calculateStats(); ProfileInfo.Task task = info.allTasksById.get(0); - assertEquals(1, task.id); - assertEquals(ProfilerTask.ACTION, task.type); - assertEquals("action task", task.getDescription()); + assertThat(task.id).isEqualTo(1); + assertThat(task.type).isEqualTo(ProfilerTask.ACTION); + assertThat(task.getDescription()).isEqualTo("action task"); task = info.allTasksById.get(1); - assertEquals(2, task.id); - assertEquals(ProfilerTask.TEST, task.type); - assertEquals("event", task.getDescription()); + assertThat(task.id).isEqualTo(2); + assertThat(task.type).isEqualTo(ProfilerTask.TEST); + assertThat(task.getDescription()).isEqualTo("event"); } @Test @@ -122,7 +119,7 @@ public class ProfilerTest extends FoundationTestCase { assertThat(info.allTasksById).hasSize(6); // only 5 tasks + finalization should be recorded ProfileInfo.Task task = info.allTasksById.get(0); - assertTrue(task.stats.isEmpty()); + assertThat(task.stats.isEmpty()).isTrue(); task = info.allTasksById.get(1); int count = 0; @@ -131,21 +128,21 @@ public class ProfilerTest extends FoundationTestCase { count++; } } - assertEquals(2, count); // only children are GENERIC and ACTION_CHECK - assertEquals(task.aggregatedStats.toArray().length, ProfilerTask.TASK_COUNT); - assertEquals(2, task.aggregatedStats.getAttr(ProfilerTask.VFS_STAT).count); + assertThat(count).isEqualTo(2); // only children are GENERIC and ACTION_CHECK + assertThat(ProfilerTask.TASK_COUNT).isEqualTo(task.aggregatedStats.toArray().length); + assertThat(task.aggregatedStats.getAttr(ProfilerTask.VFS_STAT).count).isEqualTo(2); task = info.allTasksById.get(2); assertThat(task.durationNanos).isEqualTo(0); task = info.allTasksById.get(3); - assertEquals(2, task.stats.getAttr(ProfilerTask.VFS_STAT).count); - assertEquals(1, task.subtasks.length); - assertEquals("stat2", task.subtasks[0].getDescription()); + assertThat(task.stats.getAttr(ProfilerTask.VFS_STAT).count).isEqualTo(2); + assertThat(task.subtasks).hasLength(1); + assertThat(task.subtasks[0].getDescription()).isEqualTo("stat2"); // assert that startTime grows with id long time = -1; for (ProfileInfo.Task t : info.allTasksById) { - assertTrue(t.startTime >= time); + assertThat(t.startTime).isAtLeast(time); time = t.startTime; } } @@ -165,7 +162,7 @@ public class ProfilerTest extends FoundationTestCase { assertThat(info.allTasksById).hasSize(3); // 2 tasks + finalization should be recorded ProfileInfo.Task task = info.allTasksById.get(1); - assertEquals(ProfilerTask.VFS_STAT, task.type); + assertThat(task.type).isEqualTo(ProfilerTask.VFS_STAT); // Check that task would have been dropped if profiler was not configured to record everything. assertThat(task.durationNanos).isLessThan(ProfilerTask.VFS_STAT.minDuration); @@ -180,8 +177,8 @@ public class ProfilerTest extends FoundationTestCase { profiler.logSimpleTask(10000, 20000, ProfilerTask.VFS_STAT, "stat"); profiler.logSimpleTask(20000, 30000, ProfilerTask.REMOTE_EXECUTION, "remote execution"); - assertTrue(profiler.isProfiling(ProfilerTask.VFS_STAT)); - assertFalse(profiler.isProfiling(ProfilerTask.REMOTE_EXECUTION)); + assertThat(profiler.isProfiling(ProfilerTask.VFS_STAT)).isTrue(); + assertThat(profiler.isProfiling(ProfilerTask.REMOTE_EXECUTION)).isFalse(); profiler.stop(); @@ -190,7 +187,7 @@ public class ProfilerTest extends FoundationTestCase { assertThat(info.allTasksById).hasSize(1); // only VFS_STAT task should be recorded ProfileInfo.Task task = info.allTasksById.get(0); - assertEquals(ProfilerTask.VFS_STAT, task.type); + assertThat(task.type).isEqualTo(ProfilerTask.VFS_STAT); } @Test @@ -201,8 +198,8 @@ public class ProfilerTest extends FoundationTestCase { BlazeClock.instance(), BlazeClock.instance().nanoTime()); profiler.logSimpleTask(10000, 20000, ProfilerTask.VFS_STAT, "stat"); - assertTrue(ProfilerTask.VFS_STAT.collectsSlowestInstances()); - assertFalse(profiler.isProfiling(ProfilerTask.VFS_STAT)); + assertThat(ProfilerTask.VFS_STAT.collectsSlowestInstances()).isTrue(); + assertThat(profiler.isProfiling(ProfilerTask.VFS_STAT)).isFalse(); profiler.stop(); @@ -264,23 +261,23 @@ public class ProfilerTest extends FoundationTestCase { ProfileInfo info = ProfileInfo.loadProfile(cacheFile); info.calculateStats(); info.analyzeRelationships(); - assertEquals(4 + 10000 + 10000, info.allTasksById.size()); // total number of tasks - assertEquals(3, info.tasksByThread.size()); // total number of threads + assertThat(info.allTasksById).hasSize(4 + 10000 + 10000); // total number of tasks + assertThat(info.tasksByThread).hasSize(3); // total number of threads // while main thread had 3 tasks, 2 of them were nested, so tasksByThread // would contain only one "main task" task - assertEquals(2, info.tasksByThread.get(id).length); + assertThat(info.tasksByThread.get(id)).hasLength(2); ProfileInfo.Task mainTask = info.tasksByThread.get(id)[0]; - assertEquals("main task", mainTask.getDescription()); - assertEquals(2, mainTask.subtasks.length); + assertThat(mainTask.getDescription()).isEqualTo("main task"); + assertThat(mainTask.subtasks).hasLength(2); // other threads had 10000 independent recorded tasks each - assertEquals(10000, info.tasksByThread.get(id1).length); - assertEquals(10000, info.tasksByThread.get(id2).length); + assertThat(info.tasksByThread.get(id1)).hasLength(10000); + assertThat(info.tasksByThread.get(id2)).hasLength(10000); int startId = mainTask.subtasks[0].id; // id of "starting threads" int endId = mainTask.subtasks[1].id; // id of "joining" - assertTrue(startId < info.tasksByThread.get(id1)[0].id); - assertTrue(startId < info.tasksByThread.get(id2)[0].id); - assertTrue(endId > info.tasksByThread.get(id1)[9999].id); - assertTrue(endId > info.tasksByThread.get(id2)[9999].id); + assertThat(startId).isLessThan(info.tasksByThread.get(id1)[0].id); + assertThat(startId).isLessThan(info.tasksByThread.get(id2)[0].id); + assertThat(endId).isGreaterThan(info.tasksByThread.get(id1)[9999].id); + assertThat(endId).isGreaterThan(info.tasksByThread.get(id2)[9999].id); } @Test @@ -355,19 +352,19 @@ public class ProfilerTest extends FoundationTestCase { ProfileInfo info = ProfileInfo.loadProfile(cacheFile); info.calculateStats(); - assertFalse(info.isCorruptedOrIncomplete()); + assertThat(info.isCorruptedOrIncomplete()).isFalse(); Path corruptedFile = cacheDir.getRelative("profile5bad.dat"); FileSystemUtils.writeContent( corruptedFile, Arrays.copyOf(FileSystemUtils.readContent(cacheFile), 2000)); info = ProfileInfo.loadProfile(corruptedFile); info.calculateStats(); - assertTrue(info.isCorruptedOrIncomplete()); + assertThat(info.isCorruptedOrIncomplete()).isTrue(); // Since root tasks will appear after nested tasks in the profile file and // we have exactly one nested task for each root task, then following will be // always true for our corrupted file: // 0 <= number_of_all_tasks - 2*number_of_root_tasks <= 1 - assertEquals(info.rootTasksById.size(), info.allTasksById.size() / 2); + assertThat(info.allTasksById.size() / 2).isEqualTo(info.rootTasksById.size()); } @Test @@ -386,19 +383,19 @@ public class ProfilerTest extends FoundationTestCase { // Validate our test profile. ProfileInfo info = ProfileInfo.loadProfile(dataFile); info.calculateStats(); - assertFalse(info.isCorruptedOrIncomplete()); - assertEquals(2, info.getStatsForType(ProfilerTask.TEST, info.rootTasksById).count); - assertEquals(0, info.getStatsForType(ProfilerTask.UNKNOWN, info.rootTasksById).count); + assertThat(info.isCorruptedOrIncomplete()).isFalse(); + assertThat(info.getStatsForType(ProfilerTask.TEST, info.rootTasksById).count).isEqualTo(2); + assertThat(info.getStatsForType(ProfilerTask.UNKNOWN, info.rootTasksById).count).isEqualTo(0); // Now replace "TEST" type with something unsupported - e.g. "XXXX". InputStream in = new InflaterInputStream(dataFile.getInputStream(), new Inflater(false), 65536); byte[] buffer = new byte[60000]; int len = in.read(buffer); in.close(); - assertTrue(len < buffer.length); // Validate that file was completely decoded. + assertThat(len).isLessThan(buffer.length); // Validate that file was completely decoded. String content = new String(buffer, ISO_8859_1); int infoIndex = content.indexOf("TEST"); - assertTrue(infoIndex > 0); + assertThat(infoIndex).isGreaterThan(0); content = content.substring(0, infoIndex) + "XXXX" + content.substring(infoIndex + 4); OutputStream out = new DeflaterOutputStream(dataFile.getOutputStream(), new Deflater(Deflater.BEST_SPEED, false), 65536); @@ -408,11 +405,11 @@ public class ProfilerTest extends FoundationTestCase { // Validate that XXXX records were classified as UNKNOWN. info = ProfileInfo.loadProfile(dataFile); info.calculateStats(); - assertFalse(info.isCorruptedOrIncomplete()); - assertEquals(0, info.getStatsForType(ProfilerTask.TEST, info.rootTasksById).count); - assertEquals(1, info.getStatsForType(ProfilerTask.SCANNER, info.rootTasksById).count); - assertEquals(1, info.getStatsForType(ProfilerTask.EXCEPTION, info.rootTasksById).count); - assertEquals(2, info.getStatsForType(ProfilerTask.UNKNOWN, info.rootTasksById).count); + assertThat(info.isCorruptedOrIncomplete()).isFalse(); + assertThat(info.getStatsForType(ProfilerTask.TEST, info.rootTasksById).count).isEqualTo(0); + assertThat(info.getStatsForType(ProfilerTask.SCANNER, info.rootTasksById).count).isEqualTo(1); + assertThat(info.getStatsForType(ProfilerTask.EXCEPTION, info.rootTasksById).count).isEqualTo(1); + assertThat(info.getStatsForType(ProfilerTask.UNKNOWN, info.rootTasksById).count).isEqualTo(2); } @Test 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 08a0bb1928..b9b9862b31 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 @@ -255,7 +255,8 @@ public class ProtoCompileActionBuilderTest { ImmutableList.<String>of() /* protocOpts */); fail("Expected an exception"); } catch (IllegalStateException e) { - assertThat(e.getMessage()) + assertThat(e) + .hasMessageThat() .isEqualTo( "Invocation name pluginName appears more than once. " + "This could lead to incorrect proto-compiler behavior"); diff --git a/src/test/java/com/google/devtools/common/options/AssignmentConverterTest.java b/src/test/java/com/google/devtools/common/options/AssignmentConverterTest.java index ff81b8f071..d6f7a57b25 100644 --- a/src/test/java/com/google/devtools/common/options/AssignmentConverterTest.java +++ b/src/test/java/com/google/devtools/common/options/AssignmentConverterTest.java @@ -14,21 +14,19 @@ package com.google.devtools.common.options; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.common.collect.Maps; - +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.Map; - /** - * Test for {@link Converters.AssignmentConverter} and - * {@link Converters.OptionalAssignmentConverter}. + * Test for {@link Converters.AssignmentConverter} and {@link + * Converters.OptionalAssignmentConverter}. */ public abstract class AssignmentConverterTest { @@ -47,9 +45,9 @@ public abstract class AssignmentConverterTest { @Test public void assignment() throws Exception { - assertEquals(Maps.immutableEntry("A", "1"), convert("A=1")); - assertEquals(Maps.immutableEntry("A", "ABC"), convert("A=ABC")); - assertEquals(Maps.immutableEntry("A", ""), convert("A=")); + assertThat(convert("A=1")).isEqualTo(Maps.immutableEntry("A", "1")); + assertThat(convert("A=ABC")).isEqualTo(Maps.immutableEntry("A", "ABC")); + assertThat(convert("A=")).isEqualTo(Maps.immutableEntry("A", "")); } @Test @@ -102,7 +100,7 @@ public abstract class AssignmentConverterTest { @Test public void missingValue() throws Exception { - assertEquals(Maps.immutableEntry("NAME", null), convert("NAME")); + assertThat(convert("NAME")).isEqualTo(Maps.immutableEntry("NAME", null)); } } } diff --git a/src/test/java/com/google/devtools/common/options/BoolOrEnumConverterTest.java b/src/test/java/com/google/devtools/common/options/BoolOrEnumConverterTest.java index 3f88e0d18c..54a173fa78 100644 --- a/src/test/java/com/google/devtools/common/options/BoolOrEnumConverterTest.java +++ b/src/test/java/com/google/devtools/common/options/BoolOrEnumConverterTest.java @@ -14,9 +14,8 @@ package com.google.devtools.common.options; +import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.common.options.OptionsParser.newOptionsParser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.junit.Test; @@ -55,16 +54,18 @@ public class BoolOrEnumConverterTest { @Test public void converterFromEnum() throws Exception { CompilationModeConverter converter = new CompilationModeConverter(); - assertEquals(CompilationMode.DBG, converter.convert("dbg")); - assertEquals(CompilationMode.OPT, converter.convert("opt")); + assertThat(converter.convert("dbg")).isEqualTo(CompilationMode.DBG); + assertThat(converter.convert("opt")).isEqualTo(CompilationMode.OPT); try { converter.convert("none"); fail(); } catch (OptionsParsingException e) { - assertEquals("Not a valid compilation mode: 'none' (should be dbg or opt)", e.getMessage()); + assertThat(e) + .hasMessageThat() + .isEqualTo("Not a valid compilation mode: 'none' (should be dbg or opt)"); } - assertEquals("dbg or opt", converter.getTypeDescription()); + assertThat(converter.getTypeDescription()).isEqualTo("dbg or opt"); } @Test @@ -74,11 +75,11 @@ public class BoolOrEnumConverterTest { CompilationModeConverter converter = new CompilationModeConverter(); for (String falseValue : falseValues) { - assertEquals(CompilationMode.OPT, converter.convert(falseValue)); + assertThat(converter.convert(falseValue)).isEqualTo(CompilationMode.OPT); } for (String trueValue : trueValues) { - assertEquals(CompilationMode.DBG, converter.convert(trueValue)); + assertThat(converter.convert(trueValue)).isEqualTo(CompilationMode.DBG); } } @@ -88,8 +89,8 @@ public class BoolOrEnumConverterTest { parser.parse("--nocompile_mode"); CompilationModeTestOptions options = parser.getOptions(CompilationModeTestOptions.class); - assertNotNull(options.compileMode); - assertEquals(CompilationMode.OPT, options.compileMode); + assertThat(options.compileMode).isNotNull(); + assertThat(options.compileMode).isEqualTo(CompilationMode.OPT); } @Test @@ -98,8 +99,8 @@ public class BoolOrEnumConverterTest { parser.parse("--compile_mode"); CompilationModeTestOptions options = parser.getOptions(CompilationModeTestOptions.class); - assertNotNull(options.compileMode); - assertEquals(CompilationMode.DBG, options.compileMode); + assertThat(options.compileMode).isNotNull(); + assertThat(options.compileMode).isEqualTo(CompilationMode.DBG); } } diff --git a/src/test/java/com/google/devtools/common/options/CommaSeparatedOptionListConverterTest.java b/src/test/java/com/google/devtools/common/options/CommaSeparatedOptionListConverterTest.java index 6d0e053eca..29491921ce 100644 --- a/src/test/java/com/google/devtools/common/options/CommaSeparatedOptionListConverterTest.java +++ b/src/test/java/com/google/devtools/common/options/CommaSeparatedOptionListConverterTest.java @@ -13,20 +13,15 @@ // limitations under the License. package com.google.devtools.common.options; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; +import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * A test for {@link Converters.CommaSeparatedOptionListConverter}. - */ +/** A test for {@link Converters.CommaSeparatedOptionListConverter}. */ @RunWith(JUnit4.class) public class CommaSeparatedOptionListConverterTest { @@ -35,41 +30,40 @@ public class CommaSeparatedOptionListConverterTest { @Test public void emptyStringYieldsEmptyList() throws Exception { - assertEquals(Collections.emptyList(), converter.convert("")); + assertThat(converter.convert("")).isEmpty(); } @Test public void commaTwoEmptyStrings() throws Exception { - assertEquals(Arrays.asList("", ""), converter.convert(",")); + assertThat(converter.convert(",")).containsExactly("", "").inOrder(); } @Test public void leadingCommaYieldsLeadingSpace() throws Exception { - assertEquals(Arrays.asList("", "leading", "comma"), - converter.convert(",leading,comma")); + assertThat(converter.convert(",leading,comma")) + .containsExactly("", "leading", "comma").inOrder(); } @Test public void trailingCommaYieldsTrailingSpace() throws Exception { - assertEquals(Arrays.asList("trailing", "comma", ""), - converter.convert("trailing,comma,")); + assertThat(converter.convert("trailing,comma,")) + .containsExactly("trailing", "comma", "").inOrder(); } @Test public void singleWord() throws Exception { - assertEquals(Arrays.asList("lonely"), converter.convert("lonely")); + assertThat(converter.convert("lonely")).containsExactly("lonely"); } @Test public void multiWords() throws Exception { - assertEquals(Arrays.asList("one", "two", "three"), - converter.convert("one,two,three")); + assertThat(converter.convert("one,two,three")) + .containsExactly("one", "two", "three").inOrder(); } @Test public void spaceIsIgnored() throws Exception { - assertEquals(Arrays.asList("one two three"), - converter.convert("one two three")); + assertThat(converter.convert("one two three")).containsExactly("one two three"); } @Test diff --git a/src/test/java/com/google/devtools/common/options/EnumConverterTest.java b/src/test/java/com/google/devtools/common/options/EnumConverterTest.java index 9ce8ee0985..5c7ab787d8 100644 --- a/src/test/java/com/google/devtools/common/options/EnumConverterTest.java +++ b/src/test/java/com/google/devtools/common/options/EnumConverterTest.java @@ -14,10 +14,8 @@ package com.google.devtools.common.options; +import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.common.options.OptionsParser.newOptionsParser; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.fail; import java.util.List; @@ -46,15 +44,17 @@ public class EnumConverterTest { @Test public void converterForEnumWithTwoValues() throws Exception { CompilationModeConverter converter = new CompilationModeConverter(); - assertEquals(CompilationMode.DBG, converter.convert("dbg")); - assertEquals(CompilationMode.OPT, converter.convert("opt")); + assertThat(converter.convert("dbg")).isEqualTo(CompilationMode.DBG); + assertThat(converter.convert("opt")).isEqualTo(CompilationMode.OPT); try { converter.convert("none"); fail(); } catch(OptionsParsingException e) { - assertEquals("Not a valid compilation mode: 'none' (should be dbg or opt)", e.getMessage()); + assertThat(e) + .hasMessageThat() + .isEqualTo("Not a valid compilation mode: 'none' (should be dbg or opt)"); } - assertEquals("dbg or opt", converter.getTypeDescription()); + assertThat(converter.getTypeDescription()).isEqualTo("dbg or opt"); } private enum Fruit { @@ -72,14 +72,13 @@ public class EnumConverterTest { public void typeDescriptionForEnumWithThreeValues() throws Exception { FruitConverter converter = new FruitConverter(); // We always use lowercase in the user-visible messages: - assertEquals("apple, banana or cherry", - converter.getTypeDescription()); + assertThat(converter.getTypeDescription()).isEqualTo("apple, banana or cherry"); } @Test public void converterIsCaseInsensitive() throws Exception { FruitConverter converter = new FruitConverter(); - assertSame(Fruit.Banana, converter.convert("bAnANa")); + assertThat(converter.convert("bAnANa")).isSameAs(Fruit.Banana); } // Regression test: lists of enum using a subclass of EnumConverter don't work @@ -106,10 +105,10 @@ public class EnumConverterTest { OptionsParser parser = newOptionsParser(EnumListTestOptions.class); parser.parse("--goo=ALPHA", "--goo=BRAVO"); EnumListTestOptions options = parser.getOptions(EnumListTestOptions.class); - assertNotNull(options.goo); - assertEquals(2, options.goo.size()); - assertEquals(AlphabetEnum.ALPHA, options.goo.get(0)); - assertEquals(AlphabetEnum.BRAVO, options.goo.get(1)); + assertThat(options.goo).isNotNull(); + assertThat(options.goo).hasSize(2); + assertThat(options.goo.get(0)).isEqualTo(AlphabetEnum.ALPHA); + assertThat(options.goo.get(1)).isEqualTo(AlphabetEnum.BRAVO); } } diff --git a/src/test/java/com/google/devtools/common/options/GenericTypeHelperTest.java b/src/test/java/com/google/devtools/common/options/GenericTypeHelperTest.java index 00da20a547..0e858c857c 100644 --- a/src/test/java/com/google/devtools/common/options/GenericTypeHelperTest.java +++ b/src/test/java/com/google/devtools/common/options/GenericTypeHelperTest.java @@ -14,7 +14,7 @@ package com.google.devtools.common.options; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import org.junit.Test; import org.junit.runner.RunWith; @@ -52,9 +52,10 @@ public class GenericTypeHelperTest { private static void assertDoIt(Class<?> expected, Class<? extends DoSomething<?>> implementingClass) throws Exception { - assertEquals(expected, - GenericTypeHelper.getActualReturnType(implementingClass, - implementingClass.getMethod("doIt"))); + assertThat( + GenericTypeHelper.getActualReturnType( + implementingClass, implementingClass.getMethod("doIt"))) + .isEqualTo(expected); } @Test diff --git a/src/test/java/com/google/devtools/common/options/LogLevelConverterTest.java b/src/test/java/com/google/devtools/common/options/LogLevelConverterTest.java index 1dbcd40105..67919c7827 100644 --- a/src/test/java/com/google/devtools/common/options/LogLevelConverterTest.java +++ b/src/test/java/com/google/devtools/common/options/LogLevelConverterTest.java @@ -13,20 +13,16 @@ // limitations under the License. package com.google.devtools.common.options; -import static org.junit.Assert.assertEquals; +import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.fail; import com.google.devtools.common.options.Converters.LogLevelConverter; - +import java.util.logging.Level; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; -import java.util.logging.Level; - -/** - * A test for {@link LogLevelConverter}. - */ +/** A test for {@link LogLevelConverter}. */ @RunWith(JUnit4.class) public class LogLevelConverterTest { @@ -36,7 +32,7 @@ public class LogLevelConverterTest { public void convertsIntsToLevels() throws OptionsParsingException { int levelId = 0; for (Level level : LogLevelConverter.LEVELS) { - assertEquals(level, converter.convert(Integer.toString(levelId++))); + assertThat(converter.convert(Integer.toString(levelId++))).isEqualTo(level); } } @@ -46,7 +42,7 @@ public class LogLevelConverterTest { converter.convert("oops - not a number."); fail(); } catch (OptionsParsingException e) { - assertEquals("Not a log level: oops - not a number.", e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("Not a log level: oops - not a number."); } } @@ -58,7 +54,7 @@ public class LogLevelConverterTest { fail(); } catch (OptionsParsingException e) { String expected = "Not a log level: " + Integer.toString(example); - assertEquals(expected, e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo(expected); } } } diff --git a/src/test/java/com/google/devtools/common/options/OptionsDataTest.java b/src/test/java/com/google/devtools/common/options/OptionsDataTest.java index 0066ca3605..ca777ed23e 100644 --- a/src/test/java/com/google/devtools/common/options/OptionsDataTest.java +++ b/src/test/java/com/google/devtools/common/options/OptionsDataTest.java @@ -75,8 +75,7 @@ public class OptionsDataTest { construct(ExampleNameConflictOptions.class); fail("foo should conflict with the previous flag foo"); } catch (DuplicateOptionDeclarationException e) { - assertThat(e.getMessage()).contains( - "Duplicate option name, due to option: --foo"); + assertThat(e).hasMessageThat().contains("Duplicate option name, due to option: --foo"); } } @@ -104,8 +103,7 @@ public class OptionsDataTest { construct(ExampleIntegerFooOptions.class, ExampleBooleanFooOptions.class); fail("foo should conflict with the previous flag foo"); } catch (DuplicateOptionDeclarationException e) { - assertThat(e.getMessage()).contains( - "Duplicate option name, due to option: --foo"); + assertThat(e).hasMessageThat().contains("Duplicate option name, due to option: --foo"); } } @@ -127,9 +125,11 @@ public class OptionsDataTest { fail("nofoo should conflict with the previous flag foo, " + "since foo, as a boolean flag, can be written as --nofoo"); } catch (DuplicateOptionDeclarationException e) { - assertThat(e.getMessage()).contains( - "Duplicate option name, due to option --nofoo, it " - + "conflicts with a negating alias for boolean flag --foo"); + assertThat(e) + .hasMessageThat() + .contains( + "Duplicate option name, due to option --nofoo, it " + + "conflicts with a negating alias for boolean flag --foo"); } try { @@ -137,8 +137,9 @@ public class OptionsDataTest { fail("nofoo should conflict with the previous flag foo, " + "since foo, as a boolean flag, can be written as --nofoo"); } catch (DuplicateOptionDeclarationException e) { - assertThat(e.getMessage()).contains( - "Duplicate option name, due to boolean option alias: --nofoo"); + assertThat(e) + .hasMessageThat() + .contains("Duplicate option name, due to boolean option alias: --nofoo"); } } @@ -161,8 +162,9 @@ public class OptionsDataTest { fail("nofoo should conflict with the previous flag foo, " + "since foo, as a boolean flag, can be written as --nofoo"); } catch (DuplicateOptionDeclarationException e) { - assertThat(e.getMessage()).contains( - "Duplicate option name, due to boolean option alias: --nofoo"); + assertThat(e) + .hasMessageThat() + .contains("Duplicate option name, due to boolean option alias: --nofoo"); } } @@ -185,9 +187,11 @@ public class OptionsDataTest { fail("nofoo, the old name for bar, should conflict with the previous flag foo, " + "since foo, as a boolean flag, can be written as --nofoo"); } catch (DuplicateOptionDeclarationException e) { - assertThat(e.getMessage()).contains( - "Duplicate option name, due to old option name --nofoo, it conflicts with a " - + "negating alias for boolean flag --foo"); + assertThat(e) + .hasMessageThat() + .contains( + "Duplicate option name, due to old option name --nofoo, it conflicts with a " + + "negating alias for boolean flag --foo"); } } diff --git a/src/test/java/com/google/devtools/common/options/OptionsMapConversionTest.java b/src/test/java/com/google/devtools/common/options/OptionsMapConversionTest.java index ea60323abc..8f008007f4 100644 --- a/src/test/java/com/google/devtools/common/options/OptionsMapConversionTest.java +++ b/src/test/java/com/google/devtools/common/options/OptionsMapConversionTest.java @@ -168,9 +168,11 @@ public class OptionsMapConversionTest { OptionsParser.fromMap(SubFooBOptions.class, fieldMap); fail("Should have failed due to the given map's fields not matching the ones on the class"); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).contains( - "Map keys do not match fields of options class; extra map keys: {'a'}; " - + "extra options class options: {'b1', 'b2'}"); + assertThat(e) + .hasMessageThat() + .contains( + "Map keys do not match fields of options class; extra map keys: {'a'}; " + + "extra options class options: {'b1', 'b2'}"); } } @@ -182,8 +184,9 @@ public class OptionsMapConversionTest { OptionsParser.fromMap(FooOptions.class, fieldMap); fail("Should have failed due to trying to assign a field value with the wrong type"); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).matches( - "Can not set boolean field .*\\.foo to java\\.lang\\.Integer"); + assertThat(e) + .hasMessageThat() + .matches("Can not set boolean field .*\\.foo to java\\.lang\\.Integer"); } } diff --git a/src/test/java/com/google/devtools/common/options/OptionsParserTest.java b/src/test/java/com/google/devtools/common/options/OptionsParserTest.java index 3a046a4035..b122aba5b0 100644 --- a/src/test/java/com/google/devtools/common/options/OptionsParserTest.java +++ b/src/test/java/com/google/devtools/common/options/OptionsParserTest.java @@ -17,11 +17,6 @@ package com.google.devtools.common.options; import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.common.options.OptionsParser.newOptionsParser; import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.google.common.collect.ImmutableList; @@ -78,7 +73,7 @@ public class OptionsParserTest { newOptionsParser(BadOptions.class); fail(); } catch (OptionsParser.ConstructionException e) { - assertThat(e.getCause()).isInstanceOf(DuplicateOptionDeclarationException.class); + assertThat(e).hasCauseThat().isInstanceOf(DuplicateOptionDeclarationException.class); } } @@ -196,12 +191,12 @@ public class OptionsParserTest { OptionsParser parser = newOptionsParser(ExampleFoo.class, ExampleBaz.class); parser.parse("--baz=oops", "--bar", "17"); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("defaultFoo", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("defaultFoo"); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("oops", baz.baz); + assertThat(baz.baz).isEqualTo("oops"); } - + @Test public void parseWithParamsFile() throws OptionsParsingException, IOException { // TODO(bazel-team): Switch to an in memory file system, here and below. @@ -216,12 +211,12 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("defaultFoo", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("defaultFoo"); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("oops", baz.baz); + assertThat(baz.baz).isEqualTo("oops"); } - + @Test public void parseWithEmptyParamsFile() throws OptionsParsingException, IOException { // TODO(bazel-team): Switch to an in memory file system, here and below. @@ -236,12 +231,12 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("defaultFoo", foo.foo); - assertEquals(42, foo.bar); + assertThat(foo.foo).isEqualTo("defaultFoo"); + assertThat(foo.bar).isEqualTo(42); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("defaultBaz", baz.baz); + assertThat(baz.baz).isEqualTo("defaultBaz"); } - + @Test public void parseWithParamsFileWithEmptyStringValues() throws Exception { Path params = Files.createTempDirectory("foo").resolve("params"); @@ -255,11 +250,11 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("", foo.foo); + assertThat(foo.foo).isEmpty(); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("", baz.baz); + assertThat(baz.baz).isEmpty(); } - + @Test public void parseWithParamsFileWithEmptyString() throws OptionsParsingException, IOException { // TODO(bazel-team): Switch to an in memory file system, here and below. @@ -274,12 +269,12 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("defaultFoo", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("defaultFoo"); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("", baz.baz); + assertThat(baz.baz).isEmpty(); } - + @Test public void parseWithParamsFileWithEmptyStringAtEnd() throws OptionsParsingException, IOException { @@ -298,10 +293,10 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("defaultFoo", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("defaultFoo"); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("", baz.baz); + assertThat(baz.baz).isEmpty(); } @Test @@ -317,10 +312,10 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("\"fuzzy\nfoo\"", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("\"fuzzy\nfoo\""); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("defaultBaz", baz.baz); + assertThat(baz.baz).isEqualTo("defaultBaz"); } @Test @@ -336,10 +331,10 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("fuzzy\\ foo", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("fuzzy\\ foo"); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("defaultBaz", baz.baz); + assertThat(baz.baz).isEqualTo("defaultBaz"); } @Test @@ -355,10 +350,10 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("\"fuzzy\\\"foo\"", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("\"fuzzy\\\"foo\""); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("defaultBaz", baz.baz); + assertThat(baz.baz).isEqualTo("defaultBaz"); } @Test @@ -376,15 +371,16 @@ public class OptionsParserTest { parser.parse("@" + params); fail(); } catch (OptionsParsingException e) { - assertEquals( - String.format( - ParamsFilePreProcessor.ERROR_MESSAGE_FORMAT, - params, - String.format(ParamsFilePreProcessor.UNFINISHED_QUOTE_MESSAGE_FORMAT, "\"", 6)), - e.getMessage()); + assertThat(e) + .hasMessageThat() + .isEqualTo( + String.format( + ParamsFilePreProcessor.ERROR_MESSAGE_FORMAT, + params, + String.format(ParamsFilePreProcessor.UNFINISHED_QUOTE_MESSAGE_FORMAT, "\"", 6))); } } - + @Test public void parseWithParamsFileWithMultilineStringValues() throws Exception { Path params = Files.createTempDirectory("foo").resolve("params"); @@ -406,12 +402,12 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("hello\\\nworld", foo.foo); - assertEquals("\"hello\nworld\"", foo.nodoc); + assertThat(foo.foo).isEqualTo("hello\\\nworld"); + assertThat(foo.nodoc).isEqualTo("\"hello\nworld\""); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("'hello\nworld'", baz.baz); + assertThat(baz.baz).isEqualTo("'hello\nworld'"); } - + @Test public void parseWithParamsFileWithMultilineStringValuesCRLF() throws Exception { Path params = Files.createTempDirectory("foo").resolve("params"); @@ -427,10 +423,10 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("'hello\nworld'", baz.baz); + assertThat(baz.baz).isEqualTo("'hello\nworld'"); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("hello\\\nworld", foo.foo); - assertEquals("\"hello\nworld\"", foo.nodoc); + assertThat(foo.foo).isEqualTo("hello\\\nworld"); + assertThat(foo.nodoc).isEqualTo("\"hello\nworld\""); } @Test @@ -447,10 +443,10 @@ public class OptionsParserTest { parser.enableParamsFileSupport(FileSystems.getDefault()); parser.parse("@" + params); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("defaultFoo", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("defaultFoo"); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("oops", baz.baz); + assertThat(baz.baz).isEqualTo("oops"); } @Test @@ -462,9 +458,9 @@ public class OptionsParserTest { parser.parse(unknownOpts); fail(); } catch (OptionsParsingException e) { - assertEquals("@does/not/exist", e.getInvalidArgument()); - assertNotNull(parser.getOptions(ExampleFoo.class)); - assertNotNull(parser.getOptions(ExampleBaz.class)); + assertThat(e.getInvalidArgument()).isEqualTo("@does/not/exist"); + assertThat(parser.getOptions(ExampleFoo.class)).isNotNull(); + assertThat(parser.getOptions(ExampleBaz.class)).isNotNull(); } } @@ -488,10 +484,10 @@ public class OptionsParserTest { parser.parse("--unknown", "option"); fail(); } catch (OptionsParsingException e) { - assertEquals("--unknown", e.getInvalidArgument()); - assertEquals("Unrecognized option: --unknown", e.getMessage()); + assertThat(e.getInvalidArgument()).isEqualTo("--unknown"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --unknown"); } - assertEquals(Collections.<String>emptyList(), parser.getResidue()); + assertThat(parser.getResidue()).isEmpty(); } @Test @@ -506,10 +502,10 @@ public class OptionsParserTest { parser.setAllowSingleDashLongOptions(true); parser.parse("-baz=oops", "-bar", "17"); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("defaultFoo", foo.foo); - assertEquals(17, foo.bar); + assertThat(foo.foo).isEqualTo("defaultFoo"); + assertThat(foo.bar).isEqualTo(17); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("oops", baz.baz); + assertThat(baz.baz).isEqualTo("oops"); } @Test @@ -520,10 +516,10 @@ public class OptionsParserTest { parser.parse(unknownOpts); fail(); } catch (OptionsParsingException e) { - assertEquals("--unknown", e.getInvalidArgument()); - assertEquals("Unrecognized option: --unknown", e.getMessage()); - assertNotNull(parser.getOptions(ExampleFoo.class)); - assertNotNull(parser.getOptions(ExampleBaz.class)); + assertThat(e.getInvalidArgument()).isEqualTo("--unknown"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --unknown"); + assertThat(parser.getOptions(ExampleFoo.class)).isNotNull(); + assertThat(parser.getOptions(ExampleBaz.class)).isNotNull(); } } @@ -535,9 +531,9 @@ public class OptionsParserTest { parser.parse(internalOpts); fail(); } catch (OptionsParsingException e) { - assertEquals("--internal_boolean", e.getInvalidArgument()); - assertEquals("Unrecognized option: --internal_boolean", e.getMessage()); - assertNotNull(parser.getOptions(ExampleInternalOptions.class)); + assertThat(e.getInvalidArgument()).isEqualTo("--internal_boolean"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --internal_boolean"); + assertThat(parser.getOptions(ExampleInternalOptions.class)).isNotNull(); } } @@ -549,9 +545,9 @@ public class OptionsParserTest { parser.parse(internalOpts); fail(); } catch (OptionsParsingException e) { - assertEquals("--nointernal_boolean", e.getInvalidArgument()); - assertEquals("Unrecognized option: --nointernal_boolean", e.getMessage()); - assertNotNull(parser.getOptions(ExampleInternalOptions.class)); + assertThat(e.getInvalidArgument()).isEqualTo("--nointernal_boolean"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --nointernal_boolean"); + assertThat(parser.getOptions(ExampleInternalOptions.class)).isNotNull(); } } @@ -560,7 +556,8 @@ public class OptionsParserTest { OptionsParser parser = newOptionsParser(ExampleInternalOptions.class); List<String> spacedOpts = asList("--public string=value with spaces"); parser.parse(spacedOpts); - assertEquals("value with spaces", parser.getOptions(ExampleInternalOptions.class).publicString); + assertThat(parser.getOptions(ExampleInternalOptions.class).publicString) + .isEqualTo("value with spaces"); } @Test @@ -571,9 +568,9 @@ public class OptionsParserTest { parser.parse(internalOpts); fail("parsing should have failed for including a private option"); } catch (OptionsParsingException e) { - assertEquals("--internal_string=any_value", e.getInvalidArgument()); - assertEquals("Unrecognized option: --internal_string=any_value", e.getMessage()); - assertNotNull(parser.getOptions(ExampleInternalOptions.class)); + assertThat(e.getInvalidArgument()).isEqualTo("--internal_string=any_value"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --internal_string=any_value"); + assertThat(parser.getOptions(ExampleInternalOptions.class)).isNotNull(); } } @@ -585,9 +582,9 @@ public class OptionsParserTest { parser.parse(internalOpts); fail("parsing should have failed for including a private option"); } catch (OptionsParsingException e) { - assertEquals("--internal_string", e.getInvalidArgument()); - assertEquals("Unrecognized option: --internal_string", e.getMessage()); - assertNotNull(parser.getOptions(ExampleInternalOptions.class)); + assertThat(e.getInvalidArgument()).isEqualTo("--internal_string"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --internal_string"); + assertThat(parser.getOptions(ExampleInternalOptions.class)).isNotNull(); } } @@ -599,10 +596,10 @@ public class OptionsParserTest { parser.parse(opts); fail(); } catch (OptionsParsingException e) { - assertEquals("--unknown", e.getInvalidArgument()); - assertEquals("Unrecognized option: --unknown", e.getMessage()); - assertNotNull(parser.getOptions(ExampleFoo.class)); - assertNotNull(parser.getOptions(ExampleBaz.class)); + assertThat(e.getInvalidArgument()).isEqualTo("--unknown"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --unknown"); + assertThat(parser.getOptions(ExampleFoo.class)).isNotNull(); + assertThat(parser.getOptions(ExampleBaz.class)).isNotNull(); } } @@ -614,7 +611,7 @@ public class OptionsParserTest { parser.parse("--boom="); ExampleBoom boom = parser.getOptions(ExampleBoom.class); // The converted value is intentionally null since boom uses the EmptyToNullStringConverter - assertNull(boom.boom); + assertThat(boom.boom).isNull(); } public static class CategoryTest extends OptionsBase { @@ -636,22 +633,20 @@ public class OptionsParserTest { public void getOptionsAndGetResidueWithNoCallToParse() { // With no call to parse(), all options are at default values, and there's // no reside. - assertEquals("defaultFoo", - newOptionsParser(ExampleFoo.class). - getOptions(ExampleFoo.class).foo); - assertEquals(Collections.<String>emptyList(), - newOptionsParser(ExampleFoo.class).getResidue()); + assertThat(newOptionsParser(ExampleFoo.class).getOptions(ExampleFoo.class).foo) + .isEqualTo("defaultFoo"); + assertThat(newOptionsParser(ExampleFoo.class).getResidue()).isEmpty(); } @Test public void parserCanBeCalledRepeatedly() throws OptionsParsingException { OptionsParser parser = newOptionsParser(ExampleFoo.class); parser.parse("--foo", "foo1"); - assertEquals("foo1", parser.getOptions(ExampleFoo.class).foo); + assertThat(parser.getOptions(ExampleFoo.class).foo).isEqualTo("foo1"); parser.parse(); - assertEquals("foo1", parser.getOptions(ExampleFoo.class).foo); // no change + assertThat(parser.getOptions(ExampleFoo.class).foo).isEqualTo("foo1"); // no change parser.parse("--foo", "foo2"); - assertEquals("foo2", parser.getOptions(ExampleFoo.class).foo); // updated + assertThat(parser.getOptions(ExampleFoo.class).foo).isEqualTo("foo2"); // updated } @Test @@ -677,10 +672,10 @@ public class OptionsParserTest { parser.parse("--foo", "well", "--baz", "here", "--", "--bar", "ignore"); ExampleFoo foo = parser.getOptions(ExampleFoo.class); ExampleBaz baz = parser.getOptions(ExampleBaz.class); - assertEquals("well", foo.foo); - assertEquals("here", baz.baz); - assertEquals(42, foo.bar); // the default! - assertEquals(asList("--bar", "ignore"), parser.getResidue()); + assertThat(foo.foo).isEqualTo("well"); + assertThat(baz.baz).isEqualTo("here"); + assertThat(foo.bar).isEqualTo(42); // the default! + assertThat(parser.getResidue()).containsExactly("--bar", "ignore").inOrder(); } @Test @@ -691,7 +686,7 @@ public class OptionsParserTest { parser.parse("residue", "is", "not", "OK"); fail(); } catch (OptionsParsingException e) { - assertEquals("Unrecognized arguments: residue is not OK", e.getMessage()); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized arguments: residue is not OK"); } } @@ -702,9 +697,9 @@ public class OptionsParserTest { parser.parse("--foo", "one", "--bar", "43", "unknown1"); parser.parse("--foo", "two", "unknown2"); ExampleFoo foo = parser.getOptions(ExampleFoo.class); - assertEquals("two", foo.foo); // second call takes precedence - assertEquals(43, foo.bar); - assertEquals(Arrays.asList("unknown1", "unknown2"), parser.getResidue()); + assertThat(foo.foo).isEqualTo("two"); // second call takes precedence + assertThat(foo.bar).isEqualTo(43); + assertThat(parser.getResidue()).containsExactly("unknown1", "unknown2").inOrder(); } // Regression test for a subtle bug! The toString of each options interface @@ -740,8 +735,8 @@ public class OptionsParserTest { public void toStringIsIndependentOfExplicitCommandLineOptions() throws Exception { ExampleFoo foo1 = Options.parse(ExampleFoo.class).getOptions(); ExampleFoo foo2 = Options.parse(ExampleFoo.class, "--bar", "42").getOptions(); - assertEquals(foo1, foo2); - assertEquals(foo1.toString(), foo2.toString()); + assertThat(foo2).isEqualTo(foo1); + assertThat(foo2.toString()).isEqualTo(foo1.toString()); Map<String, Object> expectedMap = new ImmutableMap.Builder<String, Object>(). put("bing", Collections.emptyList()). @@ -750,8 +745,8 @@ public class OptionsParserTest { put("bang", Collections.emptyList()). put("foo", "defaultFoo").build(); - assertEquals(expectedMap, foo1.asMap()); - assertEquals(expectedMap, foo2.asMap()); + assertThat(foo1.asMap()).isEqualTo(expectedMap); + assertThat(foo2.asMap()).isEqualTo(expectedMap); } // Regression test for yet another subtle bug! The inherited options weren't @@ -788,8 +783,8 @@ public class OptionsParserTest { @Test public void assertDefaultStringsForCustomOptions() throws OptionsParsingException { CustomOptions options = Options.parse(CustomOptions.class).getOptions(); - assertEquals("simple default", options.simple); - assertEquals("multipart default", options.multipartName); + assertThat(options.simple).isEqualTo("simple default"); + assertThat(options.multipartName).isEqualTo("multipart default"); } public static class NullTestOptions extends OptionsBase { @@ -801,7 +796,7 @@ public class OptionsParserTest { @Test public void defaultNullStringGivesNull() throws Exception { NullTestOptions options = Options.parse(NullTestOptions.class).getOptions(); - assertNull(options.simple); + assertThat(options.simple).isNull(); } public static class ImplicitDependencyOptions extends OptionsBase { @@ -824,9 +819,9 @@ public class OptionsParserTest { public void implicitDependencyHasImplicitDependency() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(ImplicitDependencyOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--first=first")); - assertEquals("first", parser.getOptions(ImplicitDependencyOptions.class).first); - assertEquals("second", parser.getOptions(ImplicitDependencyOptions.class).second); - assertEquals("third", parser.getOptions(ImplicitDependencyOptions.class).third); + assertThat(parser.getOptions(ImplicitDependencyOptions.class).first).isEqualTo("first"); + assertThat(parser.getOptions(ImplicitDependencyOptions.class).second).isEqualTo("second"); + assertThat(parser.getOptions(ImplicitDependencyOptions.class).third).isEqualTo("third"); } public static class BadImplicitDependencyOptions extends OptionsBase { @@ -893,7 +888,8 @@ public class OptionsParserTest { newOptionsParser(ConflictingExpansionsOptions.class); fail("Should have failed due to specifying both expansion and expansionFunction"); } catch (AssertionError e) { - assertThat(e.getMessage()) + assertThat(e) + .hasMessageThat() .contains("Cannot set both expansion and expansionFunction for " + "option --badness"); } } @@ -921,8 +917,8 @@ public class OptionsParserTest { newOptionsParser(NullExpansionsOptions.class); fail("Should have failed due to null expansion function result"); } catch (OptionsParser.ConstructionException e) { - assertThat(e.getCause()).isInstanceOf(NullPointerException.class); - assertThat(e.getCause().getMessage()).contains("null value in entry"); + assertThat(e).hasCauseThat().isInstanceOf(NullPointerException.class); + assertThat(e).hasCauseThat().hasMessageThat().contains("null value in entry"); } } @@ -967,8 +963,8 @@ public class OptionsParserTest { parser.parse( OptionPriority.COMMAND_LINE, null, Arrays.asList("--expands", "--underlying=direct_value")); ExpansionOptions options = parser.getOptions(ExpansionOptions.class); - assertEquals("direct_value", options.underlying); - assertEquals(0, parser.getWarnings().size()); + assertThat(options.underlying).isEqualTo("direct_value"); + assertThat(parser.getWarnings()).isEmpty(); } @Test @@ -977,25 +973,25 @@ public class OptionsParserTest { parser.parse( OptionPriority.COMMAND_LINE, null, Arrays.asList("--underlying=direct_value", "--expands")); ExpansionOptions options = parser.getOptions(ExpansionOptions.class); - assertEquals("from_expansion", options.underlying); + assertThat(options.underlying).isEqualTo("from_expansion"); } @Test public void overrideWithHigherPriority() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(NullTestOptions.class); parser.parse(OptionPriority.RC_FILE, null, Arrays.asList("--simple=a")); - assertEquals("a", parser.getOptions(NullTestOptions.class).simple); + assertThat(parser.getOptions(NullTestOptions.class).simple).isEqualTo("a"); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--simple=b")); - assertEquals("b", parser.getOptions(NullTestOptions.class).simple); + assertThat(parser.getOptions(NullTestOptions.class).simple).isEqualTo("b"); } @Test public void overrideWithLowerPriority() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(NullTestOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--simple=a")); - assertEquals("a", parser.getOptions(NullTestOptions.class).simple); + assertThat(parser.getOptions(NullTestOptions.class).simple).isEqualTo("a"); parser.parse(OptionPriority.RC_FILE, null, Arrays.asList("--simple=b")); - assertEquals("a", parser.getOptions(NullTestOptions.class).simple); + assertThat(parser.getOptions(NullTestOptions.class).simple).isEqualTo("a"); } @Test @@ -1012,7 +1008,7 @@ public class OptionsParserTest { @Test public void getOptionValueDescriptionWithoutValue() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(NullTestOptions.class); - assertNull(parser.getOptionValueDescription("simple")); + assertThat(parser.getOptionValueDescription("simple")).isNull(); } @Test @@ -1021,15 +1017,15 @@ public class OptionsParserTest { parser.parse(OptionPriority.COMMAND_LINE, "my description", Arrays.asList("--simple=abc")); OptionValueDescription result = parser.getOptionValueDescription("simple"); - assertNotNull(result); - assertEquals("simple", result.getName()); - assertEquals("abc", result.getValue()); - assertEquals(OptionPriority.COMMAND_LINE, result.getPriority()); - assertEquals("my description", result.getSource()); - assertNull(result.getImplicitDependant()); - assertFalse(result.isImplicitDependency()); - assertNull(result.getExpansionParent()); - assertFalse(result.isExpansion()); + assertThat(result).isNotNull(); + assertThat(result.getName()).isEqualTo("simple"); + assertThat(result.getValue()).isEqualTo("abc"); + assertThat(result.getPriority()).isEqualTo(OptionPriority.COMMAND_LINE); + assertThat(result.getSource()).isEqualTo("my description"); + assertThat(result.getImplicitDependant()).isNull(); + assertThat(result.isImplicitDependency()).isFalse(); + assertThat(result.getExpansionParent()).isNull(); + assertThat(result.isExpansion()).isFalse(); } public static class ImplicitDependencyWarningOptions extends OptionsBase { @@ -1116,30 +1112,30 @@ public class OptionsParserTest { public void deprecationWarning() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(WarningOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--first")); - assertEquals(Arrays.asList("Option 'first' is deprecated"), parser.getWarnings()); + assertThat(parser.getWarnings()).isEqualTo(Arrays.asList("Option 'first' is deprecated")); } @Test public void deprecationWarningForListOption() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(WarningOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--second=a")); - assertEquals(Arrays.asList("Option 'second' is deprecated"), parser.getWarnings()); + assertThat(parser.getWarnings()).isEqualTo(Arrays.asList("Option 'second' is deprecated")); } @Test public void deprecationWarningForExpansionOption() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(WarningOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--third")); - assertEquals(Arrays.asList("Option 'third' is deprecated"), parser.getWarnings()); - assertTrue(parser.getOptions(WarningOptions.class).fourth); + assertThat(parser.getWarnings()).isEqualTo(Arrays.asList("Option 'third' is deprecated")); + assertThat(parser.getOptions(WarningOptions.class).fourth).isTrue(); } @Test public void deprecationWarningForAbbreviatedExpansionOption() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(WarningOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("-t")); - assertEquals(Arrays.asList("Option 'third' is deprecated"), parser.getWarnings()); - assertTrue(parser.getOptions(WarningOptions.class).fourth); + assertThat(parser.getWarnings()).isEqualTo(Arrays.asList("Option 'third' is deprecated")); + assertThat(parser.getOptions(WarningOptions.class).fourth).isTrue(); } public static class NewWarningOptions extends OptionsBase { @@ -1169,24 +1165,25 @@ public class OptionsParserTest { public void newDeprecationWarning() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(NewWarningOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--first")); - assertEquals(Arrays.asList("Option 'first' is deprecated: it's gone"), parser.getWarnings()); + assertThat(parser.getWarnings()) + .isEqualTo(Arrays.asList("Option 'first' is deprecated: it's gone")); } @Test public void newDeprecationWarningForListOption() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(NewWarningOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--second=a")); - assertEquals(Arrays.asList("Option 'second' is deprecated: sorry, no replacement"), - parser.getWarnings()); + assertThat(parser.getWarnings()) + .isEqualTo(Arrays.asList("Option 'second' is deprecated: sorry, no replacement")); } @Test public void newDeprecationWarningForExpansionOption() throws Exception { OptionsParser parser = OptionsParser.newOptionsParser(NewWarningOptions.class); parser.parse(OptionPriority.COMMAND_LINE, null, Arrays.asList("--third")); - assertEquals(Arrays.asList("Option 'third' is deprecated: use --forth instead"), - parser.getWarnings()); - assertTrue(parser.getOptions(NewWarningOptions.class).fourth); + assertThat(parser.getWarnings()) + .isEqualTo(Arrays.asList("Option 'third' is deprecated: use --forth instead")); + assertThat(parser.getOptions(NewWarningOptions.class).fourth).isTrue(); } public static class ExpansionWarningOptions extends OptionsBase { @@ -1233,7 +1230,7 @@ public class OptionsParserTest { // in the code. @Test public void optionPrioritiesAreCorrectlyOrdered() throws Exception { - assertEquals(6, OptionPriority.values().length); + assertThat(OptionPriority.values()).hasLength(6); assertThat(OptionPriority.DEFAULT).isLessThan(OptionPriority.COMPUTED_DEFAULT); assertThat(OptionPriority.COMPUTED_DEFAULT).isLessThan(OptionPriority.RC_FILE); assertThat(OptionPriority.RC_FILE).isLessThan(OptionPriority.COMMAND_LINE); @@ -1280,29 +1277,29 @@ public class OptionsParserTest { parser.parse(OptionPriority.COMMAND_LINE, "source", Arrays.asList("--alpha=one", "--gamma=two", "--echo=three")); List<UnparsedOptionValueDescription> result = parser.asListOfUnparsedOptions(); - assertNotNull(result); - assertEquals(3, result.size()); + assertThat(result).isNotNull(); + assertThat(result).hasSize(3); - assertEquals("alpha", result.get(0).getName()); - assertEquals(true, result.get(0).isDocumented()); - assertEquals(false, result.get(0).isHidden()); - assertEquals("one", result.get(0).getUnparsedValue()); - assertEquals("source", result.get(0).getSource()); - assertEquals(OptionPriority.COMMAND_LINE, result.get(0).getPriority()); + assertThat(result.get(0).getName()).isEqualTo("alpha"); + assertThat(result.get(0).isDocumented()).isTrue(); + assertThat(result.get(0).isHidden()).isFalse(); + assertThat(result.get(0).getUnparsedValue()).isEqualTo("one"); + assertThat(result.get(0).getSource()).isEqualTo("source"); + assertThat(result.get(0).getPriority()).isEqualTo(OptionPriority.COMMAND_LINE); - assertEquals("gamma", result.get(1).getName()); - assertEquals(false, result.get(1).isDocumented()); - assertEquals(false, result.get(1).isHidden()); - assertEquals("two", result.get(1).getUnparsedValue()); - assertEquals("source", result.get(1).getSource()); - assertEquals(OptionPriority.COMMAND_LINE, result.get(1).getPriority()); + assertThat(result.get(1).getName()).isEqualTo("gamma"); + assertThat(result.get(1).isDocumented()).isFalse(); + assertThat(result.get(1).isHidden()).isFalse(); + assertThat(result.get(1).getUnparsedValue()).isEqualTo("two"); + assertThat(result.get(1).getSource()).isEqualTo("source"); + assertThat(result.get(1).getPriority()).isEqualTo(OptionPriority.COMMAND_LINE); - assertEquals("echo", result.get(2).getName()); - assertEquals(false, result.get(2).isDocumented()); - assertEquals(true, result.get(2).isHidden()); - assertEquals("three", result.get(2).getUnparsedValue()); - assertEquals("source", result.get(2).getSource()); - assertEquals(OptionPriority.COMMAND_LINE, result.get(2).getPriority()); + assertThat(result.get(2).getName()).isEqualTo("echo"); + assertThat(result.get(2).isDocumented()).isFalse(); + assertThat(result.get(2).isHidden()).isTrue(); + assertThat(result.get(2).getUnparsedValue()).isEqualTo("three"); + assertThat(result.get(2).getSource()).isEqualTo("source"); + assertThat(result.get(2).getPriority()).isEqualTo(OptionPriority.COMMAND_LINE); } @Test @@ -1311,30 +1308,30 @@ public class OptionsParserTest { parser.parse(OptionPriority.COMMAND_LINE, "source", Arrays.asList("--alpha=one", "--gamma=two")); List<UnparsedOptionValueDescription> result = parser.asListOfExplicitOptions(); - assertNotNull(result); - assertEquals(2, result.size()); + assertThat(result).isNotNull(); + assertThat(result).hasSize(2); - assertEquals("alpha", result.get(0).getName()); - assertEquals(true, result.get(0).isDocumented()); - assertEquals("one", result.get(0).getUnparsedValue()); - assertEquals("source", result.get(0).getSource()); - assertEquals(OptionPriority.COMMAND_LINE, result.get(0).getPriority()); + assertThat(result.get(0).getName()).isEqualTo("alpha"); + assertThat(result.get(0).isDocumented()).isTrue(); + assertThat(result.get(0).getUnparsedValue()).isEqualTo("one"); + assertThat(result.get(0).getSource()).isEqualTo("source"); + assertThat(result.get(0).getPriority()).isEqualTo(OptionPriority.COMMAND_LINE); - assertEquals("gamma", result.get(1).getName()); - assertEquals(false, result.get(1).isDocumented()); - assertEquals("two", result.get(1).getUnparsedValue()); - assertEquals("source", result.get(1).getSource()); - assertEquals(OptionPriority.COMMAND_LINE, result.get(1).getPriority()); + assertThat(result.get(1).getName()).isEqualTo("gamma"); + assertThat(result.get(1).isDocumented()).isFalse(); + assertThat(result.get(1).getUnparsedValue()).isEqualTo("two"); + assertThat(result.get(1).getSource()).isEqualTo("source"); + assertThat(result.get(1).getPriority()).isEqualTo(OptionPriority.COMMAND_LINE); } private void assertOptionValue(String expectedName, Object expectedValue, OptionPriority expectedPriority, String expectedSource, OptionValueDescription actual) { - assertNotNull(actual); - assertEquals(expectedName, actual.getName()); - assertEquals(expectedValue, actual.getValue()); - assertEquals(expectedPriority, actual.getPriority()); - assertEquals(expectedSource, actual.getSource()); + assertThat(actual).isNotNull(); + assertThat(actual.getName()).isEqualTo(expectedName); + assertThat(actual.getValue()).isEqualTo(expectedValue); + assertThat(actual.getPriority()).isEqualTo(expectedPriority); + assertThat(actual.getSource()).isEqualTo(expectedSource); } @Test @@ -1343,8 +1340,8 @@ public class OptionsParserTest { parser.parse(OptionPriority.COMMAND_LINE, "source", Arrays.asList("--alpha=one", "--gamma=two")); List<OptionValueDescription> result = parser.asListOfEffectiveOptions(); - assertNotNull(result); - assertEquals(5, result.size()); + assertThat(result).isNotNull(); + assertThat(result).hasSize(5); HashMap<String,OptionValueDescription> map = new HashMap<String,OptionValueDescription>(); for (OptionValueDescription description : result) { map.put(description.getName(), description); @@ -1377,7 +1374,7 @@ public class OptionsParserTest { OptionsParser parser = OptionsParser.newOptionsParser(ListExample.class); parser.parse(OptionPriority.COMMAND_LINE, "a", Arrays.asList("--alpha=two")); parser.parse(OptionPriority.RC_FILE, "b", Arrays.asList("--alpha=one")); - assertEquals(Arrays.asList("one", "two"), parser.getOptions(ListExample.class).alpha); + assertThat(parser.getOptions(ListExample.class).alpha).isEqualTo(Arrays.asList("one", "two")); } public static class CommaSeparatedOptionsExample extends OptionsBase { @@ -1393,8 +1390,8 @@ public class OptionsParserTest { OptionsParser parser = OptionsParser.newOptionsParser(CommaSeparatedOptionsExample.class); parser.parse(OptionPriority.COMMAND_LINE, "a", Arrays.asList("--alpha=one", "--alpha=two,three")); - assertEquals(Arrays.asList("one", "two", "three"), - parser.getOptions(CommaSeparatedOptionsExample.class).alpha); + assertThat(parser.getOptions(CommaSeparatedOptionsExample.class).alpha) + .isEqualTo(Arrays.asList("one", "two", "three")); } public static class IllegalListTypeExample extends OptionsBase { @@ -1464,60 +1461,61 @@ public class OptionsParserTest { @Test public void canonicalizeEasy() throws Exception { - assertEquals(Arrays.asList("--a=x"), canonicalize(Yesterday.class, "--a=x")); + assertThat(canonicalize(Yesterday.class, "--a=x")).containsExactly("--a=x"); } @Test public void canonicalizeSkipDuplicate() throws Exception { - assertEquals(Arrays.asList("--a=x"), canonicalize(Yesterday.class, "--a=y", "--a=x")); + assertThat(canonicalize(Yesterday.class, "--a=y", "--a=x")).containsExactly("--a=x"); } @Test public void canonicalizeExpands() throws Exception { - assertEquals(Arrays.asList("--a=0"), canonicalize(Yesterday.class, "--c")); + assertThat(canonicalize(Yesterday.class, "--c")).containsExactly("--a=0"); } @Test public void canonicalizeExpansionOverridesExplicit() throws Exception { - assertEquals(Arrays.asList("--a=0"), canonicalize(Yesterday.class, "--a=x", "--c")); + assertThat(canonicalize(Yesterday.class, "--a=x", "--c")).containsExactly("--a=0"); } @Test public void canonicalizeExplicitOverridesExpansion() throws Exception { - assertEquals(Arrays.asList("--a=x"), canonicalize(Yesterday.class, "--c", "--a=x")); + assertThat(canonicalize(Yesterday.class, "--c", "--a=x")).containsExactly("--a=x"); } @Test public void canonicalizeSorts() throws Exception { - assertEquals(Arrays.asList("--a=x", "--b=y"), canonicalize(Yesterday.class, "--b=y", "--a=x")); + assertThat(canonicalize(Yesterday.class, "--b=y", "--a=x")) + .containsExactly("--a=x", "--b=y").inOrder(); } @Test public void canonicalizeImplicitDepsAtEnd() throws Exception { - assertEquals(Arrays.asList("--a=x", "--e=y"), canonicalize(Yesterday.class, "--e=y", "--a=x")); + assertThat(canonicalize(Yesterday.class, "--e=y", "--a=x")) + .isEqualTo(Arrays.asList("--a=x", "--e=y")); } @Test public void canonicalizeImplicitDepsSkipsDuplicate() throws Exception { - assertEquals(Arrays.asList("--e=y"), canonicalize(Yesterday.class, "--e=x", "--e=y")); + assertThat(canonicalize(Yesterday.class, "--e=x", "--e=y")).containsExactly("--e=y"); } @Test public void canonicalizeDoesNotSortImplicitDeps() throws Exception { - assertEquals(Arrays.asList("--a=x", "--f=z", "--e=y"), - canonicalize(Yesterday.class, "--f=z", "--e=y", "--a=x")); + assertThat(canonicalize(Yesterday.class, "--f=z", "--e=y", "--a=x")) + .containsExactly("--a=x", "--f=z", "--e=y").inOrder(); } @Test public void canonicalizeDoesNotSkipAllowMultiple() throws Exception { - assertEquals(Arrays.asList("--d=a", "--d=b"), - canonicalize(Yesterday.class, "--d=a", "--d=b")); + assertThat(canonicalize(Yesterday.class, "--d=a", "--d=b")) + .containsExactly("--d=a", "--d=b").inOrder(); } @Test public void canonicalizeReplacesAbbrevWithName() throws Exception { - assertEquals(Arrays.asList("--g=1"), - canonicalize(Yesterday.class, "-h")); + assertThat(canonicalize(Yesterday.class, "-h")).containsExactly("--g=1"); } public static class LongValueExample extends OptionsBase { @@ -1535,12 +1533,12 @@ public class OptionsParserTest { OptionsParser parser = newOptionsParser(LongValueExample.class); parser.parse(""); LongValueExample result = parser.getOptions(LongValueExample.class); - assertEquals(2147483648L, result.longval); - assertEquals(2147483647, result.intval); + assertThat(result.longval).isEqualTo(2147483648L); + assertThat(result.intval).isEqualTo(2147483647); parser.parse("--longval", Long.toString(Long.MIN_VALUE)); result = parser.getOptions(LongValueExample.class); - assertEquals(Long.MIN_VALUE, result.longval); + assertThat(result.longval).isEqualTo(Long.MIN_VALUE); try { parser.parse("--intval=2147483648"); @@ -1550,7 +1548,7 @@ public class OptionsParserTest { parser.parse("--longval", "100"); result = parser.getOptions(LongValueExample.class); - assertEquals(100, result.longval); + assertThat(result.longval).isEqualTo(100); } public static class OldNameExample extends OptionsBase { @@ -1565,21 +1563,21 @@ public class OptionsParserTest { OptionsParser parser = newOptionsParser(OldNameExample.class); parser.parse("--old_name=foo"); OldNameExample result = parser.getOptions(OldNameExample.class); - assertEquals("foo", result.flag); + assertThat(result.flag).isEqualTo("foo"); // Should also work by its new name. parser = newOptionsParser(OldNameExample.class); parser.parse("--new_name=foo"); result = parser.getOptions(OldNameExample.class); - assertEquals("foo", result.flag); + assertThat(result.flag).isEqualTo("foo"); // Should be no warnings if the new name is used. assertThat(parser.getWarnings()).isEmpty(); } @Test public void testOldNameCanonicalization() throws Exception { - assertEquals( - Arrays.asList("--new_name=foo"), canonicalize(OldNameExample.class, "--old_name=foo")); + assertThat(canonicalize(OldNameExample.class, "--old_name=foo")) + .containsExactly("--new_name=foo"); } public static class ExampleBooleanFooOptions extends OptionsBase { @@ -1621,9 +1619,9 @@ public class OptionsParserTest { OptionsParser parser = newOptionsParser(WrapperOptionExample.class); parser.parse("--wrapper=--flag1=true", "--wrapper=--flag2=87", "--wrapper=--flag3=bar"); WrapperOptionExample result = parser.getOptions(WrapperOptionExample.class); - assertEquals(true, result.flag1); - assertEquals(87, result.flag2); - assertEquals("bar", result.flag3); + assertThat(result.flag1).isTrue(); + assertThat(result.flag2).isEqualTo(87); + assertThat(result.flag3).isEqualTo("bar"); } @Test @@ -1634,7 +1632,7 @@ public class OptionsParserTest { fail(); } catch (OptionsParsingException e) { // Check that the message looks like it's suggesting the correct format. - assertThat(e.getMessage()).contains("--foo"); + assertThat(e).hasMessageThat().contains("--foo"); } } @@ -1642,7 +1640,7 @@ public class OptionsParserTest { public void testWrapperCanonicalization() throws OptionsParsingException { List<String> canonicalized = canonicalize(WrapperOptionExample.class, "--wrapper=--flag1=true", "--wrapper=--flag2=87", "--wrapper=--flag3=bar"); - assertEquals(Arrays.asList("--flag1=true", "--flag2=87", "--flag3=bar"), canonicalized); + assertThat(canonicalized).isEqualTo(Arrays.asList("--flag1=true", "--flag2=87", "--flag3=bar")); } /** Dummy options that declares it uses only core types. */ @@ -1716,9 +1714,11 @@ public class OptionsParserTest { OptionsParser.getUsesOnlyCoreTypes(BadCoreTypesOptions.class); fail("Should have detected illegal use of @UsesOnlyCoreTypes"); } catch (OptionsParser.ConstructionException expected) { - assertThat(expected.getMessage()).matches( - "Options class '.*BadCoreTypesOptions' is marked as @UsesOnlyCoreTypes, but field " - + "'foo' has type '.*Foo'"); + assertThat(expected) + .hasMessageThat() + .matches( + "Options class '.*BadCoreTypesOptions' is marked as @UsesOnlyCoreTypes, but field " + + "'foo' has type '.*Foo'"); } } @@ -1729,9 +1729,11 @@ public class OptionsParserTest { fail("Should have detected illegal use of @UsesOnlyCoreTypes " + "(due to inheritance from bad superclass)"); } catch (OptionsParser.ConstructionException expected) { - assertThat(expected.getMessage()).matches( - "Options class '.*InheritedBadCoreTypesOptions' is marked as @UsesOnlyCoreTypes, but " - + "field 'foo' has type '.*Foo'"); + assertThat(expected) + .hasMessageThat() + .matches( + "Options class '.*InheritedBadCoreTypesOptions' is marked as @UsesOnlyCoreTypes, but " + + "field 'foo' has type '.*Foo'"); } } @@ -1781,4 +1783,3 @@ public class OptionsParserTest { assertThat(data1).isEqualTo(data2); } } - diff --git a/src/test/java/com/google/devtools/common/options/OptionsTest.java b/src/test/java/com/google/devtools/common/options/OptionsTest.java index f6c75d5086..24b435f614 100644 --- a/src/test/java/com/google/devtools/common/options/OptionsTest.java +++ b/src/test/java/com/google/devtools/common/options/OptionsTest.java @@ -115,9 +115,9 @@ public class OptionsTest { assertThat(webFlags.host).isEqualTo("www.google.com"); assertThat(webFlags.port).isEqualTo(80); - assertThat(webFlags.isDebugging).isEqualTo(false); + assertThat(webFlags.isDebugging).isFalse(); assertThat(webFlags.triState).isEqualTo(TriState.AUTO); - assertThat(remainingArgs.length).isEqualTo(0); + assertThat(remainingArgs).hasLength(0); } @Test @@ -145,8 +145,8 @@ public class OptionsTest { assertThat(likeLeft).isEqualTo(left); assertThat(left).isNotEqualTo(right); assertThat(right).isNotEqualTo(left); - assertThat(left).isNotEqualTo(null); - assertThat(likeLeft).isNotEqualTo(null); + assertThat(left).isNotNull(); + assertThat(likeLeft).isNotNull(); assertThat(likeLeft.hashCode()).isEqualTo(likeLeft.hashCode()); assertThat(likeLeft.hashCode()).isEqualTo(left.hashCode()); // Strictly speaking this is not required for hashCode to be correct, @@ -186,8 +186,8 @@ public class OptionsTest { assertThat(webFlags.host).isEqualTo("google.com"); assertThat(webFlags.port).isEqualTo(8080); - assertThat(webFlags.isDebugging).isEqualTo(true); - assertThat(remainingArgs.length).isEqualTo(0); + assertThat(webFlags.isDebugging).isTrue(); + assertThat(remainingArgs).hasLength(0); } @Test @@ -201,8 +201,8 @@ public class OptionsTest { assertThat(webFlags.host).isEqualTo("google.com"); assertThat(webFlags.port).isEqualTo(8080); - assertThat(webFlags.isDebugging).isEqualTo(true); - assertThat(remainingArgs.length).isEqualTo(0); + assertThat(webFlags.isDebugging).isTrue(); + assertThat(remainingArgs).hasLength(0); } @Test @@ -210,7 +210,7 @@ public class OptionsTest { Options<HttpOptions> options = Options.parse(HttpOptions.class, new String[]{"--nodebug", "--notristate"}); HttpOptions webFlags = options.getOptions(); - assertThat(webFlags.isDebugging).isEqualTo(false); + assertThat(webFlags.isDebugging).isFalse(); assertThat(webFlags.triState).isEqualTo(TriState.NO); } @@ -219,7 +219,7 @@ public class OptionsTest { Options<HttpOptions> options = Options.parse(HttpOptions.class, new String[]{"-d-", "-t-"}); HttpOptions webFlags = options.getOptions(); - assertThat(webFlags.isDebugging).isEqualTo(false); + assertThat(webFlags.isDebugging).isFalse(); assertThat(webFlags.triState).isEqualTo(TriState.NO); } @@ -228,7 +228,7 @@ public class OptionsTest { Options<HttpOptions> options = Options.parse(HttpOptions.class, new String[]{"--debug=0", "--tristate=0"}); HttpOptions webFlags = options.getOptions(); - assertThat(webFlags.isDebugging).isEqualTo(false); + assertThat(webFlags.isDebugging).isFalse(); assertThat(webFlags.triState).isEqualTo(TriState.NO); } @@ -237,7 +237,7 @@ public class OptionsTest { Options<HttpOptions> options = Options.parse(HttpOptions.class, new String[]{"--debug=1", "--tristate=1"}); HttpOptions webFlags = options.getOptions(); - assertThat(webFlags.isDebugging).isEqualTo(true); + assertThat(webFlags.isDebugging).isTrue(); assertThat(webFlags.triState).isEqualTo(TriState.YES); } @@ -270,7 +270,7 @@ public class OptionsTest { Options.parse(HttpOptions.class, args); fail(); } catch (OptionsParsingException e) { - assertThat(e.getMessage()).isEqualTo("Unrecognized option: --unknown"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --unknown"); } } @@ -281,7 +281,7 @@ public class OptionsTest { Options.parse(HttpOptions.class, args); fail(); } catch (OptionsParsingException e) { - assertThat(e.getMessage()).isEqualTo("Expected value after --port"); + assertThat(e).hasMessageThat().isEqualTo("Expected value after --port"); } } @@ -314,7 +314,8 @@ public class OptionsTest { Options.parse(HttpOptions.class, new String[]{"--debug=not_a_boolean"}); fail(); } catch (OptionsParsingException e) { - assertThat(e.getMessage()) + assertThat(e) + .hasMessageThat() .isEqualTo( "While parsing option --debug=not_a_boolean: " + "\'not_a_boolean\' is not a boolean"); @@ -327,7 +328,9 @@ public class OptionsTest { Options.parse(HttpOptions.class, new String[]{"--nodebug=1"}); fail(); } catch (OptionsParsingException e) { - assertThat(e.getMessage()).isEqualTo("Unexpected value after boolean option: --nodebug=1"); + assertThat(e) + .hasMessageThat() + .isEqualTo("Unexpected value after boolean option: --nodebug=1"); } } @@ -429,7 +432,8 @@ public class OptionsTest { Options.parse(UsesCustomConverter.class, args); fail(); } catch (OptionsParsingException e) { - assertThat(e.getMessage()) + assertThat(e) + .hasMessageThat() .isEqualTo( "While parsing option --url=a_malformed:url: " + "Could not convert 'a_malformed:url': " @@ -449,7 +453,7 @@ public class OptionsTest { Options.parse(HttpOptions.class, new String[]{"--no-debug"}); fail(); } catch (OptionsParsingException e) { - assertThat(e.getMessage()).isEqualTo("Unrecognized option: --no-debug"); + assertThat(e).hasMessageThat().isEqualTo("Unrecognized option: --no-debug"); } } @@ -477,8 +481,10 @@ public class OptionsTest { Options.parse(K.class, NO_ARGS).getOptions(); fail(); } catch (OptionsParser.ConstructionException e) { - assertThat(e.getCause()).isInstanceOf(IllegalStateException.class); - assertThat(e.getCause().getMessage()) + assertThat(e).hasCauseThat().isInstanceOf(IllegalStateException.class); + assertThat(e) + .hasCauseThat() + .hasMessageThat() .isEqualTo( "OptionsParsingException while retrieving default for " + "int1: 'null' is not an int"); |