From 0e092c846615432d9376eefe685b41f81555b7e6 Mon Sep 17 00:00:00 2001 From: Sasha Sheikin Date: Tue, 18 Jun 2024 16:55:08 +0200 Subject: [PATCH] Rewrite TestNG Assertions to AssertJ Changed automatically by openrewrite recipe https://github.com/openrewrite/rewrite-testing-frameworks/pull/520 ``` org.openrewrite.maven rewrite-maven-plugin 5.32.0 org.openrewrite.java.testing.assertj.TestNgToAssertj org.openrewrite.recipe rewrite-testing-frameworks 2.11.0-SNAPSHOT ``` run ``` ./mvnw rewrite:run -Dmaven.javadoc.skip=true -DskipTests=true -Dmaven .site.skip=true -Dmaven.artifact.threads=16 -T 1C -e -Dair.check.skip-all=true --no-snapshot-updates ``` AssertJ dependency to `pom.xml` added manually. Also, some minor compilation/compatibility errors fixed manually. --- .../io/airlift/bootstrap/TestBootstrap.java | 5 +- .../TestConfigurationAwareModule.java | 16 +- .../bootstrap/TestLifeCycleManager.java | 96 +++--- .../concurrent/TestAsyncSemaphore.java | 34 +- .../concurrent/TestBoundedExecutor.java | 16 +- .../TestExtendedSettableFuture.java | 40 ++- .../airlift/concurrent/TestMoreFutures.java | 294 ++++++++--------- .../concurrent/TestThreadLocalCache.java | 14 +- .../airlift/configuration/ProblemsTest.java | 60 ++-- .../io/airlift/configuration/TestConfig.java | 85 +++-- .../TestConfigurationFactory.java | 78 +++-- .../TestConfigurationInspector.java | 6 +- .../TestConfigurationLoader.java | 18 +- .../TestConfigurationMetadata.java | 20 +- .../configuration/TestConfigurationUtils.java | 3 +- .../io/airlift/configuration/TestMonitor.java | 8 +- .../testing/TestConfigAssertions.java | 22 +- discovery/pom.xml | 6 + .../client/AbstractTestDiscoveryModule.java | 20 +- .../discovery/client/TestAnnouncement.java | 9 +- .../discovery/client/TestAnnouncer.java | 27 +- .../client/TestCachingServiceSelector.java | 12 +- .../discovery/client/TestDiscoveryBinder.java | 15 +- .../discovery/client/TestDiscoveryModule.java | 7 +- .../client/TestHttpAnnouncementBinder.java | 11 +- .../client/TestHttpAnnouncementImpl.java | 8 +- .../TestHttpDiscoveryAnnouncementClient.java | 10 +- .../client/TestHttpDiscoveryLookupClient.java | 14 +- .../client/TestHttpServiceSelectorBinder.java | 16 +- .../client/TestServiceAnnouncement.java | 13 +- .../client/TestServiceDescriptor.java | 21 +- .../client/TestServiceInventory.java | 30 +- .../discovery/client/TestServiceTypes.java | 8 +- event-http/pom.xml | 6 + .../client/http/TestHttpEventClient.java | 15 +- event/pom.xml | 6 + .../AbstractTestInMemoryEventClient.java | 16 +- .../client/AbstractTestMultiEventClient.java | 30 +- .../TestEventSubmissionFailedException.java | 9 +- .../event/client/TestEventValidation.java | 8 +- .../event/client/TestJsonEventSerializer.java | 4 +- .../event/client/TestJsonEventWriter.java | 4 +- .../event/client/TestTypeParametersUtils.java | 18 +- .../http/client/AbstractHttpClientTest.java | 175 +++++----- .../client/TestBasicAuthRequestFilter.java | 7 +- .../airlift/http/client/TestCacheControl.java | 88 +++-- .../TestDefaultingJsonResponseHandler.java | 6 +- .../http/client/TestFormDataBodyBuilder.java | 4 +- .../client/TestFullJsonResponseHandler.java | 89 +++-- .../TestGatheringByteArrayInputStream.java | 32 +- .../airlift/http/client/TestHeaderName.java | 6 +- .../http/client/TestHttpClientBinder.java | 32 +- .../http/client/TestHttpUriBuilder.java | 66 ++-- .../http/client/TestJsonResponseHandler.java | 13 +- .../http/client/TestRequestBuilder.java | 15 +- .../client/TestTraceTokenRequestFilter.java | 10 +- .../client/jetty/TestHttpClientLogger.java | 54 ++- .../client/testing/TestTestingHttpClient.java | 6 +- .../http/server/TestDelimitedRequestLog.java | 62 ++-- .../http/server/TestHttpServerCipher.java | 2 +- .../http/server/TestHttpServerInfo.java | 14 +- .../http/server/TestHttpServerModule.java | 85 +++-- .../http/server/TestHttpServerProvider.java | 186 ++++++----- .../airlift/http/server/TestInet4Network.java | 52 ++- .../http/server/TestInet4Networks.java | 29 +- .../http/server/TestJettyMultipleCerts.java | 4 +- .../server/TestRequestTimingEventHandler.java | 14 +- .../AbstractTestTestingHttpServer.java | 36 +- .../TestJaxrsTestingHttpProcessor.java | 13 +- jaxrs/pom.xml | 6 + .../java/io/airlift/jaxrs/TestJsonMapper.java | 15 +- .../TestProgrammaticResource.java | 8 +- .../jaxrs/testing/TestMockRequest.java | 26 +- jmx-http-rpc/pom.xml | 6 + .../jmx/http/rpc/TestMBeanServerResource.java | 73 ++--- jmx-http/pom.xml | 6 + .../io/airlift/jmx/TestMBeanResource.java | 29 +- .../java/io/airlift/json/ImmutablePerson.java | 14 +- .../src/test/java/io/airlift/json/Person.java | 30 +- .../java/io/airlift/json/TestJsonCodec.java | 49 ++- .../io/airlift/json/TestJsonCodecBinder.java | 4 +- .../io/airlift/json/TestJsonCodecFactory.java | 8 +- .../java/io/airlift/json/TestJsonModule.java | 20 +- .../test/java/io/airlift/json/Vehicle.java | 23 +- .../json/isolated/TestJsonCodecBinder.java | 8 +- .../io/airlift/log/TestJsonFormatter.java | 63 ++-- .../java/io/airlift/log/TestLogFileName.java | 26 +- .../io/airlift/log/TestLogHistoryManager.java | 6 +- .../test/java/io/airlift/log/TestLogging.java | 55 ++-- .../java/io/airlift/log/TestLoggingMBean.java | 28 +- .../airlift/log/TestLoggingOutputStream.java | 15 +- .../log/TestRollingFileMessageOutput.java | 136 ++++---- .../io/airlift/log/TestSocketHandler.java | 9 +- log/pom.xml | 6 + .../test/java/io/airlift/log/TestLogger.java | 49 ++- node/pom.xml | 6 + .../io/airlift/node/TestAddressSource.java | 6 +- .../java/io/airlift/node/TestNodeInfo.java | 49 ++- .../java/io/airlift/node/TestNodeModule.java | 58 ++-- .../node/testing/TestTestingNodeModule.java | 41 ++- openmetrics/pom.xml | 6 + .../openmetrics/TestMetricExpositions.java | 22 +- .../sample/TestPersonRepresentation.java | 6 +- .../io/airlift/sample/TestPersonResource.java | 43 ++- .../io/airlift/sample/TestPersonStore.java | 40 ++- .../airlift/sample/TestPersonsResource.java | 10 +- .../java/io/airlift/sample/TestServer.java | 24 +- .../security/jwks/TestJwksDecoder.java | 44 +-- .../security/jwks/TestJwksService.java | 13 +- .../security/cert/TestCertificateBuilder.java | 14 +- .../csr/TestCertificationRequest.java | 16 +- .../csr/TestCertificationRequestInfo.java | 17 +- .../csr/TestSignatureAlgorithmIdentifier.java | 15 +- .../airlift/security/pem/TestPemReader.java | 40 ++- skeleton-server/pom.xml | 6 + .../java/io/airlift/skeleton/TestServer.java | 4 +- .../java/io/airlift/stats/TestCpuTimer.java | 34 +- .../io/airlift/stats/TestDecayCounter.java | 11 +- .../io/airlift/stats/TestDecayTDigest.java | 11 +- .../io/airlift/stats/TestDistribution.java | 14 +- .../io/airlift/stats/TestJmxGcMonitor.java | 6 +- .../io/airlift/stats/TestQuantileDigest.java | 308 +++++++++--------- .../java/io/airlift/stats/TestTDigest.java | 138 ++++---- .../airlift/stats/TestTestingGcMonitor.java | 14 +- .../java/io/airlift/stats/TestTimeStat.java | 93 +++--- .../java/io/airlift/stats/TimedStatTest.java | 33 +- .../stats/cardinality/TestDenseHll.java | 10 +- .../cardinality/TestDenseSerialization.java | 12 +- .../stats/cardinality/TestHyperLogLog.java | 24 +- .../stats/cardinality/TestSparseHll.java | 5 +- testing/pom.xml | 6 + .../io/airlift/testing/TestAssertions.java | 26 +- .../testing/TestEquivalenceTester.java | 6 +- .../java/io/airlift/testing/TestTempFile.java | 24 +- .../io/airlift/testing/TestTestingClock.java | 6 +- .../testing/TestValidationAssertions.java | 20 +- trace-token/pom.xml | 6 + .../tracetoken/TestTraceTokenManager.java | 20 +- 138 files changed, 2079 insertions(+), 2204 deletions(-) diff --git a/bootstrap/src/test/java/io/airlift/bootstrap/TestBootstrap.java b/bootstrap/src/test/java/io/airlift/bootstrap/TestBootstrap.java index f4418c9b79e..f6fda98e210 100644 --- a/bootstrap/src/test/java/io/airlift/bootstrap/TestBootstrap.java +++ b/bootstrap/src/test/java/io/airlift/bootstrap/TestBootstrap.java @@ -27,8 +27,7 @@ import static io.airlift.testing.Assertions.assertContains; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.fail; public class TestBootstrap { @@ -118,7 +117,7 @@ public void testLoggingConfiguredOnce() new Bootstrap().setOptionalConfigurationProperty("log.path", "tcp://0.0.0.0:0").initialize(); int configuredHandlerCount = root.getHandlers().length; new Bootstrap().setOptionalConfigurationProperty("log.path", "tcp://0.0.0.0:0").initialize(); - assertEquals(root.getHandlers().length, configuredHandlerCount); + assertThat(root.getHandlers().length).isEqualTo(configuredHandlerCount); } @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod") diff --git a/bootstrap/src/test/java/io/airlift/bootstrap/TestConfigurationAwareModule.java b/bootstrap/src/test/java/io/airlift/bootstrap/TestConfigurationAwareModule.java index 00221197b55..08424897236 100644 --- a/bootstrap/src/test/java/io/airlift/bootstrap/TestConfigurationAwareModule.java +++ b/bootstrap/src/test/java/io/airlift/bootstrap/TestConfigurationAwareModule.java @@ -23,8 +23,8 @@ import org.testng.annotations.Test; import static com.google.inject.name.Names.named; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; public class TestConfigurationAwareModule @@ -38,9 +38,9 @@ public void testConfigAvailable() .setRequiredConfigurationProperty("bar.enabled", "true") .initialize(); - assertEquals(injector.getInstance(Key.get(String.class, named("foo"))), "fooInstance"); - assertEquals(injector.getInstance(Key.get(String.class, named("bar"))), "barInstance"); - assertEquals(injector.getInstance(Key.get(String.class, named("abc"))), "abcInstance"); + assertThat(injector.getInstance(Key.get(String.class, named("foo")))).isEqualTo("fooInstance"); + assertThat(injector.getInstance(Key.get(String.class, named("bar")))).isEqualTo("barInstance"); + assertThat(injector.getInstance(Key.get(String.class, named("abc")))).isEqualTo("abcInstance"); } @Test @@ -83,8 +83,8 @@ protected void setup(Binder binder) .setRequiredConfigurationProperty("bar.enabled", "true") .initialize(); - assertEquals(injector.getInstance(Key.get(String.class, named("foo"))), "fooInstance"); - assertEquals(injector.getInstance(Key.get(String.class, named("bar"))), "barInstance"); + assertThat(injector.getInstance(Key.get(String.class, named("foo")))).isEqualTo("fooInstance"); + assertThat(injector.getInstance(Key.get(String.class, named("bar")))).isEqualTo("barInstance"); } public static class FooModule @@ -93,7 +93,7 @@ public static class FooModule @Override protected void setup(Binder binder) { - assertTrue(buildConfigObject(FooConfig.class).isFoo()); + assertThat(buildConfigObject(FooConfig.class).isFoo()).isTrue(); install(new BarModule()); binder.bind(String.class).annotatedWith(named("foo")).toInstance("fooInstance"); binder.install(new AbcModule()); @@ -106,7 +106,7 @@ public static class BarModule @Override protected void setup(Binder binder) { - assertTrue(buildConfigObject(BarConfig.class).isBar()); + assertThat(buildConfigObject(BarConfig.class).isBar()).isTrue(); binder.bind(String.class).annotatedWith(named("bar")).toInstance("barInstance"); } } diff --git a/bootstrap/src/test/java/io/airlift/bootstrap/TestLifeCycleManager.java b/bootstrap/src/test/java/io/airlift/bootstrap/TestLifeCycleManager.java index 3c5bcd5a293..7ea76fccab8 100644 --- a/bootstrap/src/test/java/io/airlift/bootstrap/TestLifeCycleManager.java +++ b/bootstrap/src/test/java/io/airlift/bootstrap/TestLifeCycleManager.java @@ -38,9 +38,8 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; @Test(singleThreaded = true) public class TestLifeCycleManager @@ -73,7 +72,7 @@ public void testImmediateStarts() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("InstanceThatUsesInstanceThatRequiresStart:OK")); + assertThat(stateLog).isEqualTo(ImmutableList.of("InstanceThatUsesInstanceThatRequiresStart:OK")); } @Test @@ -94,10 +93,10 @@ protected void configure() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("postSimpleBaseImpl")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postSimpleBaseImpl")); lifeCycleManager.stop(); - assertEquals(stateLog, ImmutableList.of("postSimpleBaseImpl", "preSimpleBaseImpl")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postSimpleBaseImpl", "preSimpleBaseImpl")); } @Test @@ -110,11 +109,11 @@ public void testSubClassAnnotated() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("postSimpleBaseImpl")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postSimpleBaseImpl")); lifeCycleManager.stop(); - assertEquals(stateLog, ImmutableList.of("postSimpleBaseImpl", "preSimpleBaseImpl")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postSimpleBaseImpl", "preSimpleBaseImpl")); } @Test @@ -130,12 +129,12 @@ public void testExecuted() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); instance.waitForStart(); - assertEquals(stateLog, ImmutableList.of("Starting")); + assertThat(stateLog).isEqualTo(ImmutableList.of("Starting")); lifeCycleManager.stop(); instance.waitForEnd(); - assertEquals(stateLog, ImmutableList.of("Starting", "Done")); + assertThat(stateLog).isEqualTo(ImmutableList.of("Starting", "Done")); } @Test @@ -154,10 +153,10 @@ public void testDeepDependency() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("postDependentInstance")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postDependentInstance")); lifeCycleManager.stop(); - assertEquals(stateLog, ImmutableList.of("postDependentInstance", "preDependentInstance")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postDependentInstance", "preDependentInstance")); } @Test @@ -168,7 +167,7 @@ public void testIllegalMethods() Stage.PRODUCTION, binder -> binder.bind(IllegalInstance.class).in(Scopes.SINGLETON), new LifeCycleModule()); - fail(); + fail(""); } catch (CreationException dummy) { // correct behavior @@ -187,7 +186,7 @@ public void testDuplicateMethodNames() lifeCycleManager.start(); lifeCycleManager.stop(); - assertEquals(stateLog, ImmutableList.of("foo")); + assertThat(stateLog).isEqualTo(ImmutableList.of("foo")); } @Test @@ -206,7 +205,7 @@ public void testJITInjection() lifeCycleManager.start(); lifeCycleManager.stop(); - assertEquals(stateLog, ImmutableList.of("postDependentInstance", "preDependentInstance")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postDependentInstance", "preDependentInstance")); } @Test @@ -222,20 +221,20 @@ public void testPreDestroySuppressedExceptionHandling() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("postDependentInstance")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postDependentInstance")); try { lifeCycleManager.stopWithoutFailureLogging(); fail("Expected exception to be thrown"); } catch (LifeCycleStopException e) { - assertEquals(e.getSuppressed().length, 2, "Expected two suppressed exceptions"); + assertThat(e.getSuppressed().length).as("Expected two suppressed exceptions").isEqualTo(2); Set suppressedMessages = Arrays.stream(e.getSuppressed()) .map(Throwable::getMessage) .collect(Collectors.toSet()); - assertEquals(ImmutableSet.copyOf(suppressedMessages), ImmutableSet.of("preDestroyExceptionOne", "preDestroyExceptionTwo")); + assertThat(ImmutableSet.copyOf(suppressedMessages)).isEqualTo(ImmutableSet.of("preDestroyExceptionOne", "preDestroyExceptionTwo")); } - assertEquals(ImmutableSet.copyOf(stateLog), ImmutableSet.of( + assertThat(ImmutableSet.copyOf(stateLog)).isEqualTo(ImmutableSet.of( "postDependentInstance", "preDestroyExceptionOne", "preDestroyExceptionTwo", @@ -255,16 +254,16 @@ public void testPreDestroyLoggingExceptionHandling() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("postDependentInstance")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postDependentInstance")); try { lifeCycleManager.stop(); fail("Expected exception to be thrown"); } catch (LifeCycleStopException e) { - assertEquals(e.getSuppressed().length, 0, "Suppressed exceptions list should be empty"); + assertThat(e.getSuppressed().length).as("Suppressed exceptions list should be empty").isEqualTo(0); } - assertEquals(ImmutableSet.copyOf(stateLog), ImmutableSet.of( + assertThat(ImmutableSet.copyOf(stateLog)).isEqualTo(ImmutableSet.of( "postDependentInstance", "preDestroyExceptionOne", "preDestroyExceptionTwo", @@ -282,19 +281,17 @@ public void testPostConstructExceptionCallsPreDestroy() fail("Expected injector creation to fail with an exception"); } catch (CreationException e) { - assertEquals(ImmutableSet.copyOf(stateLog), ImmutableSet.of( + assertThat(ImmutableSet.copyOf(stateLog)).isEqualTo(ImmutableSet.of( "postConstructFailure", "preDestroyFailureAfterPostConstructFailureOne", "preDestroyFailureAfterPostConstructFailureTwo")); - assertEquals(e.getCause().getClass(), LifeCycleStartException.class, "Expected LifeCycleStartException to be thrown, found: " + e.getCause().getClass()); - assertEquals(e.getCause().getSuppressed().length, 2, "Expected two suppressed exceptions"); - assertEquals( - ImmutableSet.copyOf( - Arrays.stream(e.getCause().getSuppressed()) - .map(Throwable::getCause) - .map(Throwable::getMessage) - .collect(Collectors.toSet())), - ImmutableSet.of("preDestroyFailureAfterPostConstructFailureOne", "preDestroyFailureAfterPostConstructFailureTwo")); + assertThat(e.getCause().getClass()).as("Expected LifeCycleStartException to be thrown, found: " + e.getCause().getClass()).isEqualTo(LifeCycleStartException.class); + assertThat(e.getCause().getSuppressed().length).as("Expected two suppressed exceptions").isEqualTo(2); + assertThat(ImmutableSet.copyOf( + Arrays.stream(e.getCause().getSuppressed()) + .map(Throwable::getCause) + .map(Throwable::getMessage) + .collect(Collectors.toSet()))).isEqualTo(ImmutableSet.of("preDestroyFailureAfterPostConstructFailureOne", "preDestroyFailureAfterPostConstructFailureTwo")); } } @@ -312,10 +309,10 @@ public void testNoPreDestroy() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("makeMe")); + assertThat(stateLog).isEqualTo(ImmutableList.of("makeMe")); lifeCycleManager.stop(); - assertEquals(stateLog, ImmutableList.of("makeMe", "unmakeMe")); + assertThat(stateLog).isEqualTo(ImmutableList.of("makeMe", "unmakeMe")); } @Test @@ -337,16 +334,15 @@ public void testModule() lifeCycleManager.stop(); Set stateLogSet = new HashSet<>(stateLog); - assertEquals(stateLogSet, - Sets.newHashSet( - "postDependentBoundInstance", - "postDependentInstance", - "postMakeOne", - "postMakeTwo", - "preDestroyTwo", - "preDestroyOne", - "preDependentInstance", - "preDependentBoundInstance")); + assertThat(stateLogSet).isEqualTo(Sets.newHashSet( + "postDependentBoundInstance", + "postDependentInstance", + "postMakeOne", + "postMakeTwo", + "preDestroyTwo", + "preDestroyOne", + "preDependentInstance", + "preDependentBoundInstance")); } @Test @@ -360,10 +356,10 @@ public void testProvider() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("postBarProvider", "postBarInstance")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postBarProvider", "postBarInstance")); lifeCycleManager.stop(); - assertEquals(stateLog, ImmutableList.of("postBarProvider", "postBarInstance", "preBarInstance", "preBarProvider")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postBarProvider", "postBarInstance", "preBarInstance", "preBarProvider")); } @Test @@ -388,10 +384,10 @@ public BarInstance create() LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); - assertEquals(stateLog, ImmutableList.of("postBarInstance")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postBarInstance")); lifeCycleManager.stop(); - assertEquals(stateLog, ImmutableList.of("postBarInstance", "preBarInstance")); + assertThat(stateLog).isEqualTo(ImmutableList.of("postBarInstance", "preBarInstance")); } @Test @@ -412,13 +408,13 @@ public BarInstance createBar() } }); - assertNull(injector.getInstance(BarInstance.class)); + assertThat(injector.getInstance(BarInstance.class)).isNull(); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); lifeCycleManager.start(); lifeCycleManager.stop(); - assertNull(injector.getInstance(BarInstance.class)); + assertThat(injector.getInstance(BarInstance.class)).isNull(); } } diff --git a/concurrent/src/test/java/io/airlift/concurrent/TestAsyncSemaphore.java b/concurrent/src/test/java/io/airlift/concurrent/TestAsyncSemaphore.java index 9eb82e7219b..fb615e48c95 100644 --- a/concurrent/src/test/java/io/airlift/concurrent/TestAsyncSemaphore.java +++ b/concurrent/src/test/java/io/airlift/concurrent/TestAsyncSemaphore.java @@ -21,6 +21,7 @@ import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.Uninterruptibles; import jakarta.annotation.Nullable; +import org.assertj.core.api.Fail; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -49,8 +50,7 @@ import static io.airlift.testing.Assertions.assertLessThanOrEqual; import static java.util.concurrent.Executors.newCachedThreadPool; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Fail.fail; public class TestAsyncSemaphore { @@ -72,7 +72,7 @@ public void testInlineExecution() // Wait for completion Futures.allAsList(futures).get(1, TimeUnit.MINUTES); - assertEquals(count.get(), 1000); + assertThat(count.get()).isEqualTo(1000); } @Test @@ -98,7 +98,7 @@ public void testSingleThreadBoundedConcurrency() // Wait for completion Futures.allAsList(futures).get(1, TimeUnit.MINUTES); - assertEquals(count.get(), 1000); + assertThat(count.get()).isEqualTo(1000); } @Test @@ -124,7 +124,7 @@ public void testMultiThreadBoundedConcurrency() // Wait for completion Futures.allAsList(futures).get(1, TimeUnit.MINUTES); - assertEquals(count.get(), 1000); + assertThat(count.get()).isEqualTo(1000); } @Test @@ -157,7 +157,7 @@ public void testMultiSubmitters() // Wait for completion Uninterruptibles.awaitUninterruptibly(completionLatch, 1, TimeUnit.MINUTES); - assertEquals(count.get(), 100); + assertThat(count.get()).isEqualTo(100); } @Test @@ -184,14 +184,14 @@ public void testFailedTasks() for (ListenableFuture future : futures) { try { future.get(); - fail(); + fail(""); } catch (Exception ignored) { } } - assertEquals(successCount.get(), 0); - assertEquals(failureCount.get(), 1000); + assertThat(successCount.get()).isEqualTo(0); + assertThat(failureCount.get()).isEqualTo(1000); } @Test @@ -209,7 +209,7 @@ public void testFailedTaskSubmission() List> futures = new ArrayList<>(); for (int i = 0; i < 1000; i++) { // Should never execute this future - ListenableFuture future = asyncSemaphore.submit(() -> fail(null)); + ListenableFuture future = asyncSemaphore.submit(Fail::fail); addCallback(future, completionCallback(successCount, failureCount, completionLatch), directExecutor()); futures.add(future); } @@ -220,14 +220,14 @@ public void testFailedTaskSubmission() for (ListenableFuture future : futures) { try { future.get(); - fail(); + fail(""); } catch (Exception ignored) { } } - assertEquals(successCount.get(), 0); - assertEquals(failureCount.get(), 1000); + assertThat(successCount.get()).isEqualTo(0); + assertThat(failureCount.get()).isEqualTo(1000); } @Test @@ -249,7 +249,7 @@ public void testFailedTaskWithMultipleSubmitters() executor.execute(() -> { Uninterruptibles.awaitUninterruptibly(startLatch, 1, TimeUnit.MINUTES); // Should never execute this future - ListenableFuture future = asyncSemaphore.submit(() -> fail(null)); + ListenableFuture future = asyncSemaphore.submit(Fail::fail); futures.add(future); addCallback(future, completionCallback(successCount, failureCount, completionLatch), directExecutor()); }); @@ -264,14 +264,14 @@ public void testFailedTaskWithMultipleSubmitters() for (ListenableFuture future : futures) { try { future.get(); - fail(); + fail(""); } catch (Exception ignored) { } } - assertEquals(successCount.get(), 0); - assertEquals(failureCount.get(), 100); + assertThat(successCount.get()).isEqualTo(0); + assertThat(failureCount.get()).isEqualTo(100); } @Test diff --git a/concurrent/src/test/java/io/airlift/concurrent/TestBoundedExecutor.java b/concurrent/src/test/java/io/airlift/concurrent/TestBoundedExecutor.java index 49e39c1b3cb..1418a41cf9d 100644 --- a/concurrent/src/test/java/io/airlift/concurrent/TestBoundedExecutor.java +++ b/concurrent/src/test/java/io/airlift/concurrent/TestBoundedExecutor.java @@ -14,10 +14,8 @@ import static com.google.common.util.concurrent.Uninterruptibles.awaitUninterruptibly; import static java.util.concurrent.Executors.newCachedThreadPool; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestBoundedExecutor @@ -66,7 +64,7 @@ public void testCounter() }); } - assertTrue(awaitUninterruptibly(initializeLatch, 1, TimeUnit.MINUTES)); // Wait for pre-load tasks to initialize + assertThat(awaitUninterruptibly(initializeLatch, 1, TimeUnit.MINUTES)).isTrue(); // Wait for pre-load tasks to initialize startLatch.countDown(); // Signal go for stage1 threads // Concurrently submitted tasks @@ -83,8 +81,8 @@ public void testCounter() }); } - assertTrue(awaitUninterruptibly(completeLatch, 1, TimeUnit.MINUTES)); // Wait for tasks to complete - assertEquals(counter.get(), totalTasks); + assertThat(awaitUninterruptibly(completeLatch, 1, TimeUnit.MINUTES)).isTrue(); // Wait for tasks to complete + assertThat(counter.get()).isEqualTo(totalTasks); } @Test @@ -160,7 +158,7 @@ private void testBound(int maxThreads, int stageTasks) }); } - assertTrue(awaitUninterruptibly(initializeLatch, 1, TimeUnit.MINUTES)); // Wait for pre-load tasks to initialize + assertThat(awaitUninterruptibly(initializeLatch, 1, TimeUnit.MINUTES)).isTrue(); // Wait for pre-load tasks to initialize startLatch.countDown(); // Signal go for stage1 threads // Concurrently submitted tasks @@ -179,8 +177,8 @@ private void testBound(int maxThreads, int stageTasks) }); } - assertTrue(awaitUninterruptibly(completeLatch, 1, TimeUnit.MINUTES)); // Wait for tasks to complete + assertThat(awaitUninterruptibly(completeLatch, 1, TimeUnit.MINUTES)).isTrue(); // Wait for tasks to complete - assertFalse(failed.get()); + assertThat(failed.get()).isFalse(); } } diff --git a/concurrent/src/test/java/io/airlift/concurrent/TestExtendedSettableFuture.java b/concurrent/src/test/java/io/airlift/concurrent/TestExtendedSettableFuture.java index e263bc7fcd4..b8cdb1791e4 100644 --- a/concurrent/src/test/java/io/airlift/concurrent/TestExtendedSettableFuture.java +++ b/concurrent/src/test/java/io/airlift/concurrent/TestExtendedSettableFuture.java @@ -5,10 +5,8 @@ import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; public class TestExtendedSettableFuture { @@ -18,10 +16,10 @@ public void testSet() { ExtendedSettableFuture future = ExtendedSettableFuture.create(); future.set("abc"); - assertTrue(future.isDone()); - assertFalse(future.isCancelled()); - assertFalse(future.checkWasInterrupted()); - assertEquals(future.get(), "abc"); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCancelled()).isFalse(); + assertThat(future.checkWasInterrupted()).isFalse(); + assertThat(future.get()).isEqualTo("abc"); } @Test @@ -30,9 +28,9 @@ public void testSetException() { ExtendedSettableFuture future = ExtendedSettableFuture.create(); future.setException(new Exception("")); - assertTrue(future.isDone()); - assertFalse(future.isCancelled()); - assertFalse(future.checkWasInterrupted()); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCancelled()).isFalse(); + assertThat(future.checkWasInterrupted()).isFalse(); assertThrows(ExecutionException.class, future::get); } @@ -42,9 +40,9 @@ public void testCancelWithoutInterrupt() { ExtendedSettableFuture future = ExtendedSettableFuture.create(); future.cancel(false); - assertTrue(future.isDone()); - assertTrue(future.isCancelled()); - assertFalse(future.checkWasInterrupted()); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCancelled()).isTrue(); + assertThat(future.checkWasInterrupted()).isFalse(); assertThrows(CancellationException.class, future::get); } @@ -54,9 +52,9 @@ public void testCancelWithInterrupt() { ExtendedSettableFuture future = ExtendedSettableFuture.create(); future.cancel(true); - assertTrue(future.isDone()); - assertTrue(future.isCancelled()); - assertTrue(future.checkWasInterrupted()); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCancelled()).isTrue(); + assertThat(future.checkWasInterrupted()).isTrue(); assertThrows(CancellationException.class, future::get); } @@ -69,7 +67,7 @@ public void testSetAsync() ExtendedSettableFuture toFuture = ExtendedSettableFuture.create(); toFuture.setAsync(fromFuture); fromFuture.set("abc"); - assertEquals(toFuture.get(), "abc"); + assertThat(toFuture.get()).isEqualTo("abc"); // Test exception fromFuture = ExtendedSettableFuture.create(); @@ -84,8 +82,8 @@ public void testSetAsync() toFuture.setAsync(fromFuture); toFuture.cancel(false); // Parent Future should receive the cancellation - assertTrue(fromFuture.isCancelled()); - assertFalse(fromFuture.checkWasInterrupted()); + assertThat(fromFuture.isCancelled()).isTrue(); + assertThat(fromFuture.checkWasInterrupted()).isFalse(); // Test cancellation with interrupt fromFuture = ExtendedSettableFuture.create(); @@ -93,7 +91,7 @@ public void testSetAsync() toFuture.setAsync(fromFuture); toFuture.cancel(true); // Parent Future should receive the cancellation - assertTrue(fromFuture.isCancelled()); - assertTrue(fromFuture.checkWasInterrupted()); + assertThat(fromFuture.isCancelled()).isTrue(); + assertThat(fromFuture.checkWasInterrupted()).isTrue(); } } diff --git a/concurrent/src/test/java/io/airlift/concurrent/TestMoreFutures.java b/concurrent/src/test/java/io/airlift/concurrent/TestMoreFutures.java index 279dae5af66..95ed8d853da 100644 --- a/concurrent/src/test/java/io/airlift/concurrent/TestMoreFutures.java +++ b/concurrent/src/test/java/io/airlift/concurrent/TestMoreFutures.java @@ -47,14 +47,12 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertSame; import static org.testng.Assert.assertThrows; import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; @SuppressWarnings("deprecation") public class TestMoreFutures @@ -76,15 +74,15 @@ public void propagateCancellationWithoutInterrupt() ExtendedSettableFuture toFuture = ExtendedSettableFuture.create(); propagateCancellation(fromFuture, toFuture, false); fromFuture.cancel(true); - assertTrue(toFuture.isCancelled()); - assertFalse(toFuture.checkWasInterrupted()); + assertThat(toFuture.isCancelled()).isTrue(); + assertThat(toFuture.checkWasInterrupted()).isFalse(); fromFuture = ExtendedSettableFuture.create(); toFuture = ExtendedSettableFuture.create(); propagateCancellation(fromFuture, toFuture, false); fromFuture.cancel(false); - assertTrue(toFuture.isCancelled()); - assertFalse(toFuture.checkWasInterrupted()); + assertThat(toFuture.isCancelled()).isTrue(); + assertThat(toFuture.checkWasInterrupted()).isFalse(); } @Test @@ -95,16 +93,16 @@ public void propagateCancellationWithInterrupt() ExtendedSettableFuture toFuture = ExtendedSettableFuture.create(); propagateCancellation(fromFuture, toFuture, true); fromFuture.cancel(true); - assertTrue(toFuture.isCancelled()); - assertTrue(toFuture.checkWasInterrupted()); + assertThat(toFuture.isCancelled()).isTrue(); + assertThat(toFuture.checkWasInterrupted()).isTrue(); // Test interrupt override fromFuture = ExtendedSettableFuture.create(); toFuture = ExtendedSettableFuture.create(); propagateCancellation(fromFuture, toFuture, true); fromFuture.cancel(false); - assertTrue(toFuture.isCancelled()); - assertTrue(toFuture.checkWasInterrupted()); + assertThat(toFuture.isCancelled()).isTrue(); + assertThat(toFuture.checkWasInterrupted()).isTrue(); } @Test @@ -116,7 +114,7 @@ public void testMirror() SettableFuture toFuture = SettableFuture.create(); mirror(fromFuture, toFuture, true); fromFuture.set("abc"); - assertEquals(toFuture.get(), "abc"); + assertThat(toFuture.get()).isEqualTo("abc"); // Test exception fromFuture = ExtendedSettableFuture.create(); @@ -131,8 +129,8 @@ public void testMirror() mirror(fromFuture, toFuture, false); toFuture.cancel(true); // Parent Future should receive the cancellation - assertTrue(fromFuture.isCancelled()); - assertFalse(fromFuture.checkWasInterrupted()); + assertThat(fromFuture.isCancelled()).isTrue(); + assertThat(fromFuture.checkWasInterrupted()).isFalse(); // Test cancellation with interrupt fromFuture = ExtendedSettableFuture.create(); @@ -140,8 +138,8 @@ public void testMirror() mirror(fromFuture, toFuture, true); toFuture.cancel(false); // Parent Future should receive the cancellation - assertTrue(fromFuture.isCancelled()); - assertTrue(fromFuture.checkWasInterrupted()); + assertThat(fromFuture.isCancelled()).isTrue(); + assertThat(fromFuture.checkWasInterrupted()).isTrue(); } @Test @@ -164,33 +162,33 @@ public void testModifyUnmodifiableFuture() // completion results in an UnsupportedOperationException assertFailure(() -> unmodifiableFuture.complete("fail"), e -> assertInstanceOf(e, UnsupportedOperationException.class)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); assertFailure(() -> unmodifiableFuture.completeExceptionally(new IOException()), e -> assertInstanceOf(e, UnsupportedOperationException.class)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); assertFailure(() -> unmodifiableFuture.obtrudeValue("fail"), e -> assertInstanceOf(e, UnsupportedOperationException.class)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); assertFailure(() -> unmodifiableFuture.obtrudeException(new IOException()), e -> assertInstanceOf(e, UnsupportedOperationException.class)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); // cancel is ignored - assertFalse(unmodifiableFuture.cancel(false)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(unmodifiableFuture.cancel(false)).isFalse(); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); - assertFalse(unmodifiableFuture.cancel(true)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(unmodifiableFuture.cancel(true)).isFalse(); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); - assertFalse(unmodifiableFuture.completeExceptionally(new CancellationException())); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(unmodifiableFuture.completeExceptionally(new CancellationException())).isFalse(); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); } @Test @@ -202,20 +200,20 @@ public void testModifyCancelableUnmodifiableFuture() // completion results in an UnsupportedOperationException assertFailure(() -> unmodifiableFuture.complete("fail"), e -> assertInstanceOf(e, UnsupportedOperationException.class)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); assertFailure(() -> unmodifiableFuture.completeExceptionally(new IOException()), e -> assertInstanceOf(e, UnsupportedOperationException.class)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); assertFailure(() -> unmodifiableFuture.obtrudeValue("fail"), e -> assertInstanceOf(e, UnsupportedOperationException.class)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); assertFailure(() -> unmodifiableFuture.obtrudeException(new IOException()), e -> assertInstanceOf(e, UnsupportedOperationException.class)); - assertFalse(future.isDone()); - assertFalse(unmodifiableFuture.isDone()); + assertThat(future.isDone()).isFalse(); + assertThat(unmodifiableFuture.isDone()).isFalse(); // cancel is propagated so test separately } @@ -226,27 +224,27 @@ public void testUnmodifiableFutureCancelPropagation() { CompletableFuture future = new CompletableFuture<>(); CompletableFuture unmodifiableFuture = unmodifiableFuture(future, true); - assertTrue(unmodifiableFuture.cancel(false)); - assertTrue(future.isDone()); - assertTrue(future.isCancelled()); - assertTrue(unmodifiableFuture.isDone()); - assertTrue(unmodifiableFuture.isCancelled()); + assertThat(unmodifiableFuture.cancel(false)).isTrue(); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCancelled()).isTrue(); + assertThat(unmodifiableFuture.isDone()).isTrue(); + assertThat(unmodifiableFuture.isCancelled()).isTrue(); future = new CompletableFuture<>(); unmodifiableFuture = unmodifiableFuture(future, true); - assertTrue(unmodifiableFuture.cancel(true)); - assertTrue(future.isDone()); - assertTrue(future.isCancelled()); - assertTrue(unmodifiableFuture.isDone()); - assertTrue(unmodifiableFuture.isCancelled()); + assertThat(unmodifiableFuture.cancel(true)).isTrue(); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCancelled()).isTrue(); + assertThat(unmodifiableFuture.isDone()).isTrue(); + assertThat(unmodifiableFuture.isCancelled()).isTrue(); future = new CompletableFuture<>(); unmodifiableFuture = unmodifiableFuture(future, true); - assertTrue(unmodifiableFuture.completeExceptionally(new CancellationException())); - assertTrue(future.isDone()); - assertTrue(future.isCancelled()); - assertTrue(unmodifiableFuture.isDone()); - assertTrue(unmodifiableFuture.isCancelled()); + assertThat(unmodifiableFuture.completeExceptionally(new CancellationException())).isTrue(); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCancelled()).isTrue(); + assertThat(unmodifiableFuture.isDone()).isTrue(); + assertThat(unmodifiableFuture.isCancelled()).isTrue(); } @Test @@ -256,10 +254,10 @@ public void testCompleteUnmodifiableFuture() CompletableFuture future = new CompletableFuture<>(); CompletableFuture unmodifiableFuture = unmodifiableFuture(future); - assertTrue(future.complete("done")); - assertEquals(future.getNow(null), "done"); - assertTrue(unmodifiableFuture.isDone()); - assertEquals(unmodifiableFuture.getNow(null), "done"); + assertThat(future.complete("done")).isTrue(); + assertThat(future.getNow(null)).isEqualTo("done"); + assertThat(unmodifiableFuture.isDone()).isTrue(); + assertThat(unmodifiableFuture.getNow(null)).isEqualTo("done"); } @Test @@ -269,13 +267,13 @@ public void testCompleteExceptionallyUnmodifiableFuture() CompletableFuture future = new CompletableFuture<>(); CompletableFuture unmodifiableFuture = unmodifiableFuture(future); - assertTrue(future.completeExceptionally(new SQLException("foo"))); + assertThat(future.completeExceptionally(new SQLException("foo"))).isTrue(); assertFailure(() -> getFutureValue(future, SQLException.class), e -> { assertInstanceOf(e, SQLException.class); assertEquals(e.getMessage(), "foo"); }); - assertTrue(unmodifiableFuture.isDone()); + assertThat(unmodifiableFuture.isDone()).isTrue(); assertFailure(() -> getFutureValue(unmodifiableFuture, SQLException.class), e -> { assertInstanceOf(e, SQLException.class); assertEquals(e.getMessage(), "foo"); @@ -289,9 +287,9 @@ public void testAlreadyCompleteUnmodifiableFuture() CompletableFuture future = completedFuture("done"); CompletableFuture unmodifiableFuture = unmodifiableFuture(future); - assertEquals(future.getNow(null), "done"); - assertTrue(unmodifiableFuture.isDone()); - assertEquals(unmodifiableFuture.getNow(null), "done"); + assertThat(future.getNow(null)).isEqualTo("done"); + assertThat(unmodifiableFuture.isDone()).isTrue(); + assertThat(unmodifiableFuture.getNow(null)).isEqualTo("done"); } @Test @@ -306,7 +304,7 @@ public void testAlreadyCompleteExceptionallyUnmodifiableFuture() assertEquals(e.getMessage(), "foo"); }); - assertTrue(unmodifiableFuture.isDone()); + assertThat(unmodifiableFuture.isDone()).isTrue(); assertFailure(() -> getFutureValue(unmodifiableFuture, SQLException.class), e -> { assertInstanceOf(e, SQLException.class); assertEquals(e.getMessage(), "foo"); @@ -319,7 +317,7 @@ public void testFailedFuture() { CompletableFuture future = failedFuture(new SQLException("foo")); - assertTrue(future.isCompletedExceptionally()); + assertThat(future.isCompletedExceptionally()).isTrue(); assertFailure(future::get, e -> { assertInstanceOf(e, ExecutionException.class); @@ -362,7 +360,7 @@ public void testTryGetFutureValue() return null; }); - assertEquals(tryGetFutureValue(new CompletableFuture<>()), Optional.empty()); + assertThat(tryGetFutureValue(new CompletableFuture<>())).isEqualTo(Optional.empty()); } @Test @@ -380,7 +378,7 @@ public void testTryGetFutureValueWithWait() return null; }); - assertEquals(tryGetFutureValue(new CompletableFuture<>(), 10, MILLISECONDS), Optional.empty()); + assertThat(tryGetFutureValue(new CompletableFuture<>(), 10, MILLISECONDS)).isEqualTo(Optional.empty()); } @Test @@ -398,7 +396,7 @@ public void testTryGetFutureValueWithExceptionType() return null; }); - assertEquals(tryGetFutureValue(new CompletableFuture<>(), 10, MILLISECONDS), Optional.empty()); + assertThat(tryGetFutureValue(new CompletableFuture<>(), 10, MILLISECONDS)).isEqualTo(Optional.empty()); assertFailure(() -> tryGetFutureValue(failedFuture(new SQLException("foo")), 10, MILLISECONDS, SQLException.class), e -> { assertInstanceOf(e, SQLException.class); @@ -415,9 +413,7 @@ public void testWhenAnyComplete() assertFailure(() -> whenAnyComplete(null), e -> assertInstanceOf(e, NullPointerException.class)); assertFailure(() -> whenAnyComplete(ImmutableList.of()), e -> assertInstanceOf(e, IllegalArgumentException.class)); - assertEquals( - tryGetFutureValue(whenAnyComplete(ImmutableList.of(SettableFuture.create(), SettableFuture.create())), 10, MILLISECONDS), - Optional.empty()); + assertThat(tryGetFutureValue(whenAnyComplete(ImmutableList.of(SettableFuture.create(), SettableFuture.create())), 10, MILLISECONDS)).isEqualTo(Optional.empty()); } @Test @@ -436,9 +432,7 @@ public void testWhenAnyCompleteCancelOthers() assertFailure(() -> whenAnyComplete(null), e -> assertInstanceOf(e, NullPointerException.class)); assertFailure(() -> whenAnyComplete(ImmutableList.of()), e -> assertInstanceOf(e, IllegalArgumentException.class)); - assertEquals( - tryGetFutureValue(whenAnyComplete(ImmutableList.of(SettableFuture.create(), SettableFuture.create())), 10, MILLISECONDS), - Optional.empty()); + assertThat(tryGetFutureValue(whenAnyComplete(ImmutableList.of(SettableFuture.create(), SettableFuture.create())), 10, MILLISECONDS)).isEqualTo(Optional.empty()); } @Test @@ -450,9 +444,7 @@ public void testAnyOf() assertFailure(() -> firstCompletedFuture(null), e -> assertInstanceOf(e, NullPointerException.class)); assertFailure(() -> firstCompletedFuture(ImmutableList.of()), e -> assertInstanceOf(e, IllegalArgumentException.class)); - assertEquals( - tryGetFutureValue(firstCompletedFuture(ImmutableList.of(new CompletableFuture<>(), new CompletableFuture<>())), 10, MILLISECONDS), - Optional.empty()); + assertThat(tryGetFutureValue(firstCompletedFuture(ImmutableList.of(new CompletableFuture<>(), new CompletableFuture<>())), 10, MILLISECONDS)).isEqualTo(Optional.empty()); } @Test @@ -463,14 +455,14 @@ public void testToFromListenableFuture() SettableFuture settableFuture = SettableFuture.create(); toCompletableFuture(settableFuture).cancel(true); - assertTrue(settableFuture.isCancelled()); + assertThat(settableFuture.isCancelled()).isTrue(); CompletableFuture completableFuture = new CompletableFuture<>(); toListenableFuture(completableFuture).cancel(true); - assertTrue(completableFuture.isCancelled()); + assertThat(completableFuture.isCancelled()).isTrue(); - assertEquals(tryGetFutureValue(toCompletableFuture(SettableFuture.create()), 10, MILLISECONDS), Optional.empty()); - assertEquals(tryGetFutureValue(toListenableFuture(new CompletableFuture<>()), 10, MILLISECONDS), Optional.empty()); + assertThat(tryGetFutureValue(toCompletableFuture(SettableFuture.create()), 10, MILLISECONDS)).isEqualTo(Optional.empty()); + assertThat(tryGetFutureValue(toListenableFuture(new CompletableFuture<>()), 10, MILLISECONDS)).isEqualTo(Optional.empty()); } @Test @@ -478,10 +470,10 @@ public void testEmptyAllAsList() throws Exception { CompletableFuture> future = allAsList(ImmutableList.of()); - assertTrue(future.isDone()); - assertFalse(future.isCompletedExceptionally()); - assertFalse(future.isCancelled()); - assertEquals(future.join(), ImmutableList.of()); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCompletedExceptionally()).isFalse(); + assertThat(future.isCancelled()).isFalse(); + assertThat(future.join()).isEqualTo(ImmutableList.of()); } @Test @@ -491,14 +483,14 @@ public void testSingleElementAllAsList() CompletableFuture element1 = new CompletableFuture<>(); CompletableFuture> future = allAsList(ImmutableList.of(element1)); - assertFalse(future.isDone()); - assertFalse(future.isCancelled()); + assertThat(future.isDone()).isFalse(); + assertThat(future.isCancelled()).isFalse(); element1.complete("a"); - assertTrue(future.isDone()); - assertFalse(future.isCompletedExceptionally()); - assertFalse(future.isCancelled()); - assertEquals(future.join(), ImmutableList.of("a")); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCompletedExceptionally()).isFalse(); + assertThat(future.isCancelled()).isFalse(); + assertThat(future.join()).isEqualTo(ImmutableList.of("a")); } @Test @@ -508,13 +500,13 @@ public void testExceptionalSingleElementAllAsList() CompletableFuture element1 = new CompletableFuture<>(); CompletableFuture> future = allAsList(ImmutableList.of(element1)); - assertFalse(future.isDone()); - assertFalse(future.isCancelled()); + assertThat(future.isDone()).isFalse(); + assertThat(future.isCancelled()).isFalse(); element1.completeExceptionally(new RuntimeException()); - assertTrue(future.isDone()); - assertTrue(future.isCompletedExceptionally()); - assertFalse(future.isCancelled()); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCompletedExceptionally()).isTrue(); + assertThat(future.isCancelled()).isFalse(); } @Test @@ -525,19 +517,19 @@ public void testMultipleElementAllAsList() CompletableFuture element2 = new CompletableFuture<>(); CompletableFuture> future = allAsList(ImmutableList.of(element1, element2)); - assertFalse(future.isDone()); - assertFalse(future.isCancelled()); + assertThat(future.isDone()).isFalse(); + assertThat(future.isCancelled()).isFalse(); element1.complete("a"); - assertFalse(future.isDone()); - assertFalse(future.isCompletedExceptionally()); - assertFalse(future.isCancelled()); + assertThat(future.isDone()).isFalse(); + assertThat(future.isCompletedExceptionally()).isFalse(); + assertThat(future.isCancelled()).isFalse(); element2.complete("b"); - assertTrue(future.isDone()); - assertFalse(future.isCompletedExceptionally()); - assertFalse(future.isCancelled()); - assertEquals(future.join(), ImmutableList.of("a", "b")); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCompletedExceptionally()).isFalse(); + assertThat(future.isCancelled()).isFalse(); + assertThat(future.join()).isEqualTo(ImmutableList.of("a", "b")); } @Test @@ -548,14 +540,14 @@ public void testExceptionalMultipleElementAllAsList() CompletableFuture element2 = new CompletableFuture<>(); CompletableFuture> future = allAsList(ImmutableList.of(element1, element2)); - assertFalse(future.isDone()); - assertFalse(future.isCompletedExceptionally()); - assertFalse(future.isCancelled()); + assertThat(future.isDone()).isFalse(); + assertThat(future.isCompletedExceptionally()).isFalse(); + assertThat(future.isCancelled()).isFalse(); element1.completeExceptionally(new RuntimeException()); - assertTrue(future.isDone()); - assertTrue(future.isCompletedExceptionally()); - assertFalse(future.isCancelled()); + assertThat(future.isDone()).isTrue(); + assertThat(future.isCompletedExceptionally()).isTrue(); + assertThat(future.isCancelled()).isFalse(); } @Test(expectedExceptions = UnsupportedOperationException.class) @@ -573,14 +565,14 @@ public void testListenableTimeout() SettableFuture rootFuture = SettableFuture.create(); ListenableFuture timeoutFuture = addTimeout(rootFuture, () -> "timeout", new Duration(0, MILLISECONDS), executorService); - assertEquals(tryGetFutureValue(timeoutFuture, 10, SECONDS).orElse("failed"), "timeout"); - assertTrue(timeoutFuture.isDone()); - assertFalse(timeoutFuture.isCancelled()); + assertThat(tryGetFutureValue(timeoutFuture, 10, SECONDS).orElse("failed")).isEqualTo("timeout"); + assertThat(timeoutFuture.isDone()).isTrue(); + assertThat(timeoutFuture.isCancelled()).isFalse(); // root exception is cancelled on a timeout assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); - assertTrue(rootFuture.isDone()); - assertTrue(rootFuture.isCancelled()); + assertThat(rootFuture.isDone()).isTrue(); + assertThat(rootFuture.isCancelled()).isTrue(); } @Test @@ -594,13 +586,13 @@ public void testListenableTimeoutExceptionValue() assertInstanceOf(e, SQLException.class); assertEquals(e.getMessage(), "timeout"); }); - assertTrue(timeoutFuture.isDone()); - assertFalse(timeoutFuture.isCancelled()); + assertThat(timeoutFuture.isDone()).isTrue(); + assertThat(timeoutFuture.isCancelled()).isFalse(); // root exception is cancelled on a timeout assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); - assertTrue(rootFuture.isDone()); - assertTrue(rootFuture.isCancelled()); + assertThat(rootFuture.isDone()).isTrue(); + assertThat(rootFuture.isCancelled()).isTrue(); } @Test @@ -611,16 +603,16 @@ public void testListenableTimeoutCancel() ListenableFuture timeoutFuture = addTimeout(rootFuture, () -> "timeout", new Duration(10, SECONDS), executorService); // check timeout - assertEquals(tryGetFutureValue(timeoutFuture, 10, MILLISECONDS), Optional.empty()); + assertThat(tryGetFutureValue(timeoutFuture, 10, MILLISECONDS)).isEqualTo(Optional.empty()); - assertTrue(timeoutFuture.cancel(true)); - assertTrue(timeoutFuture.isDone()); - assertTrue(timeoutFuture.isCancelled()); + assertThat(timeoutFuture.cancel(true)).isTrue(); + assertThat(timeoutFuture.isDone()).isTrue(); + assertThat(timeoutFuture.isCancelled()).isTrue(); // root exception is cancelled on a timeout assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); - assertTrue(rootFuture.isDone()); - assertTrue(rootFuture.isCancelled()); + assertThat(rootFuture.isDone()).isTrue(); + assertThat(rootFuture.isCancelled()).isTrue(); } @Test @@ -630,14 +622,14 @@ public void testTimeout() CompletableFuture rootFuture = new CompletableFuture<>(); CompletableFuture timeoutFuture = addTimeout(rootFuture, () -> "timeout", new Duration(0, MILLISECONDS), executorService); - assertEquals(tryGetFutureValue(timeoutFuture, 10, SECONDS).orElse("failed"), "timeout"); - assertTrue(timeoutFuture.isDone()); - assertFalse(timeoutFuture.isCancelled()); + assertThat(tryGetFutureValue(timeoutFuture, 10, SECONDS).orElse("failed")).isEqualTo("timeout"); + assertThat(timeoutFuture.isDone()).isTrue(); + assertThat(timeoutFuture.isCancelled()).isFalse(); // root exception is cancelled on a timeout assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); - assertTrue(rootFuture.isDone()); - assertTrue(rootFuture.isCancelled()); + assertThat(rootFuture.isDone()).isTrue(); + assertThat(rootFuture.isCancelled()).isTrue(); } @Test @@ -651,13 +643,13 @@ public void testTimeoutExceptionValue() assertInstanceOf(e, SQLException.class); assertEquals(e.getMessage(), "timeout"); }); - assertTrue(timeoutFuture.isDone()); - assertFalse(timeoutFuture.isCancelled()); + assertThat(timeoutFuture.isDone()).isTrue(); + assertThat(timeoutFuture.isCancelled()).isFalse(); // root exception is cancelled on a timeout assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); - assertTrue(rootFuture.isDone()); - assertTrue(rootFuture.isCancelled()); + assertThat(rootFuture.isDone()).isTrue(); + assertThat(rootFuture.isCancelled()).isTrue(); } @Test @@ -668,22 +660,22 @@ public void testTimeoutCancel() CompletableFuture timeoutFuture = addTimeout(rootFuture, () -> "timeout", new Duration(10, SECONDS), executorService); // check timeout - assertEquals(tryGetFutureValue(timeoutFuture, 10, MILLISECONDS), Optional.empty()); + assertThat(tryGetFutureValue(timeoutFuture, 10, MILLISECONDS)).isEqualTo(Optional.empty()); - assertTrue(timeoutFuture.cancel(true)); - assertTrue(timeoutFuture.isDone()); - assertTrue(timeoutFuture.isCancelled()); + assertThat(timeoutFuture.cancel(true)).isTrue(); + assertThat(timeoutFuture.isDone()).isTrue(); + assertThat(timeoutFuture.isCancelled()).isTrue(); // root exception is cancelled on a timeout assertFailure(() -> rootFuture.get(10, SECONDS), e -> assertInstanceOf(e, CancellationException.class)); - assertTrue(rootFuture.isDone()); - assertTrue(rootFuture.isCancelled()); + assertThat(rootFuture.isDone()).isTrue(); + assertThat(rootFuture.isCancelled()).isTrue(); } @Test public void testGetDone() { - assertEquals(getDone(immediateFuture("Alice")), "Alice"); + assertThat(getDone(immediateFuture("Alice"))).isEqualTo("Alice"); assertFailure(() -> getDone(immediateFailedFuture(new IllegalStateException("some failure"))), expect(IllegalStateException.class, "some failure")); @@ -738,7 +730,7 @@ public void testAllAsListWithCancellationOnFailure() private static void assertGetUncheckedListenable(Function, Object> getter) throws Exception { - assertEquals(getter.apply(immediateFuture("foo")), "foo"); + assertThat(getter.apply(immediateFuture("foo"))).isEqualTo("foo"); assertFailure(() -> getter.apply(immediateFailedFuture(new IllegalArgumentException("foo"))), e -> { assertInstanceOf(e, IllegalArgumentException.class); @@ -757,13 +749,13 @@ private static void assertGetUncheckedListenable(Function canceledFuture = SettableFuture.create(); canceledFuture.cancel(true); assertFailure(() -> getter.apply(canceledFuture), e -> assertInstanceOf(e, CancellationException.class)); - assertEquals(getter.apply(immediateFuture(null)), null); + assertThat(getter.apply(immediateFuture(null))).isEqualTo(null); } private void assertGetUnchecked(UncheckedGetter getter) @@ -778,7 +770,7 @@ private void assertGetUnchecked(UncheckedGetter getter) private static void assertGetUncheckedInternal(UncheckedGetter getter) throws Exception { - assertEquals(getter.get(completedFuture("foo")), "foo"); + assertThat(getter.get(completedFuture("foo"))).isEqualTo("foo"); assertFailure(() -> getter.get(failedFuture(new IllegalArgumentException("foo"))), e -> { assertInstanceOf(e, IllegalArgumentException.class); @@ -797,13 +789,13 @@ private static void assertGetUncheckedInternal(UncheckedGetter getter) assertInstanceOf(e.getCause(), InterruptedException.class); assertTrue(Thread.interrupted()); }); - assertFalse(Thread.currentThread().isInterrupted()); + assertThat(Thread.currentThread().isInterrupted()).isFalse(); CompletableFuture canceledFuture = new CompletableFuture<>(); canceledFuture.cancel(true); assertFailure(() -> getter.get(canceledFuture), e -> assertInstanceOf(e, CancellationException.class)); - assertEquals(getter.get(completedFuture(null)), null); + assertThat(getter.get(completedFuture(null))).isEqualTo(null); } private static void assertFailure(Thrower thrower, Consumer verifier) @@ -826,7 +818,7 @@ private static Consumer expect(Class expectedCla private static Consumer expect(Class expectedClass, String expectedMessagePattern, Consumer causeVerifier) { return e -> { - assertNotNull(e, "exception is null"); + assertThat(e).as("exception is null").isNotNull(); if (!expectedClass.isInstance(e) || !nullToEmpty(e.getMessage()).matches(expectedMessagePattern)) { fail(format("Expected %s with message '%s', got: %s", expectedClass, expectedMessagePattern, e)); } diff --git a/concurrent/src/test/java/io/airlift/concurrent/TestThreadLocalCache.java b/concurrent/src/test/java/io/airlift/concurrent/TestThreadLocalCache.java index 3f3db09916d..fc54457bded 100644 --- a/concurrent/src/test/java/io/airlift/concurrent/TestThreadLocalCache.java +++ b/concurrent/src/test/java/io/airlift/concurrent/TestThreadLocalCache.java @@ -17,7 +17,7 @@ import java.util.concurrent.atomic.AtomicInteger; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestThreadLocalCache { @@ -32,20 +32,20 @@ public void testSanity() }); // Load first key - assertEquals(cache.get("abc"), "abc0"); - assertEquals(cache.get("abc"), "abc0"); + assertThat(cache.get("abc")).isEqualTo("abc0"); + assertThat(cache.get("abc")).isEqualTo("abc0"); // Load second key - assertEquals(cache.get("def"), "def1"); + assertThat(cache.get("def")).isEqualTo("def1"); // First key should still be there - assertEquals(cache.get("abc"), "abc0"); + assertThat(cache.get("abc")).isEqualTo("abc0"); // Expire first key by exceeding max size - assertEquals(cache.get("ghi"), "ghi2"); + assertThat(cache.get("ghi")).isEqualTo("ghi2"); // First key should now be regenerated - assertEquals(cache.get("abc"), "abc3"); + assertThat(cache.get("abc")).isEqualTo("abc3"); // TODO: add tests for multiple threads } diff --git a/configuration/src/test/java/io/airlift/configuration/ProblemsTest.java b/configuration/src/test/java/io/airlift/configuration/ProblemsTest.java index 54124664ad3..8a4a0e53dcb 100644 --- a/configuration/src/test/java/io/airlift/configuration/ProblemsTest.java +++ b/configuration/src/test/java/io/airlift/configuration/ProblemsTest.java @@ -23,8 +23,8 @@ import static io.airlift.testing.Assertions.assertContains; import static io.airlift.testing.Assertions.assertContainsAllOf; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; public class ProblemsTest { @@ -35,10 +35,10 @@ public void testOneError() problems.addError("message %d", 1); List errors = problems.getErrors(); - assertEquals(errors.size(), 1); - assertEquals(errors.get(0).getMessage(), "message 1"); + assertThat(errors.size()).isEqualTo(1); + assertThat(errors.get(0).getMessage()).isEqualTo("message 1"); - assertEquals(problems.getWarnings().size(), 0, "Found unexpected warnings in problem object"); + assertThat(problems.getWarnings().size()).as("Found unexpected warnings in problem object").isEqualTo(0); try { problems.throwIfHasErrors(); @@ -57,11 +57,11 @@ public void testTwoErrors() problems.addError("message %d", 2); List errors = problems.getErrors(); - assertEquals(errors.size(), 2); - assertEquals(errors.get(0).getMessage(), "message 1"); - assertEquals(errors.get(1).getMessage(), "message 2"); + assertThat(errors.size()).isEqualTo(2); + assertThat(errors.get(0).getMessage()).isEqualTo("message 1"); + assertThat(errors.get(1).getMessage()).isEqualTo("message 2"); - assertEquals(problems.getWarnings().size(), 0, "Found unexpected warnings in problem object"); + assertThat(problems.getWarnings().size()).as("Found unexpected warnings in problem object").isEqualTo(0); try { problems.throwIfHasErrors(); @@ -79,10 +79,10 @@ public void testFormatError() problems.addError("message %d", "NaN"); List errors = problems.getErrors(); - assertEquals(errors.size(), 1); + assertThat(errors.size()).isEqualTo(1); assertContainsAllOf(errors.get(0).getMessage(), "message %d", "NaN", "IllegalFormatConversionException"); - assertEquals(problems.getWarnings().size(), 0, "Found unexpected warnings in problem object"); + assertThat(problems.getWarnings().size()).as("Found unexpected warnings in problem object").isEqualTo(0); try { problems.throwIfHasErrors(); @@ -99,17 +99,17 @@ public void testOneWarning() Problems problems = new Problems(); problems.addWarning("message %d", 1); - assertEquals(problems.getErrors().size(), 0, "Found unexpected errors in problem object"); + assertThat(problems.getErrors().size()).as("Found unexpected errors in problem object").isEqualTo(0); List warnings = problems.getWarnings(); - assertEquals(warnings.size(), 1); - assertEquals(warnings.get(0).getMessage(), "message 1"); + assertThat(warnings.size()).isEqualTo(1); + assertThat(warnings.get(0).getMessage()).isEqualTo("message 1"); try { problems.throwIfHasErrors(); } catch (ConfigurationException cause) { - fail("Didn't expect problems object to throw", cause); + org.assertj.core.api.Assertions.fail("Didn't expect problems object to throw", cause); } } @@ -120,18 +120,18 @@ public void testTwoWarnings() problems.addWarning("message %d", 1); problems.addWarning("message %d", 2); - assertEquals(problems.getErrors().size(), 0, "Found unexpected errors in problem object"); + assertThat(problems.getErrors().size()).as("Found unexpected errors in problem object").isEqualTo(0); List warnings = problems.getWarnings(); - assertEquals(warnings.size(), 2); - assertEquals(warnings.get(0).getMessage(), "message 1"); - assertEquals(warnings.get(1).getMessage(), "message 2"); + assertThat(warnings.size()).isEqualTo(2); + assertThat(warnings.get(0).getMessage()).isEqualTo("message 1"); + assertThat(warnings.get(1).getMessage()).isEqualTo("message 2"); try { problems.throwIfHasErrors(); } catch (ConfigurationException cause) { - fail("Didn't expect problems object to throw", cause); + org.assertj.core.api.Assertions.fail("Didn't expect problems object to throw", cause); } } @@ -141,17 +141,17 @@ public void testFormatWarning() Problems problems = new Problems(); problems.addWarning("message %d", "NaN"); - assertEquals(problems.getErrors().size(), 0, "Found unexpected errors in problem object"); + assertThat(problems.getErrors().size()).as("Found unexpected errors in problem object").isEqualTo(0); List warnings = problems.getWarnings(); - assertEquals(warnings.size(), 1); + assertThat(warnings.size()).isEqualTo(1); assertContainsAllOf(warnings.get(0).getMessage(), "message %d", "NaN", "IllegalFormatConversionException"); try { problems.throwIfHasErrors(); } catch (ConfigurationException cause) { - fail("Didn't expect problems object to throw", cause); + org.assertj.core.api.Assertions.fail("Didn't expect problems object to throw", cause); } } @@ -167,15 +167,15 @@ public void testErrorsAndWarnings() problems.addWarning("message w%d", 3); List errors = problems.getErrors(); - assertEquals(errors.size(), 2); - assertEquals(errors.get(0).getMessage(), "message e1"); - assertEquals(errors.get(1).getMessage(), "message e2"); + assertThat(errors.size()).isEqualTo(2); + assertThat(errors.get(0).getMessage()).isEqualTo("message e1"); + assertThat(errors.get(1).getMessage()).isEqualTo("message e2"); List warnings = problems.getWarnings(); - assertEquals(warnings.size(), 3); - assertEquals(warnings.get(0).getMessage(), "message w1"); - assertEquals(warnings.get(1).getMessage(), "message w2"); - assertEquals(warnings.get(2).getMessage(), "message w3"); + assertThat(warnings.size()).isEqualTo(3); + assertThat(warnings.get(0).getMessage()).isEqualTo("message w1"); + assertThat(warnings.get(1).getMessage()).isEqualTo("message w2"); + assertThat(warnings.get(2).getMessage()).isEqualTo("message w3"); try { problems.throwIfHasErrors(); diff --git a/configuration/src/test/java/io/airlift/configuration/TestConfig.java b/configuration/src/test/java/io/airlift/configuration/TestConfig.java index 9b6f1cfda74..5a35558a1a2 100644 --- a/configuration/src/test/java/io/airlift/configuration/TestConfig.java +++ b/configuration/src/test/java/io/airlift/configuration/TestConfig.java @@ -47,9 +47,10 @@ import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.within; public class TestConfig { @@ -121,7 +122,7 @@ public void testConfigDefaults() new StringOptionDefaults("default string"))); Config1 config = injector.getInstance(Config1.class); - assertEquals("default string", config.getStringOption()); + assertThat("default string").isEqualTo(config.getStringOption()); } @Test @@ -133,7 +134,7 @@ public void testConfigDefaultsWithAnnotationType() new StringOptionDefaults("default string"))); Config1 config = injector.getInstance(Key.get(Config1.class, MyAnnotation.class)); - assertEquals("default string", config.getStringOption()); + assertThat("default string").isEqualTo(config.getStringOption()); } @Test @@ -145,7 +146,7 @@ public void testConfigDefaultsWithAnnotationObject() new StringOptionDefaults("default string"))); Config1 config = injector.getInstance(Key.get(Config1.class, named("boo"))); - assertEquals("default string", config.getStringOption()); + assertThat("default string").isEqualTo(config.getStringOption()); } @Test @@ -159,7 +160,7 @@ public void testConfigDefaultsOverride() new StringOptionDefaults("final default string"))); Config1 config = injector.getInstance(Config1.class); - assertEquals("final default string", config.getStringOption()); + assertThat("final default string").isEqualTo(config.getStringOption()); } @Test @@ -176,27 +177,27 @@ public void testPropertiesOverrideDefaults() private static void verifyConfig(Config1 config) { - assertEquals("a string", config.getStringOption()); - assertEquals(true, config.getBooleanOption()); - assertEquals(Boolean.TRUE, config.getBoxedBooleanOption()); - assertEquals(Byte.MAX_VALUE, config.getByteOption()); - assertEquals(Byte.valueOf(Byte.MAX_VALUE), config.getBoxedByteOption()); - assertEquals(Short.MAX_VALUE, config.getShortOption()); - assertEquals(Short.valueOf(Short.MAX_VALUE), config.getBoxedShortOption()); - assertEquals(Integer.MAX_VALUE, config.getIntegerOption()); - assertEquals(Integer.valueOf(Integer.MAX_VALUE), config.getBoxedIntegerOption()); - assertEquals(Long.MAX_VALUE, config.getLongOption()); - assertEquals(Long.valueOf(Long.MAX_VALUE), config.getBoxedLongOption()); - assertEquals(Float.MAX_VALUE, config.getFloatOption(), 0); - assertEquals(Float.MAX_VALUE, config.getBoxedFloatOption()); - assertEquals(Double.MAX_VALUE, config.getDoubleOption(), 0); - assertEquals(Double.MAX_VALUE, config.getBoxedDoubleOption()); - assertEquals(FOO, config.getMyEnumOption()); - assertEquals(BAR, config.getMyEnumSecondOption()); - assertEquals(config.getValueClassOption().getValue(), "a value class"); - assertEquals(config.getMyEnumList(), ImmutableList.of(BAR, FOO)); - assertEquals(config.getMyEnumSet(), ImmutableSet.of(BAR, FOO)); - assertEquals(config.getMyIntegerList(), ImmutableList.of(10, 12, 14, 16)); + assertThat("a string").isEqualTo(config.getStringOption()); + assertThat(true).isEqualTo(config.getBooleanOption()); + assertThat(Boolean.TRUE).isEqualTo(config.getBoxedBooleanOption()); + assertThat(Byte.MAX_VALUE).isEqualTo(config.getByteOption()); + assertThat(Byte.valueOf(Byte.MAX_VALUE)).isEqualTo(config.getBoxedByteOption()); + assertThat(Short.MAX_VALUE).isEqualTo(config.getShortOption()); + assertThat(Short.valueOf(Short.MAX_VALUE)).isEqualTo(config.getBoxedShortOption()); + assertThat(Integer.MAX_VALUE).isEqualTo(config.getIntegerOption()); + assertThat(Integer.valueOf(Integer.MAX_VALUE)).isEqualTo(config.getBoxedIntegerOption()); + assertThat(Long.MAX_VALUE).isEqualTo(config.getLongOption()); + assertThat(Long.valueOf(Long.MAX_VALUE)).isEqualTo(config.getBoxedLongOption()); + assertThat(Float.MAX_VALUE).isCloseTo(config.getFloatOption(), within(0f)); + assertThat(Float.MAX_VALUE).isEqualTo(config.getBoxedFloatOption()); + assertThat(Double.MAX_VALUE).isCloseTo(config.getDoubleOption(), within(0.)); + assertThat(Double.MAX_VALUE).isEqualTo(config.getBoxedDoubleOption()); + assertThat(FOO).isEqualTo(config.getMyEnumOption()); + assertThat(BAR).isEqualTo(config.getMyEnumSecondOption()); + assertThat(config.getValueClassOption().getValue()).isEqualTo("a value class"); + assertThat(config.getMyEnumList()).isEqualTo(ImmutableList.of(BAR, FOO)); + assertThat(config.getMyEnumSet()).isEqualTo(ImmutableSet.of(BAR, FOO)); + assertThat(config.getMyIntegerList()).isEqualTo(ImmutableList.of(10, 12, 14, 16)); } @Test @@ -216,13 +217,13 @@ public void testDetectsNoConfigAnnotations() public void testConfigGlobalDefaults() throws Exception { - int globalDefaultValue = 1; + byte globalDefaultValue = 1; int defaultValue = 2; int customValue = 3; Module module = binder -> { configBinder(binder).bindConfigGlobalDefaults(Config1.class, (config -> { - config.setByteOption((byte) globalDefaultValue); + config.setByteOption(globalDefaultValue); config.setIntegerOption(globalDefaultValue); config.setLongOption(globalDefaultValue); })); @@ -236,9 +237,9 @@ public void testConfigGlobalDefaults() Injector injector = createInjector(ImmutableMap.of("longOption", "" + customValue), module); Config1 config = injector.getInstance(Key.get(Config1.class, MyAnnotation.class)); - assertEquals(config.getByteOption(), globalDefaultValue); - assertEquals(config.getIntegerOption(), defaultValue); - assertEquals(config.getLongOption(), customValue); + assertThat(config.getByteOption()).isEqualTo(globalDefaultValue); + assertThat(config.getIntegerOption()).isEqualTo(defaultValue); + assertThat(config.getLongOption()).isEqualTo(customValue); } @Test @@ -260,13 +261,11 @@ public void testConfigurationBindingListener() verifyConfig(injector.getInstance(Config1.class)); verifyConfig(injector.getInstance(Key.get(Config1.class, MyAnnotation.class))); - assertEquals(seenBindings.size(), 3); - assertEquals( - ImmutableSet.copyOf(seenBindings), - ImmutableSet.of( - new ConfigurationBinding<>(Key.get(Config1.class), Config1.class, Optional.empty()), - new ConfigurationBinding<>(Key.get(Config1.class, MyAnnotation.class), Config1.class, Optional.empty()), - new ConfigurationBinding<>(Key.get(AnotherConfig.class), AnotherConfig.class, Optional.empty()))); + assertThat(seenBindings.size()).isEqualTo(3); + assertThat(ImmutableSet.copyOf(seenBindings)).isEqualTo(ImmutableSet.of( + new ConfigurationBinding<>(Key.get(Config1.class), Config1.class, Optional.empty()), + new ConfigurationBinding<>(Key.get(Config1.class, MyAnnotation.class), Config1.class, Optional.empty()), + new ConfigurationBinding<>(Key.get(AnotherConfig.class), AnotherConfig.class, Optional.empty()))); } @Test @@ -299,12 +298,8 @@ protected void setup(Binder binder) } }; - assertEquals( - createInjector(ImmutableMap.of("value", "a"), module).getInstance(String.class), - "used value a"); - assertEquals( - createInjector(ImmutableMap.of("value", "b"), module).getInstance(String.class), - "used value b"); + assertThat(createInjector(ImmutableMap.of("value", "a"), module).getInstance(String.class)).isEqualTo("used value a"); + assertThat(createInjector(ImmutableMap.of("value", "b"), module).getInstance(String.class)).isEqualTo("used value b"); assertThatThrownBy(() -> createInjector(ImmutableMap.of("value", "c"), module)) .hasStackTraceContaining("Not supported value: C"); } diff --git a/configuration/src/test/java/io/airlift/configuration/TestConfigurationFactory.java b/configuration/src/test/java/io/airlift/configuration/TestConfigurationFactory.java index 4f831a89593..919d74fd17e 100644 --- a/configuration/src/test/java/io/airlift/configuration/TestConfigurationFactory.java +++ b/configuration/src/test/java/io/airlift/configuration/TestConfigurationFactory.java @@ -41,13 +41,9 @@ import static io.airlift.configuration.ConfigBinder.configBinder; import static java.lang.String.format; import static java.util.Objects.requireNonNull; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; public class TestConfigurationFactory { @@ -75,9 +71,9 @@ public void testAnnotatedSetters() AnnotatedSetter annotatedSetter = injector.getInstance(AnnotatedSetter.class); monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(0); - assertNotNull(annotatedSetter); - assertEquals(annotatedSetter.getStringValue(), "some value"); - assertTrue(annotatedSetter.isBooleanValue()); + assertThat(annotatedSetter).isNotNull(); + assertThat(annotatedSetter.getStringValue()).isEqualTo("some value"); + assertThat(annotatedSetter.isBooleanValue()).isTrue(); } @Test @@ -91,9 +87,9 @@ public void testConfigurationDespiteLegacyConfig() LegacyConfigPresent legacyConfigPresent = injector.getInstance(LegacyConfigPresent.class); monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(0); - assertNotNull(legacyConfigPresent); - assertEquals(legacyConfigPresent.getStringA(), "this is a"); - assertEquals(legacyConfigPresent.getStringB(), "this is b"); + assertThat(legacyConfigPresent).isNotNull(); + assertThat(legacyConfigPresent.getStringA()).isEqualTo("this is a"); + assertThat(legacyConfigPresent.getStringB()).isEqualTo("this is b"); } @Test @@ -108,9 +104,9 @@ public void testConfigurationThroughLegacyConfig() monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(1); monitor.assertMatchingWarningRecorded("Configuration property 'string-value' has been replaced. Use 'string-a' instead."); - assertNotNull(legacyConfigPresent); - assertEquals(legacyConfigPresent.getStringA(), "this is a"); - assertEquals(legacyConfigPresent.getStringB(), "this is b"); + assertThat(legacyConfigPresent).isNotNull(); + assertThat(legacyConfigPresent.getStringA()).isEqualTo("this is a"); + assertThat(legacyConfigPresent.getStringB()).isEqualTo("this is b"); } @Test @@ -125,9 +121,9 @@ public void testConfigurationWithPrefixThroughLegacyConfig() monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(1); monitor.assertMatchingWarningRecorded("Configuration property 'example.string-value' has been replaced. Use 'example.string-a' instead."); - assertNotNull(legacyConfigPresent); - assertEquals(legacyConfigPresent.getStringA(), "this is a"); - assertEquals(legacyConfigPresent.getStringB(), "this is b"); + assertThat(legacyConfigPresent).isNotNull(); + assertThat(legacyConfigPresent.getStringA()).isEqualTo("this is a"); + assertThat(legacyConfigPresent.getStringB()).isEqualTo("this is b"); } @Test @@ -168,9 +164,9 @@ public void testConfigurationDespiteDeprecatedConfig() DeprecatedConfigPresent deprecatedConfigPresent = injector.getInstance(DeprecatedConfigPresent.class); monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(0); - assertNotNull(deprecatedConfigPresent); - assertEquals(deprecatedConfigPresent.getStringA(), "defaultA"); - assertEquals(deprecatedConfigPresent.getStringB(), "this is b"); + assertThat(deprecatedConfigPresent).isNotNull(); + assertThat(deprecatedConfigPresent.getStringA()).isEqualTo("defaultA"); + assertThat(deprecatedConfigPresent.getStringB()).isEqualTo("this is b"); } @Test @@ -185,9 +181,9 @@ public void testConfigurationThroughDeprecatedConfig() monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(1); monitor.assertMatchingWarningRecorded("Configuration property 'string-a' is deprecated and should not be used"); - assertNotNull(deprecatedConfigPresent); - assertEquals(deprecatedConfigPresent.getStringA(), "this is a"); - assertEquals(deprecatedConfigPresent.getStringB(), "this is b"); + assertThat(deprecatedConfigPresent).isNotNull(); + assertThat(deprecatedConfigPresent.getStringA()).isEqualTo("this is a"); + assertThat(deprecatedConfigPresent.getStringB()).isEqualTo("this is b"); } @Test @@ -202,9 +198,9 @@ public void testConfigurationWithPrefixThroughDeprecatedConfig() monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(1); monitor.assertMatchingWarningRecorded("Configuration property 'example.string-a' is deprecated and should not be used"); - assertNotNull(deprecatedConfigPresent); - assertEquals(deprecatedConfigPresent.getStringA(), "this is a"); - assertEquals(deprecatedConfigPresent.getStringB(), "this is b"); + assertThat(deprecatedConfigPresent).isNotNull(); + assertThat(deprecatedConfigPresent.getStringA()).isEqualTo("this is a"); + assertThat(deprecatedConfigPresent.getStringB()).isEqualTo("this is b"); } @Test @@ -242,9 +238,9 @@ public void testSuccessfulBeanValidation() BeanValidationClass beanValidationClass = injector.getInstance(BeanValidationClass.class); monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(0); - assertNotNull(beanValidationClass); - assertEquals(beanValidationClass.getStringValue(), "has a value"); - assertEquals(beanValidationClass.getIntValue(), 50); + assertThat(beanValidationClass).isNotNull(); + assertThat(beanValidationClass.getStringValue()).isEqualTo("has a value"); + assertThat(beanValidationClass.getIntValue()).isEqualTo(50); } @Test @@ -287,7 +283,7 @@ public void testAcceptBooleanValue() Config1 config = requireNonNull(injector.getInstance(Config1.class), "injector.getInstance(Config1.class) is null"); monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(0); - assertTrue(config.getBooleanOption()); + assertThat(config.getBooleanOption()).isTrue(); } for (String value : ImmutableList.of("false", "FALSE", "fAlsE")) { @@ -298,7 +294,7 @@ public void testAcceptBooleanValue() Config1 config = requireNonNull(injector.getInstance(Config1.class), "injector.getInstance(Config1.class) is null"); monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(0); - assertFalse(config.getBooleanOption()); + assertThat(config.getBooleanOption()).isFalse(); } } @@ -396,7 +392,7 @@ public void testListOfStrings() { TestMonitor monitor = new TestMonitor(); Injector injector = createInjector(ImmutableMap.of("values", "ala, ma ,kota, "), monitor, binder -> configBinder(binder).bindConfig(ListOfStringsClass.class)); - assertEquals(injector.getInstance(ListOfStringsClass.class).getValues(), ImmutableList.of("ala", "ma", "kota")); + assertThat(injector.getInstance(ListOfStringsClass.class).getValues()).isEqualTo(ImmutableList.of("ala", "ma", "kota")); monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(0); } @@ -421,7 +417,7 @@ public void testStringConstructor() { TestMonitor monitor = new TestMonitor(); Injector injector = createInjector(ImmutableMap.of("value", "constructor-value"), monitor, binder -> configBinder(binder).bindConfig(StringConstructorClass.class)); - assertEquals(injector.getInstance(StringConstructorClass.class).value.string, "constructor-argument: constructor-value"); + assertThat(injector.getInstance(StringConstructorClass.class).value.string).isEqualTo("constructor-argument: constructor-value"); monitor.assertNumberOfErrors(0); monitor.assertNumberOfWarnings(0); @@ -442,7 +438,7 @@ public void testUsedProperties() ConfigurationFactory configurationFactory = new ConfigurationFactory(properties, null, new TestMonitor()); configurationFactory.registerConfigurationClasses(ImmutableList.of(binder -> configBinder(binder).bindConfig(AnnotatedSetter.class))); configurationFactory.validateRegisteredConfigurationProvider(); - assertEquals(configurationFactory.getUsedProperties(), ImmutableSet.of("string-value", "boolean-value")); + assertThat(configurationFactory.getUsedProperties()).hasSameElementsAs(ImmutableSet.of("string-value", "boolean-value")); } @Test @@ -456,7 +452,7 @@ public void testUsedPropertiesWithFailure() configurationFactory.registerConfigurationClasses(ImmutableList.of(binder -> configBinder(binder).bindConfig(AnnotatedSetter.class))); List messages = configurationFactory.validateRegisteredConfigurationProvider(); assertMessagesMatch(messages, ImmutableList.of(".*Invalid value 'invalid' for type boolean \\(property 'boolean-value'\\).*AnnotatedSetter.*")); - assertEquals(configurationFactory.getUsedProperties(), properties.keySet()); + assertThat(configurationFactory.getUsedProperties()).isEqualTo(properties.keySet()); } private static Injector createInjector(Map properties, TestMonitor monitor, Module module) @@ -464,7 +460,7 @@ private static Injector createInjector(Map properties, TestMonit ConfigurationFactory configurationFactory = new ConfigurationFactory(properties, null, monitor); configurationFactory.registerConfigurationClasses(ImmutableList.of(module)); List messages = configurationFactory.validateRegisteredConfigurationProvider(); - assertEquals(configurationFactory.getUsedProperties(), properties.keySet()); + assertThat(configurationFactory.getUsedProperties()).hasSameElementsAs(properties.keySet()); return Guice.createInjector(new ConfigurationModule(configurationFactory), module, new ValidationErrorModule(messages)); } @@ -503,7 +499,7 @@ private static void assertInvalidConfig(Map properties, Module m private static void assertMessagesMatch(Collection messages, List expectedErrorMessagePatterns) { - assertEquals(messages.size(), expectedErrorMessagePatterns.size(), "expected error count"); + assertThat(messages.size()).as("expected error count").isEqualTo(expectedErrorMessagePatterns.size()); List patterns = expectedErrorMessagePatterns.stream() .map(Pattern::compile) @@ -515,13 +511,13 @@ private static void assertMessagesMatch(Collection messages, L Pattern matchedPattern = null; for (Pattern pattern : patterns) { if (pattern.matcher(messageString).matches()) { - assertNull(matchedPattern, format("Error message matches two patterns patterns:\nmessage:\n %s\npatterns:\n %s\n %s", messageString, matchedPattern, pattern)); + assertThat(matchedPattern).as(format("Error message matches two patterns patterns:\nmessage:\n %s\npatterns:\n %s\n %s", messageString, matchedPattern, pattern)).isNull(); String usedMatch = usedPatterns.put(pattern, messageString); - assertNull(usedMatch, format("Pattern '%s' matches message '%s' and '%s", pattern, messageString, usedMatch)); + assertThat(usedMatch).as(format("Pattern '%s' matches message '%s' and '%s", pattern, messageString, usedMatch)).isNull(); matchedPattern = pattern; } } - assertNotNull(matchedPattern, format("Error message did not match any expected patterns:\nmessage:\n %s\npatterns:\n %s", messageString, Joiner.on("\n ").join(patterns))); + assertThat(matchedPattern).as(format("Error message did not match any expected patterns:\nmessage:\n %s\npatterns:\n %s", messageString, Joiner.on("\n ").join(patterns))).isNotNull(); } } diff --git a/configuration/src/test/java/io/airlift/configuration/TestConfigurationInspector.java b/configuration/src/test/java/io/airlift/configuration/TestConfigurationInspector.java index 45c827070ee..13c67faf28a 100644 --- a/configuration/src/test/java/io/airlift/configuration/TestConfigurationInspector.java +++ b/configuration/src/test/java/io/airlift/configuration/TestConfigurationInspector.java @@ -13,7 +13,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.MoreCollectors.onlyElement; import static io.airlift.configuration.ConfigBinder.configBinder; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestConfigurationInspector { @@ -24,7 +24,7 @@ public void testDefaultValue() .stream() .map(ConfigAttribute::getDefaultValue) .collect(toImmutableList()); - assertEquals(defaultString, ImmutableList.of("----")); + assertThat(defaultString).isEqualTo(ImmutableList.of("----")); } @Test @@ -34,7 +34,7 @@ public void testCurrentValue() .stream() .map(ConfigAttribute::getCurrentValue) .collect(toImmutableList()); - assertEquals(currentString, ImmutableList.of("string")); + assertThat(currentString).isEqualTo(ImmutableList.of("string")); } private ConfigRecord getConfigRecord() diff --git a/configuration/src/test/java/io/airlift/configuration/TestConfigurationLoader.java b/configuration/src/test/java/io/airlift/configuration/TestConfigurationLoader.java index 4e6afb38c44..ba819c04d84 100644 --- a/configuration/src/test/java/io/airlift/configuration/TestConfigurationLoader.java +++ b/configuration/src/test/java/io/airlift/configuration/TestConfigurationLoader.java @@ -30,7 +30,7 @@ import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE; import static io.airlift.configuration.ConfigurationLoader.loadProperties; import static java.nio.file.Files.createTempDirectory; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestConfigurationLoader { @@ -58,7 +58,7 @@ public void testLoadsFromSystemProperties() Map properties = loadProperties(); - assertEquals(properties.get("test"), "foo"); + assertThat(properties.get("test")).isEqualTo("foo"); System.clearProperty("test"); } @@ -72,8 +72,8 @@ public void testLoadsFromFile() Map properties = loadProperties(); - assertEquals(properties.get("test"), "foo"); - assertEquals(properties.get("config"), file.getAbsolutePath()); + assertThat(properties.get("test")).isEqualTo("foo"); + assertThat(properties.get("config")).isEqualTo(file.getAbsolutePath()); System.clearProperty("config"); } @@ -92,10 +92,10 @@ public void testTrimWhitespaceFromFile() Map properties = loadProperties(); // config files are often human-managed and we need to be permissive, stripping trailing whitespace if any - assertEquals(properties.get("trim-whitespace-key1"), "key1-value"); + assertThat(properties.get("trim-whitespace-key1")).isEqualTo("key1-value"); // trailing whitespace in JVM property value is not so likely to be unintentional, so preserve it - assertEquals(properties.get("trim-whitespace-key2"), " \t key2-value \t "); + assertThat(properties.get("trim-whitespace-key2")).isEqualTo(" \t key2-value \t "); System.clearProperty("trim-whitespace-key2"); System.clearProperty("config"); @@ -114,9 +114,9 @@ public void testSystemOverridesFile() Map properties = loadProperties(); - assertEquals(properties.get("config"), file.getAbsolutePath()); - assertEquals(properties.get("key1"), "overridden"); - assertEquals(properties.get("key2"), "original"); + assertThat(properties.get("config")).isEqualTo(file.getAbsolutePath()); + assertThat(properties.get("key1")).isEqualTo("overridden"); + assertThat(properties.get("key2")).isEqualTo("original"); System.clearProperty("key1"); System.clearProperty("config"); diff --git a/configuration/src/test/java/io/airlift/configuration/TestConfigurationMetadata.java b/configuration/src/test/java/io/airlift/configuration/TestConfigurationMetadata.java index 15bd3e36e23..16121306c90 100644 --- a/configuration/src/test/java/io/airlift/configuration/TestConfigurationMetadata.java +++ b/configuration/src/test/java/io/airlift/configuration/TestConfigurationMetadata.java @@ -28,8 +28,8 @@ import java.util.Set; import static io.airlift.testing.EquivalenceTester.equivalenceTester; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; public class TestConfigurationMetadata { @@ -870,10 +870,10 @@ private void verifyMetaData(ConfigurationMetadata metadata, Class configCl private void verifyMetaData(ConfigurationMetadata metadata, Class configClass, String description, boolean securitySensitive, boolean hidden, Map> attributeProperties) throws Exception { - assertEquals(metadata.getConfigClass(), configClass); + assertThat(metadata.getConfigClass()).isEqualTo(configClass); if (metadata.getConstructor() != null) { - assertEquals(metadata.getConstructor(), configClass.getDeclaredConstructor()); + assertThat(metadata.getConstructor()).isEqualTo(configClass.getDeclaredConstructor()); } else { try { @@ -884,20 +884,20 @@ private void verifyMetaData(ConfigurationMetadata metadata, Class configCl } } - assertEquals(metadata.getAttributes().size(), attributeProperties.keySet().size()); + assertThat(metadata.getAttributes().size()).isEqualTo(attributeProperties.keySet().size()); for (String name : attributeProperties.keySet()) { AttributeMetadata attribute = metadata.getAttributes().get(name); - assertEquals(attribute.getConfigClass(), configClass); + assertThat(attribute.getConfigClass()).isEqualTo(configClass); Set namesToTest = new HashSet<>(); namesToTest.add(attribute.getInjectionPoint().getProperty()); for (ConfigurationMetadata.InjectionPointMetaData legacyInjectionPoint : attribute.getLegacyInjectionPoints()) { namesToTest.add(legacyInjectionPoint.getProperty()); } - assertEquals(namesToTest, attributeProperties.get(name)); - assertEquals(attribute.getDescription(), description); - assertEquals(attribute.isSecuritySensitive(), securitySensitive); - assertEquals(attribute.isHidden(), hidden); + assertThat(namesToTest).isEqualTo(attributeProperties.get(name)); + assertThat(attribute.getDescription()).isEqualTo(description); + assertThat(attribute.isSecuritySensitive()).isEqualTo(securitySensitive); + assertThat(attribute.isHidden()).isEqualTo(hidden); } } diff --git a/configuration/src/test/java/io/airlift/configuration/TestConfigurationUtils.java b/configuration/src/test/java/io/airlift/configuration/TestConfigurationUtils.java index 25721b53edc..8cad52f2184 100644 --- a/configuration/src/test/java/io/airlift/configuration/TestConfigurationUtils.java +++ b/configuration/src/test/java/io/airlift/configuration/TestConfigurationUtils.java @@ -9,7 +9,6 @@ import static io.airlift.configuration.ConfigurationUtils.replaceEnvironmentVariables; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; public class TestConfigurationUtils { @@ -59,7 +58,7 @@ public void testEnvironmentVariableReplacement() .put("no-recursive-replacement", "env-first:${ENV:SECOND}:, env-second:${ENV:FIRST}") .build(); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); assertThat(errors).containsExactly( "Configuration property 'peach' references unset environment variable 'PEACH'", diff --git a/configuration/src/test/java/io/airlift/configuration/TestMonitor.java b/configuration/src/test/java/io/airlift/configuration/TestMonitor.java index eb909748b71..87a1004db05 100644 --- a/configuration/src/test/java/io/airlift/configuration/TestMonitor.java +++ b/configuration/src/test/java/io/airlift/configuration/TestMonitor.java @@ -21,8 +21,8 @@ import java.util.ArrayList; import java.util.List; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; class TestMonitor implements Problems.Monitor @@ -54,12 +54,12 @@ public List getWarnings() public void assertNumberOfErrors(int expected) { - assertEquals(errors.size(), expected, String.format("Number of errors is incorrect, actual errors: %s", errorsString())); + assertThat(errors.size()).as(String.format("Number of errors is incorrect, actual errors: %s", errorsString())).isEqualTo(expected); } public void assertNumberOfWarnings(int expected) { - assertEquals(warnings.size(), expected, String.format("Number of warnings is incorrect, actual warnings: %s", warningsString())); + assertThat(warnings.size()).as(String.format("Number of warnings is incorrect, actual warnings: %s", warningsString())).isEqualTo(expected); } public void assertMatchingWarningRecorded(String... parts) diff --git a/configuration/src/test/java/io/airlift/configuration/testing/TestConfigAssertions.java b/configuration/src/test/java/io/airlift/configuration/testing/TestConfigAssertions.java index 61d28733ee7..7e85171ff07 100644 --- a/configuration/src/test/java/io/airlift/configuration/testing/TestConfigAssertions.java +++ b/configuration/src/test/java/io/airlift/configuration/testing/TestConfigAssertions.java @@ -33,9 +33,9 @@ import java.util.Objects; import static io.airlift.testing.Assertions.assertContains; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.testng.Assert.assertNotSame; -import static org.testng.Assert.fail; public class TestConfigAssertions { @@ -441,21 +441,21 @@ public void testRecordDefaults() PersonConfig instance = data.getInstance(); assertNotSame(instance, config); - assertEquals(data.getInvokedMethods(), ImmutableSet.of( + assertThat(data.getInvokedMethods()).isEqualTo(ImmutableSet.of( PersonConfig.class.getMethod("setName", String.class), PersonConfig.class.getMethod("setEmail", String.class), PersonConfig.class.getMethod("setPhone", String.class), PersonConfig.class.getMethod("setHomePage", URI.class))); - assertEquals(instance.getName(), "Alice Apple"); - assertEquals(instance.getEmail(), "alice@example.com"); - assertEquals(instance.getPhone(), "1-976-alice"); - assertEquals(instance.getHomePage(), URI.create("http://alice.example.com")); + assertThat(instance.getName()).isEqualTo("Alice Apple"); + assertThat(instance.getEmail()).isEqualTo("alice@example.com"); + assertThat(instance.getPhone()).isEqualTo("1-976-alice"); + assertThat(instance.getHomePage()).isEqualTo(URI.create("http://alice.example.com")); - assertEquals(config.getName(), "Alice Apple"); - assertEquals(config.getEmail(), "alice@example.com"); - assertEquals(config.getPhone(), "1-976-alice"); - assertEquals(config.getHomePage(), URI.create("http://alice.example.com")); + assertThat(config.getName()).isEqualTo("Alice Apple"); + assertThat(config.getEmail()).isEqualTo("alice@example.com"); + assertThat(config.getPhone()).isEqualTo("1-976-alice"); + assertThat(config.getHomePage()).isEqualTo(URI.create("http://alice.example.com")); } @Test diff --git a/discovery/pom.xml b/discovery/pom.xml index a2b58cc83be..7d9976638b5 100644 --- a/discovery/pom.xml +++ b/discovery/pom.xml @@ -104,6 +104,12 @@ test + + org.assertj + assertj-core + test + + org.eclipse.jetty jetty-server diff --git a/discovery/src/test/java/io/airlift/discovery/client/AbstractTestDiscoveryModule.java b/discovery/src/test/java/io/airlift/discovery/client/AbstractTestDiscoveryModule.java index 4c7759b7846..671b511f892 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/AbstractTestDiscoveryModule.java +++ b/discovery/src/test/java/io/airlift/discovery/client/AbstractTestDiscoveryModule.java @@ -33,9 +33,7 @@ import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder; import static io.airlift.discovery.client.ServiceTypes.serviceType; import static java.util.Objects.requireNonNull; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public abstract class AbstractTestDiscoveryModule { @@ -56,12 +54,12 @@ public void testBinding() discoveryModule); // should produce a discovery announcement client and a lookup client - assertNotNull(injector.getInstance(DiscoveryAnnouncementClient.class)); - assertNotNull(injector.getInstance(DiscoveryLookupClient.class)); + assertThat(injector.getInstance(DiscoveryAnnouncementClient.class)).isNotNull(); + assertThat(injector.getInstance(DiscoveryLookupClient.class)).isNotNull(); // should produce an Announcer - assertNotNull(injector.getInstance(Announcer.class)); + assertThat(injector.getInstance(Announcer.class)).isNotNull(); // should produce a ServiceSelectorManager - assertNotNull(injector.getInstance(ServiceSelectorManager.class)); + assertThat(injector.getInstance(ServiceSelectorManager.class)).isNotNull(); } @Test @@ -95,15 +93,15 @@ public void testMerging() }); HttpServiceSelector selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("apple"))); - assertEquals(selector.selectHttpService().stream().collect(onlyElement()), URI.create("http://127.0.0.1:4444")); + assertThat(selector.selectHttpService().stream().collect(onlyElement())).isEqualTo(URI.create("http://127.0.0.1:4444")); selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("banana"))); - assertEquals(selector.selectHttpService().stream().collect(onlyElement()), URI.create("http://127.0.0.1:4444")); + assertThat(selector.selectHttpService().stream().collect(onlyElement())).isEqualTo(URI.create("http://127.0.0.1:4444")); selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("carrot"))); - assertTrue(selector.selectHttpService().isEmpty()); + assertThat(selector.selectHttpService().isEmpty()).isTrue(); selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("grape"))); - assertTrue(selector.selectHttpService().isEmpty()); + assertThat(selector.selectHttpService().isEmpty()).isTrue(); } } diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestAnnouncement.java b/discovery/src/test/java/io/airlift/discovery/client/TestAnnouncement.java index e916b2931a7..8a3e6c6816a 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestAnnouncement.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestAnnouncement.java @@ -29,8 +29,7 @@ import static io.airlift.json.JsonCodec.mapJsonCodec; import static io.airlift.testing.EquivalenceTester.equivalenceTester; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestAnnouncement { @@ -55,7 +54,7 @@ public void testJsonEncode() List> services = toServices(expected.get("services")); services.get(0).put("id", announcement.getServices().stream().collect(onlyElement()).getId().toString()); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } @SuppressWarnings("unchecked") @@ -67,11 +66,11 @@ private static List> toServices(Object value) @Test public void testToString() { - assertNotNull(new Announcement("environment", "node", "pool", "location", ImmutableSet.of( + assertThat(new Announcement("environment", "node", "pool", "location", ImmutableSet.of( serviceAnnouncement("foo") .addProperty("http", "http://localhost:8080") .addProperty("jmx", "jmx://localhost:1234") - .build()))); + .build()))).isNotNull(); } @Test diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestAnnouncer.java b/discovery/src/test/java/io/airlift/discovery/client/TestAnnouncer.java index 4272fe84987..305fd0381eb 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestAnnouncer.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestAnnouncer.java @@ -33,9 +33,8 @@ import static io.airlift.concurrent.MoreFutures.getFutureValue; import static io.airlift.discovery.client.ServiceTypes.serviceType; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; @Test(singleThreaded = true) public class TestAnnouncer @@ -151,13 +150,13 @@ private void assertAnnounced(ServiceAnnouncement... serviceAnnouncements) Future future = discoveryClient.getServices(serviceType.value(), "pool"); ServiceDescriptors serviceDescriptors = getFutureValue(future, DiscoveryException.class); - assertEquals(serviceDescriptors.getType(), serviceType.value()); - assertEquals(serviceDescriptors.getPool(), "pool"); - assertNotNull(serviceDescriptors.getETag()); - assertEquals(serviceDescriptors.getMaxAge(), MAX_AGE); + assertThat(serviceDescriptors.getType()).isEqualTo(serviceType.value()); + assertThat(serviceDescriptors.getPool()).isEqualTo("pool"); + assertThat(serviceDescriptors.getETag()).isNotNull(); + assertThat(serviceDescriptors.getMaxAge()).isEqualTo(MAX_AGE); List descriptors = serviceDescriptors.getServiceDescriptors(); - assertEquals(descriptors.size(), serviceAnnouncements.length); + assertThat(descriptors.size()).isEqualTo(serviceAnnouncements.length); ImmutableMap.Builder builder = ImmutableMap.builder(); for (ServiceDescriptor descriptor : descriptors) { @@ -167,12 +166,12 @@ private void assertAnnounced(ServiceAnnouncement... serviceAnnouncements) for (ServiceAnnouncement serviceAnnouncement : serviceAnnouncements) { ServiceDescriptor serviceDescriptor = descriptorMap.get(serviceAnnouncement.getId()); - assertNotNull(serviceDescriptor, "No descriptor for announcement " + serviceAnnouncement.getId()); - assertEquals(serviceDescriptor.getType(), serviceType.value()); - assertEquals(serviceDescriptor.getPool(), "pool"); - assertEquals(serviceDescriptor.getId(), serviceAnnouncement.getId()); - assertEquals(serviceDescriptor.getProperties(), serviceAnnouncement.getProperties()); - assertEquals(serviceDescriptor.getNodeId(), nodeInfo.getNodeId()); + assertThat(serviceDescriptor).as("No descriptor for announcement " + serviceAnnouncement.getId()).isNotNull(); + assertThat(serviceDescriptor.getType()).isEqualTo(serviceType.value()); + assertThat(serviceDescriptor.getPool()).isEqualTo("pool"); + assertThat(serviceDescriptor.getId()).isEqualTo(serviceAnnouncement.getId()); + assertThat(serviceDescriptor.getProperties()).isEqualTo(serviceAnnouncement.getProperties()); + assertThat(serviceDescriptor.getNodeId()).isEqualTo(nodeInfo.getNodeId()); } } } diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestCachingServiceSelector.java b/discovery/src/test/java/io/airlift/discovery/client/TestCachingServiceSelector.java index 70ae84ad181..23bef1e1443 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestCachingServiceSelector.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestCachingServiceSelector.java @@ -29,7 +29,7 @@ import static io.airlift.concurrent.Threads.daemonThreadsNamed; import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestCachingServiceSelector { @@ -64,8 +64,8 @@ public void testBasics() new InMemoryDiscoveryClient(nodeInfo), executor); - assertEquals(serviceSelector.getType(), "type"); - assertEquals(serviceSelector.getPool(), "pool"); + assertThat(serviceSelector.getType()).isEqualTo("type"); + assertThat(serviceSelector.getPool()).isEqualTo("pool"); } @Test @@ -76,7 +76,7 @@ public void testNotStartedEmpty() new InMemoryDiscoveryClient(nodeInfo), executor); - assertEquals(serviceSelector.selectAllServices(), ImmutableList.of()); + assertThat(serviceSelector.selectAllServices()).isEqualTo(ImmutableList.of()); } @Test @@ -90,7 +90,7 @@ public void testStartedEmpty() serviceSelector.start(); - assertEquals(serviceSelector.selectAllServices(), ImmutableList.of()); + assertThat(serviceSelector.selectAllServices()).isEqualTo(ImmutableList.of()); } @Test @@ -107,7 +107,7 @@ public void testNotStartedWithServices() discoveryClient, executor); - assertEquals(serviceSelector.selectAllServices(), ImmutableList.of()); + assertThat(serviceSelector.selectAllServices()).isEqualTo(ImmutableList.of()); } @Test diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestDiscoveryBinder.java b/discovery/src/test/java/io/airlift/discovery/client/TestDiscoveryBinder.java index 4f7f22797a8..22b6ca76291 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestDiscoveryBinder.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestDiscoveryBinder.java @@ -35,8 +35,7 @@ import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder; import static io.airlift.discovery.client.ServiceTypes.serviceType; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestDiscoveryBinder { @@ -49,7 +48,7 @@ public void testBindSelector() binder -> discoveryBinder(binder).bindServiceAnnouncement(new ServiceAnnouncementProvider().get())); Set announcements = injector.getInstance(Key.get(new TypeLiteral>() {})); - assertEquals(announcements, ImmutableSet.of(ANNOUNCEMENT)); + assertThat(announcements).isEqualTo(ImmutableSet.of(ANNOUNCEMENT)); } @Test @@ -61,7 +60,7 @@ public void testBindSelectorProviderClass() binder -> discoveryBinder(binder).bindServiceAnnouncement(ServiceAnnouncementProvider.class)); Set announcements = injector.getInstance(Key.get(new TypeLiteral>() {})); - assertEquals(announcements, ImmutableSet.of(ANNOUNCEMENT)); + assertThat(announcements).isEqualTo(ImmutableSet.of(ANNOUNCEMENT)); } @Test @@ -73,7 +72,7 @@ public void testBindSelectorProviderInstance() binder -> discoveryBinder(binder).bindServiceAnnouncement(new ServiceAnnouncementProvider())); Set announcements = injector.getInstance(Key.get(new TypeLiteral>() {})); - assertEquals(announcements, ImmutableSet.of(ANNOUNCEMENT)); + assertThat(announcements).isEqualTo(ImmutableSet.of(ANNOUNCEMENT)); } @Test @@ -123,9 +122,9 @@ public void testBindSelectorAnnotationWithPool() private void assertCanCreateServiceSelector(Injector injector, String expectedType, String expectedPool) { ServiceSelector actualServiceSelector = injector.getInstance(Key.get(ServiceSelector.class, serviceType(expectedType))); - assertNotNull(actualServiceSelector); - assertEquals(actualServiceSelector.getType(), expectedType); - assertEquals(actualServiceSelector.getPool(), expectedPool); + assertThat(actualServiceSelector).isNotNull(); + assertThat(actualServiceSelector.getType()).isEqualTo(expectedType); + assertThat(actualServiceSelector.getPool()).isEqualTo(expectedPool); } private static class TestModule diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestDiscoveryModule.java b/discovery/src/test/java/io/airlift/discovery/client/TestDiscoveryModule.java index e7eee29363d..40554b78509 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestDiscoveryModule.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestDiscoveryModule.java @@ -11,8 +11,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestDiscoveryModule extends AbstractTestDiscoveryModule @@ -37,8 +36,8 @@ public void testExecutorShutdown() ExecutorService executor = injector.getInstance(Key.get(ScheduledExecutorService.class, ForDiscoveryClient.class)); LifeCycleManager lifeCycleManager = injector.getInstance(LifeCycleManager.class); - assertFalse(executor.isShutdown()); + assertThat(executor.isShutdown()).isFalse(); lifeCycleManager.stop(); - assertTrue(executor.isShutdown()); + assertThat(executor.isShutdown()).isTrue(); } } diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestHttpAnnouncementBinder.java b/discovery/src/test/java/io/airlift/discovery/client/TestHttpAnnouncementBinder.java index 961f34e8fa4..3db625e032f 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestHttpAnnouncementBinder.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestHttpAnnouncementBinder.java @@ -31,8 +31,7 @@ import static com.google.common.collect.MoreCollectors.onlyElement; import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder; import static io.airlift.discovery.client.ServiceAnnouncement.serviceAnnouncement; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestHttpAnnouncementBinder { @@ -179,11 +178,11 @@ public void testHttpAnnouncementWithCustomProvidedProperties() private void assertAnnouncement(Set actualAnnouncements, ServiceAnnouncement expected) { - assertNotNull(actualAnnouncements); - assertEquals(actualAnnouncements.size(), 1); + assertThat(actualAnnouncements).isNotNull(); + assertThat(actualAnnouncements.size()).isEqualTo(1); ServiceAnnouncement announcement = actualAnnouncements.stream().collect(onlyElement()); - assertEquals(announcement.getType(), expected.getType()); - assertEquals(announcement.getProperties(), expected.getProperties()); + assertThat(announcement.getType()).isEqualTo(expected.getType()); + assertThat(announcement.getProperties()).isEqualTo(expected.getProperties()); } public static class StringPropertyProvider diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestHttpAnnouncementImpl.java b/discovery/src/test/java/io/airlift/discovery/client/TestHttpAnnouncementImpl.java index 56b5017df7c..a62542332a2 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestHttpAnnouncementImpl.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestHttpAnnouncementImpl.java @@ -18,7 +18,7 @@ import org.testng.annotations.Test; import static io.airlift.testing.EquivalenceTester.equivalenceTester; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestHttpAnnouncementImpl { @@ -46,14 +46,14 @@ public TestHttpAnnouncementImpl() @Test public void testAnnouncementId() { - assertEquals(new HttpAnnouncementImpl("type A").announcementId(), "type A"); + assertThat(new HttpAnnouncementImpl("type A").announcementId()).isEqualTo("type A"); } @Test public void testAnnotationType() { - assertEquals(new HttpAnnouncementImpl("apple").annotationType(), HttpAnnouncement.class); - assertEquals(new HttpAnnouncementImpl("apple").annotationType(), appleHttpAnnouncement.annotationType()); + assertThat(new HttpAnnouncementImpl("apple").annotationType()).isEqualTo(HttpAnnouncement.class); + assertThat(new HttpAnnouncementImpl("apple").annotationType()).isEqualTo(appleHttpAnnouncement.annotationType()); } @Test diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestHttpDiscoveryAnnouncementClient.java b/discovery/src/test/java/io/airlift/discovery/client/TestHttpDiscoveryAnnouncementClient.java index 7b45636781e..e5a802bd62b 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestHttpDiscoveryAnnouncementClient.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestHttpDiscoveryAnnouncementClient.java @@ -5,7 +5,7 @@ import java.net.URI; import static io.airlift.discovery.client.HttpDiscoveryAnnouncementClient.createAnnouncementLocation; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestHttpDiscoveryAnnouncementClient { @@ -13,11 +13,11 @@ public class TestHttpDiscoveryAnnouncementClient public void testCreateAnnouncementLocation() { URI expected = URI.create("http://example.com:8080/v1/announcement/abc"); - assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080"), "abc"), expected); - assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080/"), "abc"), expected); + assertThat(createAnnouncementLocation(URI.create("http://example.com:8080"), "abc")).isEqualTo(expected); + assertThat(createAnnouncementLocation(URI.create("http://example.com:8080/"), "abc")).isEqualTo(expected); expected = URI.create("https://example.com:8080/v1/announcement/abc"); - assertEquals(createAnnouncementLocation(URI.create("https://example.com:8080"), "abc"), expected); - assertEquals(createAnnouncementLocation(URI.create("https://example.com:8080/"), "abc"), expected); + assertThat(createAnnouncementLocation(URI.create("https://example.com:8080"), "abc")).isEqualTo(expected); + assertThat(createAnnouncementLocation(URI.create("https://example.com:8080/"), "abc")).isEqualTo(expected); } } diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestHttpDiscoveryLookupClient.java b/discovery/src/test/java/io/airlift/discovery/client/TestHttpDiscoveryLookupClient.java index 2011e9fe27c..2632dca7dde 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestHttpDiscoveryLookupClient.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestHttpDiscoveryLookupClient.java @@ -6,7 +6,7 @@ import java.util.Optional; import static io.airlift.discovery.client.HttpDiscoveryLookupClient.createServiceLocation; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestHttpDiscoveryLookupClient { @@ -14,15 +14,15 @@ public class TestHttpDiscoveryLookupClient public void testCreateServiceLocation() { URI expected = URI.create("http://example.com:8080/v1/service/abc"); - assertEquals(createServiceLocation(URI.create("http://example.com:8080"), "abc", Optional.empty()), expected); - assertEquals(createServiceLocation(URI.create("http://example.com:8080/"), "abc", Optional.empty()), expected); + assertThat(createServiceLocation(URI.create("http://example.com:8080"), "abc", Optional.empty())).isEqualTo(expected); + assertThat(createServiceLocation(URI.create("http://example.com:8080/"), "abc", Optional.empty())).isEqualTo(expected); expected = URI.create("https://example.com:8080/v1/service/abc"); - assertEquals(createServiceLocation(URI.create("https://example.com:8080"), "abc", Optional.empty()), expected); - assertEquals(createServiceLocation(URI.create("https://example.com:8080/"), "abc", Optional.empty()), expected); + assertThat(createServiceLocation(URI.create("https://example.com:8080"), "abc", Optional.empty())).isEqualTo(expected); + assertThat(createServiceLocation(URI.create("https://example.com:8080/"), "abc", Optional.empty())).isEqualTo(expected); expected = URI.create("http://example.com:8080/v1/service/abc/xyz"); - assertEquals(createServiceLocation(URI.create("http://example.com:8080"), "abc", Optional.of("xyz")), expected); - assertEquals(createServiceLocation(URI.create("http://example.com:8080/"), "abc", Optional.of("xyz")), expected); + assertThat(createServiceLocation(URI.create("http://example.com:8080"), "abc", Optional.of("xyz"))).isEqualTo(expected); + assertThat(createServiceLocation(URI.create("http://example.com:8080/"), "abc", Optional.of("xyz"))).isEqualTo(expected); } } diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestHttpServiceSelectorBinder.java b/discovery/src/test/java/io/airlift/discovery/client/TestHttpServiceSelectorBinder.java index cad46eb4e11..3d9b5676fe1 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestHttpServiceSelectorBinder.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestHttpServiceSelectorBinder.java @@ -34,7 +34,7 @@ import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder; import static io.airlift.discovery.client.ServiceAnnouncement.serviceAnnouncement; import static io.airlift.discovery.client.ServiceTypes.serviceType; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestHttpServiceSelectorBinder { @@ -51,7 +51,7 @@ public void testHttpSelectorString() discoveryClient.announce(ImmutableSet.of(serviceAnnouncement("apple").addProperty("http", "fake://server-http").build())); HttpServiceSelector selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("apple"))); - assertEquals(selector.selectHttpService().stream().collect(onlyElement()), URI.create("fake://server-http")); + assertThat(selector.selectHttpService().stream().collect(onlyElement())).isEqualTo(URI.create("fake://server-http")); } @Test @@ -67,10 +67,10 @@ public void testHttpSelectorAnnotation() discoveryClient.announce(ImmutableSet.of(serviceAnnouncement("apple").addProperty("http", "fake://server-http").build())); HttpServiceSelector selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("apple"))); - assertEquals(selector.selectHttpService().stream().collect(onlyElement()), URI.create("fake://server-http")); + assertThat(selector.selectHttpService().stream().collect(onlyElement())).isEqualTo(URI.create("fake://server-http")); ServiceSelectorManager manager = injector.getInstance(ServiceSelectorManager.class); - assertEquals(manager.getServiceSelectors().size(), 1); + assertThat(manager.getServiceSelectors().size()).isEqualTo(1); manager.attemptRefresh(); manager.forceRefresh(); } @@ -88,7 +88,7 @@ public void testHttpsSelector() discoveryClient.announce(ImmutableSet.of(serviceAnnouncement("apple").addProperty("https", "fake://server-https").build())); HttpServiceSelector selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("apple"))); - assertEquals(selector.selectHttpService().stream().collect(onlyElement()), URI.create("fake://server-https")); + assertThat(selector.selectHttpService().stream().collect(onlyElement())).isEqualTo(URI.create("fake://server-https")); } @Test @@ -105,7 +105,7 @@ public void testFavorHttpsOverHttpSelector() serviceAnnouncement("apple").addProperty("https", "fake://server-https").build())); HttpServiceSelector selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("apple"))); - assertEquals(selector.selectHttpService(), ImmutableList.of(URI.create("fake://server-https"), URI.create("fake://server-http"))); + assertThat(selector.selectHttpService()).isEqualTo(ImmutableList.of(URI.create("fake://server-https"), URI.create("fake://server-http"))); } @Test @@ -121,7 +121,7 @@ public void testNoHttpServices() discoveryClient.announce(ImmutableSet.of(serviceAnnouncement("apple").addProperty("foo", "fake://server-https").build())); HttpServiceSelector selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("apple"))); - assertEquals(selector.selectHttpService(), ImmutableList.of()); + assertThat(selector.selectHttpService()).isEqualTo(ImmutableList.of()); } @Test @@ -138,6 +138,6 @@ public void testInvalidUris() discoveryClient.announce(ImmutableSet.of(serviceAnnouncement("apple").addProperty("https", ":::INVALID:::").build())); HttpServiceSelector selector = injector.getInstance(Key.get(HttpServiceSelector.class, serviceType("apple"))); - assertEquals(selector.selectHttpService(), ImmutableList.of()); + assertThat(selector.selectHttpService()).isEqualTo(ImmutableList.of()); } } diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestServiceAnnouncement.java b/discovery/src/test/java/io/airlift/discovery/client/TestServiceAnnouncement.java index a69c7e0f084..95b0d3a6c84 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestServiceAnnouncement.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestServiceAnnouncement.java @@ -27,8 +27,7 @@ import static io.airlift.json.JsonCodec.mapJsonCodec; import static io.airlift.testing.EquivalenceTester.equivalenceTester; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestServiceAnnouncement { @@ -52,15 +51,15 @@ public void testBuilder() private void assertAnnouncement(ServiceAnnouncement announcement, String type, Map properties) { - assertNotNull(announcement.getId()); - assertEquals(announcement.getType(), type); - assertEquals(announcement.getProperties(), properties); + assertThat(announcement.getId()).isNotNull(); + assertThat(announcement.getType()).isEqualTo(type); + assertThat(announcement.getProperties()).isEqualTo(properties); } @Test public void testToString() { - assertNotNull(serviceAnnouncement("foo").build()); + assertThat(serviceAnnouncement("foo").build()).isNotNull(); } @Test @@ -79,7 +78,7 @@ public void testJsonEncode() // set id in expected expected.put("id", serviceAnnouncement.getId().toString()); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } @Test diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestServiceDescriptor.java b/discovery/src/test/java/io/airlift/discovery/client/TestServiceDescriptor.java index 5eb0cf9d6a6..f0120f0ed03 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestServiceDescriptor.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestServiceDescriptor.java @@ -30,8 +30,7 @@ import static io.airlift.json.JsonCodec.jsonCodec; import static io.airlift.testing.EquivalenceTester.equivalenceTester; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestServiceDescriptor { @@ -57,12 +56,12 @@ public void testJsonDecode() @Test public void testToString() { - assertNotNull(new ServiceDescriptor(UUID.fromString("12345678-1234-1234-1234-123456789012"), + assertThat(new ServiceDescriptor(UUID.fromString("12345678-1234-1234-1234-123456789012"), "node", "type", "pool", "location", - ServiceState.RUNNING, ImmutableMap.of("a", "apple", "b", "banana"))); + ServiceState.RUNNING, ImmutableMap.of("a", "apple", "b", "banana"))).isNotNull(); } @Test @@ -143,12 +142,12 @@ public void testBuilderNodeInfo() private static void assertDescriptorEquals(ServiceDescriptor expected, ServiceDescriptor actual) { - assertEquals(actual, expected); - assertEquals(actual.getId(), expected.getId()); - assertEquals(actual.getNodeId(), expected.getNodeId()); - assertEquals(actual.getType(), expected.getType()); - assertEquals(actual.getPool(), expected.getPool()); - assertEquals(actual.getLocation(), expected.getLocation()); - assertEquals(actual.getProperties(), expected.getProperties()); + assertThat(actual).isEqualTo(expected); + assertThat(actual.getId()).isEqualTo(expected.getId()); + assertThat(actual.getNodeId()).isEqualTo(expected.getNodeId()); + assertThat(actual.getType()).isEqualTo(expected.getType()); + assertThat(actual.getPool()).isEqualTo(expected.getPool()); + assertThat(actual.getLocation()).isEqualTo(expected.getLocation()); + assertThat(actual.getProperties()).isEqualTo(expected.getProperties()); } } diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestServiceInventory.java b/discovery/src/test/java/io/airlift/discovery/client/TestServiceInventory.java index b4740796d83..69c99236430 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestServiceInventory.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestServiceInventory.java @@ -36,7 +36,7 @@ import java.io.IOException; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestServiceInventory { @@ -49,9 +49,9 @@ public void testNullServiceInventory() JsonCodec.jsonCodec(ServiceDescriptorsRepresentation.class), httpClient); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors()), 0); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors())).isEqualTo(0); serviceInventory.updateServiceInventory(); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors()), 0); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors())).isEqualTo(0); } } @@ -68,13 +68,13 @@ public void testFileServiceInventory() JsonCodec.jsonCodec(ServiceDescriptorsRepresentation.class), httpClient); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors()), 2); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors("discovery")), 2); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors("discovery", "general")), 2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors())).isEqualTo(2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors("discovery"))).isEqualTo(2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors("discovery", "general"))).isEqualTo(2); serviceInventory.updateServiceInventory(); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors()), 2); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors("discovery")), 2); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors("discovery", "general")), 2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors())).isEqualTo(2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors("discovery"))).isEqualTo(2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors("discovery", "general"))).isEqualTo(2); } } @@ -115,13 +115,13 @@ public void testHttpServiceInventory() JsonCodec.jsonCodec(ServiceDescriptorsRepresentation.class), httpClient); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors()), 2); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors("discovery")), 2); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors("discovery", "general")), 2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors())).isEqualTo(2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors("discovery"))).isEqualTo(2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors("discovery", "general"))).isEqualTo(2); serviceInventory.updateServiceInventory(); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors()), 2); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors("discovery")), 2); - assertEquals(Iterables.size(serviceInventory.getServiceDescriptors("discovery", "general")), 2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors())).isEqualTo(2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors("discovery"))).isEqualTo(2); + assertThat(Iterables.size(serviceInventory.getServiceDescriptors("discovery", "general"))).isEqualTo(2); } finally { if (server != null) { diff --git a/discovery/src/test/java/io/airlift/discovery/client/TestServiceTypes.java b/discovery/src/test/java/io/airlift/discovery/client/TestServiceTypes.java index 1f603af50fb..eabf1218ba5 100644 --- a/discovery/src/test/java/io/airlift/discovery/client/TestServiceTypes.java +++ b/discovery/src/test/java/io/airlift/discovery/client/TestServiceTypes.java @@ -18,7 +18,7 @@ import org.testng.annotations.Test; import static io.airlift.testing.EquivalenceTester.equivalenceTester; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestServiceTypes { @@ -46,14 +46,14 @@ public TestServiceTypes() @Test public void testValue() { - assertEquals(ServiceTypes.serviceType("type").value(), "type"); + assertThat(ServiceTypes.serviceType("type").value()).isEqualTo("type"); } @Test public void testAnnotationType() { - assertEquals(ServiceTypes.serviceType("apple").annotationType(), ServiceType.class); - assertEquals(ServiceTypes.serviceType("apple").annotationType(), appleServiceType.annotationType()); + assertThat(ServiceTypes.serviceType("apple").annotationType()).isEqualTo(ServiceType.class); + assertThat(ServiceTypes.serviceType("apple").annotationType()).isEqualTo(appleServiceType.annotationType()); } @Test diff --git a/event-http/pom.xml b/event-http/pom.xml index d14b34a070d..355c78c7c1d 100644 --- a/event-http/pom.xml +++ b/event-http/pom.xml @@ -82,6 +82,12 @@ test + + org.assertj + assertj-core + test + + org.eclipse.jetty jetty-server diff --git a/event-http/src/test/java/io/airlift/event/client/http/TestHttpEventClient.java b/event-http/src/test/java/io/airlift/event/client/http/TestHttpEventClient.java index ad185543865..b6aa095a5cf 100644 --- a/event-http/src/test/java/io/airlift/event/client/http/TestHttpEventClient.java +++ b/event-http/src/test/java/io/airlift/event/client/http/TestHttpEventClient.java @@ -63,8 +63,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public class TestHttpEventClient @@ -98,8 +97,8 @@ public void testCallSucceedsWhenServiceUnavailable() client.post(new FixedDummyEventClass("host", Instant.now(), UUID.randomUUID(), 1, "foo")); - assertNull(servlet.lastPath); - assertNull(servlet.lastBody); + assertThat(servlet.lastPath).isNull(); + assertThat(servlet.lastBody).isNull(); } @Test @@ -110,8 +109,8 @@ public void testReceivesEvent() client.post(TestingUtils.getEvents()).get(); - assertEquals(servlet.lastPath, "/v2/event"); - assertEquals(servlet.lastBody, getNormalizedJson("events.json")); + assertThat(servlet.lastPath).isEqualTo("/v2/event"); + assertThat(servlet.lastBody).isEqualTo(getNormalizedJson("events.json")); } @Test @@ -128,8 +127,8 @@ public void loadTest() for (Future future : futures) { future.get(); } - assertEquals(servlet.lastPath, "/v2/event"); - assertEquals(servlet.lastBody, getNormalizedJson("events.json")); + assertThat(servlet.lastPath).isEqualTo("/v2/event"); + assertThat(servlet.lastBody).isEqualTo(getNormalizedJson("events.json")); } @BeforeMethod diff --git a/event/pom.xml b/event/pom.xml index 7e6c1a9ef36..096cc5bf4fc 100644 --- a/event/pom.xml +++ b/event/pom.xml @@ -48,6 +48,12 @@ test + + org.assertj + assertj-core + test + + org.testng testng diff --git a/event/src/test/java/io/airlift/event/client/AbstractTestInMemoryEventClient.java b/event/src/test/java/io/airlift/event/client/AbstractTestInMemoryEventClient.java index 97eaefc1204..e4134680dcf 100644 --- a/event/src/test/java/io/airlift/event/client/AbstractTestInMemoryEventClient.java +++ b/event/src/test/java/io/airlift/event/client/AbstractTestInMemoryEventClient.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public abstract class AbstractTestInMemoryEventClient @@ -35,7 +35,7 @@ public void testPostSingleEvent() { eventClient.post(event1); - assertEquals(inMemoryEventClient.getEvents(), ImmutableList.of(event1)); + assertThat(inMemoryEventClient.getEvents()).isEqualTo(ImmutableList.of(event1)); } @Test @@ -45,8 +45,7 @@ public void testPostMultiple() eventClient.post(event2); eventClient.post(event3); - assertEquals(inMemoryEventClient.getEvents(), - ImmutableList.of(event1, event2, event3)); + assertThat(inMemoryEventClient.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); } @Test @@ -54,8 +53,7 @@ public void testPostVarArgs() { eventClient.post(event1, event2, event3); - assertEquals(inMemoryEventClient.getEvents(), - ImmutableList.of(event1, event2, event3)); + assertThat(inMemoryEventClient.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); } @Test @@ -63,8 +61,7 @@ public void testPostIterable() { eventClient.post(ImmutableList.of(event1, event2, event3)); - assertEquals(inMemoryEventClient.getEvents(), - ImmutableList.of(event1, event2, event3)); + assertThat(inMemoryEventClient.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); } @Test @@ -76,7 +73,6 @@ public void testPostEventPoster() objectEventPoster.post(event3); }); - assertEquals(inMemoryEventClient.getEvents(), - ImmutableList.of(event1, event2, event3)); + assertThat(inMemoryEventClient.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); } } diff --git a/event/src/test/java/io/airlift/event/client/AbstractTestMultiEventClient.java b/event/src/test/java/io/airlift/event/client/AbstractTestMultiEventClient.java index 640c953931d..da0b5ab0cb3 100644 --- a/event/src/test/java/io/airlift/event/client/AbstractTestMultiEventClient.java +++ b/event/src/test/java/io/airlift/event/client/AbstractTestMultiEventClient.java @@ -18,7 +18,7 @@ import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public abstract class AbstractTestMultiEventClient @@ -36,8 +36,8 @@ public void testPostSingleEvent() { eventClient.post(event1); - assertEquals(memoryEventClient1.getEvents(), ImmutableList.of(event1)); - assertEquals(memoryEventClient2.getEvents(), ImmutableList.of(event1)); + assertThat(memoryEventClient1.getEvents()).isEqualTo(ImmutableList.of(event1)); + assertThat(memoryEventClient2.getEvents()).isEqualTo(ImmutableList.of(event1)); } @Test @@ -47,10 +47,8 @@ public void testPostMultiple() eventClient.post(event2); eventClient.post(event3); - assertEquals(memoryEventClient1.getEvents(), - ImmutableList.of(event1, event2, event3)); - assertEquals(memoryEventClient2.getEvents(), - ImmutableList.of(event1, event2, event3)); + assertThat(memoryEventClient1.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); + assertThat(memoryEventClient2.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); } @Test @@ -58,10 +56,8 @@ public void testPostVarArgs() { eventClient.post(event1, event2, event3); - assertEquals(memoryEventClient1.getEvents(), - ImmutableList.of(event1, event2, event3)); - assertEquals(memoryEventClient2.getEvents(), - ImmutableList.of(event1, event2, event3)); + assertThat(memoryEventClient1.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); + assertThat(memoryEventClient2.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); } @Test @@ -69,10 +65,8 @@ public void testPostIterable() { eventClient.post(ImmutableList.of(event1, event2, event3)); - assertEquals(memoryEventClient1.getEvents(), - ImmutableList.of(event1, event2, event3)); - assertEquals(memoryEventClient2.getEvents(), - ImmutableList.of(event1, event2, event3)); + assertThat(memoryEventClient1.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); + assertThat(memoryEventClient2.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); } @Test @@ -84,9 +78,7 @@ public void testPostEventPoster() objectEventPoster.post(event3); }); - assertEquals(memoryEventClient1.getEvents(), - ImmutableList.of(event1, event2, event3)); - assertEquals(memoryEventClient2.getEvents(), - ImmutableList.of(event1, event2, event3)); + assertThat(memoryEventClient1.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); + assertThat(memoryEventClient2.getEvents()).isEqualTo(ImmutableList.of(event1, event2, event3)); } } diff --git a/event/src/test/java/io/airlift/event/client/TestEventSubmissionFailedException.java b/event/src/test/java/io/airlift/event/client/TestEventSubmissionFailedException.java index b50e712838e..024f2d8f3d3 100644 --- a/event/src/test/java/io/airlift/event/client/TestEventSubmissionFailedException.java +++ b/event/src/test/java/io/airlift/event/client/TestEventSubmissionFailedException.java @@ -24,9 +24,8 @@ import java.util.Collections; import java.util.Map; -import static org.testng.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; public class TestEventSubmissionFailedException { @@ -41,7 +40,7 @@ public void testEmptyCause() { EventSubmissionFailedException e = new EventSubmissionFailedException("service", "type", Collections.emptyMap()); - assertNull(e.getCause()); + assertThat(e.getCause()).isNull(); } @Test @@ -58,8 +57,8 @@ public void testMessageMentionsServiceAndType() { EventSubmissionFailedException e = new EventSubmissionFailedException("serviceX", "typeY", Collections.emptyMap()); - assertTrue(e.getMessage().contains("serviceX")); - assertTrue(e.getMessage().contains("typeY")); + assertThat(e.getMessage().contains("serviceX")).isTrue(); + assertThat(e.getMessage().contains("typeY")).isTrue(); } @Test diff --git a/event/src/test/java/io/airlift/event/client/TestEventValidation.java b/event/src/test/java/io/airlift/event/client/TestEventValidation.java index 046a26e15ba..07184996479 100644 --- a/event/src/test/java/io/airlift/event/client/TestEventValidation.java +++ b/event/src/test/java/io/airlift/event/client/TestEventValidation.java @@ -24,7 +24,7 @@ import static io.airlift.event.client.EventTypeMetadata.getEventTypeMetadataNested; import static io.airlift.event.client.EventTypeMetadata.getValidEventTypeMetadata; import static io.airlift.testing.Assertions.assertContains; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestEventValidation { @@ -90,15 +90,15 @@ public Nested2 getNested2() } } - assertEquals(getEventTypeMetadataNested(TestEvent.Nested.class).getTypeName(), "NestedCustom"); - assertEquals(getEventTypeMetadataNested(TestEvent.Nested2.class).getTypeName(), TestEvent.Nested2.class.getSimpleName()); + assertThat(getEventTypeMetadataNested(TestEvent.Nested.class).getTypeName()).isEqualTo("NestedCustom"); + assertThat(getEventTypeMetadataNested(TestEvent.Nested2.class).getTypeName()).isEqualTo(TestEvent.Nested2.class.getSimpleName()); } private static void assertInvalidEvent(Class eventClass, String errorPart) { EventTypeMetadata metadata = getEventTypeMetadata(eventClass); List errors = metadata.getErrors(); - assertEquals(errors.size(), 1, "expected exactly one error:\n" + Joiner.on('\n').join(errors)); + assertThat(errors.size()).as("expected exactly one error:\n" + Joiner.on('\n').join(errors)).isEqualTo(1); assertContains(errors.get(0), errorPart); } } diff --git a/event/src/test/java/io/airlift/event/client/TestJsonEventSerializer.java b/event/src/test/java/io/airlift/event/client/TestJsonEventSerializer.java index d1ac9954fdb..f5d66cd2a8d 100644 --- a/event/src/test/java/io/airlift/event/client/TestJsonEventSerializer.java +++ b/event/src/test/java/io/airlift/event/client/TestJsonEventSerializer.java @@ -23,7 +23,7 @@ import java.io.ByteArrayOutputStream; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestJsonEventSerializer { @@ -40,6 +40,6 @@ public void testEventSerializer() eventSerializer.serialize(event, jsonGenerator); String json = out.toString(UTF_8.name()); - assertEquals(json, TestingUtils.getNormalizedJson("event.json")); + assertThat(json).isEqualTo(TestingUtils.getNormalizedJson("event.json")); } } diff --git a/event/src/test/java/io/airlift/event/client/TestJsonEventWriter.java b/event/src/test/java/io/airlift/event/client/TestJsonEventWriter.java index fabebeb12e1..a69ac8e7ce2 100644 --- a/event/src/test/java/io/airlift/event/client/TestJsonEventWriter.java +++ b/event/src/test/java/io/airlift/event/client/TestJsonEventWriter.java @@ -29,7 +29,7 @@ import static io.airlift.event.client.ChainedCircularEventClass.ChainedPart; import static io.airlift.event.client.EventTypeMetadata.getValidEventTypeMetaDataSet; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestJsonEventWriter { @@ -105,7 +105,7 @@ private void assertEventJson(EventClient.EventGenerator events, String resour eventWriter.writeEvents(events, out); String json = out.toString(UTF_8.name()); - assertEquals(json, TestingUtils.getNormalizedJson(resource)); + assertThat(json).isEqualTo(TestingUtils.getNormalizedJson(resource)); } private static EventClient.EventGenerator createEventGenerator(final Iterable events) diff --git a/event/src/test/java/io/airlift/event/client/TestTypeParametersUtils.java b/event/src/test/java/io/airlift/event/client/TestTypeParametersUtils.java index 444d3c18f4b..835dd2d651f 100644 --- a/event/src/test/java/io/airlift/event/client/TestTypeParametersUtils.java +++ b/event/src/test/java/io/airlift/event/client/TestTypeParametersUtils.java @@ -27,9 +27,7 @@ import java.util.Set; import static io.airlift.event.client.TypeParameterUtils.getTypeParameters; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @SuppressWarnings({"PublicField", "unused"}) public class TestTypeParametersUtils @@ -54,8 +52,8 @@ public class TestTypeParametersUtils public void testMap() throws Exception { - assertNull(getParameters("mapNotGeneric")); - assertEquals(getParameters("mapSimple"), new Type[] {Key.class, Value.class}); + assertThat(getParameters("mapNotGeneric")).isNull(); + assertThat(getParameters("mapSimple")).isEqualTo(new Type[]{Key.class, Value.class}); assertTwoWildcardTypes(getParameters("mapWildcard")); assertTwoWildcardTypes(getParameters("mapExtendsWildcard")); assertTwoWildcardTypes(getParameters("mapSuperWildcard")); @@ -66,7 +64,7 @@ public void testMyMap() throws Exception { assertTwoTypeVariables(getParameters("myMapNotGeneric")); - assertEquals(getParameters("myMapSimple"), new Type[] {Key.class, Value.class}); + assertThat(getParameters("myMapSimple")).isEqualTo(new Type[]{Key.class, Value.class}); assertTwoWildcardTypes(getParameters("myMapWildcard")); assertTwoWildcardTypes(getParameters("myMapExtendsWildcard")); assertTwoWildcardTypes(getParameters("myMapSuperWildcard")); @@ -76,12 +74,12 @@ public void testMyMap() public void testFixedMap() throws Exception { - assertEquals(getParameters("fixedMap"), new Type[] {Key.class, Value.class}); + assertThat(getParameters("fixedMap")).isEqualTo(new Type[]{Key.class, Value.class}); } private static void assertTwoWildcardTypes(Type[] types) { - assertEquals(types.length, 2); + assertThat(types.length).isEqualTo(2); for (Type type : types) { assertInstanceOf(type, WildcardType.class); } @@ -89,7 +87,7 @@ private static void assertTwoWildcardTypes(Type[] types) private static void assertTwoTypeVariables(Type[] types) { - assertEquals(types.length, 2); + assertThat(types.length).isEqualTo(2); for (Type type : types) { assertInstanceOf(type, TypeVariable.class); } @@ -97,7 +95,7 @@ private static void assertTwoTypeVariables(Type[] types) private static void assertInstanceOf(Type type, Class clazz) { - assertTrue(clazz.isInstance(type), String.format("[%s] is not instance of %s", type, clazz.getSimpleName())); + assertThat(clazz.isInstance(type)).as(String.format("[%s] is not instance of %s", type, clazz.getSimpleName())).isTrue(); } private Type[] getParameters(String fieldName) diff --git a/http-client/src/test/java/io/airlift/http/client/AbstractHttpClientTest.java b/http-client/src/test/java/io/airlift/http/client/AbstractHttpClientTest.java index 86f24bdd6bc..449441864d3 100755 --- a/http-client/src/test/java/io/airlift/http/client/AbstractHttpClientTest.java +++ b/http-client/src/test/java/io/airlift/http/client/AbstractHttpClientTest.java @@ -72,12 +72,7 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.fail; @Test(singleThreaded = true) public abstract class AbstractHttpClientTest @@ -159,7 +154,7 @@ public void test100kGets() for (int i = 0; i < 100_000; i++) { try { int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); + assertThat(statusCode).isEqualTo(200); } catch (Exception e) { throw new Exception("Error on request " + i, e); @@ -237,7 +232,7 @@ public void testConnectionRefusedWithDefaultingResponseExceptionHandler() .build(); Object expected = new Object(); - assertEquals(executeRequest(config, request, new DefaultOnExceptionResponseHandler(expected)), expected); + assertThat(executeRequest(config, request, new DefaultOnExceptionResponseHandler(expected))).isEqualTo(expected); } @Test(expectedExceptions = {UnknownHostException.class, UnresolvedAddressException.class}, timeOut = 10000) @@ -283,12 +278,12 @@ public void testDeleteMethod() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); - assertEquals(servlet.getRequestMethod(), "DELETE"); - assertEquals(servlet.getRequestUri(), uri); - assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar")); - assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second")); - assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value")); + assertThat(statusCode).isEqualTo(200); + assertThat(servlet.getRequestMethod()).isEqualTo("DELETE"); + assertThat(servlet.getRequestUri()).isEqualTo(uri); + assertThat(servlet.getRequestHeaders("foo")).isEqualTo(ImmutableList.of("bar")); + assertThat(servlet.getRequestHeaders("dupe")).isEqualTo(ImmutableList.of("first", "second")); + assertThat(servlet.getRequestHeaders("x-custom-filter")).isEqualTo(ImmutableList.of("custom value")); assertThat(statusCounts.count(200)).isEqualTo(1); } @@ -304,8 +299,8 @@ public void testErrorResponseBody() .build(); StringResponse response = executeRequest(request, createStringResponseHandler()); - assertEquals(response.getStatusCode(), 500); - assertEquals(response.getBody(), "body text"); + assertThat(response.getStatusCode()).isEqualTo(500); + assertThat(response.getBody()).isEqualTo("body text"); } @Test @@ -321,18 +316,18 @@ public void testGetMethod() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); - assertEquals(servlet.getRequestMethod(), "GET"); + assertThat(statusCode).isEqualTo(200); + assertThat(servlet.getRequestMethod()).isEqualTo("GET"); if (servlet.getRequestUri().toString().endsWith("=")) { // todo jetty client rewrites the uri string for some reason - assertEquals(servlet.getRequestUri(), new URI(uri + "=")); + assertThat(servlet.getRequestUri()).isEqualTo(new URI(uri + "=")); } else { - assertEquals(servlet.getRequestUri(), uri); + assertThat(servlet.getRequestUri()).isEqualTo(uri); } - assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar")); - assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second")); - assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value")); + assertThat(servlet.getRequestHeaders("foo")).isEqualTo(ImmutableList.of("bar")); + assertThat(servlet.getRequestHeaders("dupe")).isEqualTo(ImmutableList.of("first", "second")); + assertThat(servlet.getRequestHeaders("x-custom-filter")).isEqualTo(ImmutableList.of("custom value")); assertThat(statusCounts.count(200)).isEqualTo(1); } @@ -347,11 +342,11 @@ public void testResponseHeadersCaseInsensitive() Response response = executeRequest(request, new PassThroughResponseHandler()); - assertNotNull(response.getHeader("date")); - assertNotNull(response.getHeader("DATE")); + assertThat(response.getHeader("date")).isNotNull(); + assertThat(response.getHeader("DATE")).isNotNull(); - assertEquals(response.getHeaders("date").size(), 1); - assertEquals(response.getHeaders("DATE").size(), 1); + assertThat(response.getHeaders("date").size()).isEqualTo(1); + assertThat(response.getHeaders("DATE").size()).isEqualTo(1); } @Test @@ -364,9 +359,9 @@ public void testQuotedSpace() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); - assertEquals(servlet.getRequestMethod(), "GET"); - assertEquals(servlet.getRequestUri(), uri); + assertThat(statusCode).isEqualTo(200); + assertThat(servlet.getRequestMethod()).isEqualTo("GET"); + assertThat(servlet.getRequestUri()).isEqualTo(uri); } @Test @@ -384,16 +379,16 @@ public void testKeepAlive() Thread.sleep(1000); StatusResponse response3 = executeRequest(request, createStatusResponseHandler()); - assertNotNull(response1.getHeader("remotePort")); - assertNotNull(response2.getHeader("remotePort")); - assertNotNull(response3.getHeader("remotePort")); + assertThat(response1.getHeader("remotePort")).isNotNull(); + assertThat(response2.getHeader("remotePort")).isNotNull(); + assertThat(response3.getHeader("remotePort")).isNotNull(); int port1 = Integer.parseInt(response1.getHeader("remotePort")); int port2 = Integer.parseInt(response2.getHeader("remotePort")); int port3 = Integer.parseInt(response3.getHeader("remotePort")); - assertEquals(port2, port1); - assertEquals(port3, port1); + assertThat(port2).isEqualTo(port1); + assertThat(port3).isEqualTo(port1); assertBetweenInclusive(port1, 1024, 65535); } @@ -410,12 +405,12 @@ public void testPostMethod() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); - assertEquals(servlet.getRequestMethod(), "POST"); - assertEquals(servlet.getRequestUri(), uri); - assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar")); - assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second")); - assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value")); + assertThat(statusCode).isEqualTo(200); + assertThat(servlet.getRequestMethod()).isEqualTo("POST"); + assertThat(servlet.getRequestUri()).isEqualTo(uri); + assertThat(servlet.getRequestHeaders("foo")).isEqualTo(ImmutableList.of("bar")); + assertThat(servlet.getRequestHeaders("dupe")).isEqualTo(ImmutableList.of("first", "second")); + assertThat(servlet.getRequestHeaders("x-custom-filter")).isEqualTo(ImmutableList.of("custom value")); assertThat(statusCounts.count(200)).isEqualTo(1); } @@ -432,12 +427,12 @@ public void testPutMethod() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); - assertEquals(servlet.getRequestMethod(), "PUT"); - assertEquals(servlet.getRequestUri(), uri); - assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar")); - assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second")); - assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value")); + assertThat(statusCode).isEqualTo(200); + assertThat(servlet.getRequestMethod()).isEqualTo("PUT"); + assertThat(servlet.getRequestUri()).isEqualTo(uri); + assertThat(servlet.getRequestHeaders("foo")).isEqualTo(ImmutableList.of("bar")); + assertThat(servlet.getRequestHeaders("dupe")).isEqualTo(ImmutableList.of("first", "second")); + assertThat(servlet.getRequestHeaders("x-custom-filter")).isEqualTo(ImmutableList.of("custom value")); assertThat(statusCounts.count(200)).isEqualTo(1); } @@ -456,13 +451,13 @@ public void testPutMethodWithStaticBodyGenerator() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); - assertEquals(servlet.getRequestMethod(), "PUT"); - assertEquals(servlet.getRequestUri(), uri); - assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar")); - assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second")); - assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value")); - assertEquals(servlet.getRequestBytes(), body); + assertThat(statusCode).isEqualTo(200); + assertThat(servlet.getRequestMethod()).isEqualTo("PUT"); + assertThat(servlet.getRequestUri()).isEqualTo(uri); + assertThat(servlet.getRequestHeaders("foo")).isEqualTo(ImmutableList.of("bar")); + assertThat(servlet.getRequestHeaders("dupe")).isEqualTo(ImmutableList.of("first", "second")); + assertThat(servlet.getRequestHeaders("x-custom-filter")).isEqualTo(ImmutableList.of("custom value")); + assertThat(servlet.getRequestBytes()).isEqualTo(body); assertThat(statusCounts.count(200)).isEqualTo(1); } @@ -483,13 +478,13 @@ public void testPutMethodWithDynamicBodyGenerator() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); - assertEquals(servlet.getRequestMethod(), "PUT"); - assertEquals(servlet.getRequestUri(), uri); - assertEquals(servlet.getRequestHeaders("foo"), ImmutableList.of("bar")); - assertEquals(servlet.getRequestHeaders("dupe"), ImmutableList.of("first", "second")); - assertEquals(servlet.getRequestHeaders("x-custom-filter"), ImmutableList.of("custom value")); - assertEquals(servlet.getRequestBytes(), new byte[] {1, 2, 5}); + assertThat(statusCode).isEqualTo(200); + assertThat(servlet.getRequestMethod()).isEqualTo("PUT"); + assertThat(servlet.getRequestUri()).isEqualTo(uri); + assertThat(servlet.getRequestHeaders("foo")).isEqualTo(ImmutableList.of("bar")); + assertThat(servlet.getRequestHeaders("dupe")).isEqualTo(ImmutableList.of("first", "second")); + assertThat(servlet.getRequestHeaders("x-custom-filter")).isEqualTo(ImmutableList.of("custom value")); + assertThat(servlet.getRequestBytes()).isEqualTo(new byte[]{1, 2, 5}); assertThat(statusCounts.count(200)).isEqualTo(1); } @@ -509,14 +504,14 @@ public void testPutMethodWithFileBodyGenerator() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 200); - assertEquals(servlet.getRequestMethod(), "PUT"); - assertEquals(servlet.getRequestUri(), uri); - assertEquals(servlet.getRequestHeaders(CONTENT_TYPE), ImmutableList.of("x-test")); - assertEquals(servlet.getRequestHeaders(CONTENT_LENGTH), ImmutableList.of(String.valueOf(contents.length))); - assertEquals(servlet.getRequestBytes(), contents); - - assertTrue(testFile.delete()); + assertThat(statusCode).isEqualTo(200); + assertThat(servlet.getRequestMethod()).isEqualTo("PUT"); + assertThat(servlet.getRequestUri()).isEqualTo(uri); + assertThat(servlet.getRequestHeaders(CONTENT_TYPE)).isEqualTo(ImmutableList.of("x-test")); + assertThat(servlet.getRequestHeaders(CONTENT_LENGTH)).isEqualTo(ImmutableList.of(String.valueOf(contents.length))); + assertThat(servlet.getRequestBytes()).isEqualTo(contents); + + assertThat(testFile.delete()).isTrue(); } @Test(expectedExceptions = {IOException.class, TimeoutException.class}) @@ -545,8 +540,8 @@ public void testResponseBody() .build(); StringResponse response = executeRequest(request, createStringResponseHandler()); - assertEquals(response.getStatusCode(), 200); - assertEquals(response.getBody(), "body text"); + assertThat(response.getStatusCode()).isEqualTo(200); + assertThat(response.getBody()).isEqualTo("body text"); } @Test @@ -558,7 +553,7 @@ public void testResponseBodyEmpty() .build(); String body = executeRequest(request, createStringResponseHandler()).getBody(); - assertEquals(body, ""); + assertThat(body).isEqualTo(""); } @Test @@ -575,8 +570,8 @@ public void testResponseHeader() StatusResponse response = executeRequest(request, createStatusResponseHandler()); - assertEquals(response.getHeaders("foo"), ImmutableList.of("bar")); - assertEquals(response.getHeaders("dupe"), ImmutableList.of("first", "second")); + assertThat(response.getHeaders("foo")).isEqualTo(ImmutableList.of("bar")); + assertThat(response.getHeaders("dupe")).isEqualTo(ImmutableList.of("first", "second")); } @Test @@ -589,7 +584,7 @@ public void testResponseStatusCode() .build(); int statusCode = executeRequest(request, createStatusResponseHandler()).getStatusCode(); - assertEquals(statusCode, 543); + assertThat(statusCode).isEqualTo(543); } @Test @@ -609,7 +604,7 @@ public void testRequestHeaders() .build(); StatusResponse response = executeRequest(request, createStatusResponseHandler()); - assertEquals(response.getStatusCode(), 200); + assertThat(response.getStatusCode()).isEqualTo(200); assertThat(servlet.getRequestHeaders("X-Test")).containsExactly("xtest1", "xtest2"); assertThat(servlet.getRequestHeaders(USER_AGENT)).containsExactly("testagent"); assertThat(servlet.getRequestHeaders(AUTHORIZATION)).containsExactly(basic, bearer); @@ -632,8 +627,8 @@ public void testRedirectRequestHeaders() .build(); StatusResponse response = executeRequest(request, createStatusResponseHandler()); - assertEquals(response.getStatusCode(), 200); - assertEquals(servlet.getRequestUri(), URI.create(baseURI.toASCIIString() + "/redirect")); + assertThat(response.getStatusCode()).isEqualTo(200); + assertThat(servlet.getRequestUri()).isEqualTo(URI.create(baseURI.toASCIIString() + "/redirect")); assertThat(servlet.getRequestHeaders("X-Test")).containsExactly("xtest1", "xtest2"); assertThat(servlet.getRequestHeaders(USER_AGENT)).containsExactly("testagent"); assertThat(servlet.getRequestHeaders(AUTHORIZATION)).isEmpty(); @@ -643,8 +638,8 @@ public void testRedirectRequestHeaders() .build(); response = executeRequest(request, createStatusResponseHandler()); - assertEquals(response.getStatusCode(), 200); - assertEquals(servlet.getRequestUri(), URI.create(baseURI.toASCIIString() + "/redirect")); + assertThat(response.getStatusCode()).isEqualTo(200); + assertThat(servlet.getRequestUri()).isEqualTo(URI.create(baseURI.toASCIIString() + "/redirect")); assertThat(servlet.getRequestHeaders("X-Test")).containsExactly("xtest1", "xtest2"); assertThat(servlet.getRequestHeaders(USER_AGENT)).containsExactly("testagent"); assertThat(servlet.getRequestHeaders(AUTHORIZATION)).containsExactly(basic, bearer); @@ -659,18 +654,18 @@ public void testFollowRedirects() .build(); StatusResponse response = executeRequest(request, createStatusResponseHandler()); - assertEquals(response.getStatusCode(), 200); - assertNull(response.getHeader(LOCATION)); - assertEquals(servlet.getRequestUri(), URI.create(baseURI.toASCIIString() + "/redirect")); + assertThat(response.getStatusCode()).isEqualTo(200); + assertThat(response.getHeader(LOCATION)).isNull(); + assertThat(servlet.getRequestUri()).isEqualTo(URI.create(baseURI.toASCIIString() + "/redirect")); request = Request.Builder.fromRequest(request) .setFollowRedirects(false) .build(); response = executeRequest(request, createStatusResponseHandler()); - assertEquals(response.getStatusCode(), 302); - assertEquals(response.getHeader(LOCATION), "/redirect"); - assertEquals(servlet.getRequestUri(), request.getUri()); + assertThat(response.getStatusCode()).isEqualTo(302); + assertThat(response.getHeader(LOCATION)).isEqualTo("/redirect"); + assertThat(servlet.getRequestUri()).isEqualTo(request.getUri()); } @Test(expectedExceptions = UnexpectedResponseException.class) @@ -694,8 +689,8 @@ public void testCompressionIsDisabled() .build(); String body = executeRequest(request, createStringResponseHandler()).getBody(); - assertEquals(body, ""); - assertFalse(servlet.getRequestHeaders().containsKey(HeaderName.of(ACCEPT_ENCODING))); + assertThat(body).isEqualTo(""); + assertThat(servlet.getRequestHeaders().containsKey(HeaderName.of(ACCEPT_ENCODING))).isFalse(); String json = "{\"fuite\":\"apple\",\"hello\":\"world\"}"; assertGreaterThanOrEqual(json.length(), GzipHandler.DEFAULT_MIN_GZIP_SIZE); @@ -704,8 +699,8 @@ public void testCompressionIsDisabled() servlet.addResponseHeader(CONTENT_TYPE, "application/json"); StringResponse response = executeRequest(request, createStringResponseHandler()); - assertEquals(response.getHeader(CONTENT_TYPE), "application/json"); - assertEquals(response.getBody(), json); + assertThat(response.getHeader(CONTENT_TYPE)).isEqualTo("application/json"); + assertThat(response.getBody()).isEqualTo(json); } private ExecutorService executor; diff --git a/http-client/src/test/java/io/airlift/http/client/TestBasicAuthRequestFilter.java b/http-client/src/test/java/io/airlift/http/client/TestBasicAuthRequestFilter.java index 949457a69fb..d88ec1c2369 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestBasicAuthRequestFilter.java +++ b/http-client/src/test/java/io/airlift/http/client/TestBasicAuthRequestFilter.java @@ -20,8 +20,7 @@ import static com.google.common.net.HttpHeaders.AUTHORIZATION; import static io.airlift.http.client.Request.Builder.prepareGet; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestBasicAuthRequestFilter { @@ -33,10 +32,10 @@ public void testBasicAuthentication() HttpRequestFilter filter = new BasicAuthRequestFilter(predicate, "Aladdin", "open sesame"); Request publicResourceRequest = createTestRequest("/public"); - assertNull(filter.filterRequest(publicResourceRequest).getHeader(AUTHORIZATION)); + assertThat(filter.filterRequest(publicResourceRequest).getHeader(AUTHORIZATION)).isNull(); Request privateResourceRequest = createTestRequest("/private"); - assertEquals(filter.filterRequest(privateResourceRequest).getHeader(AUTHORIZATION), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); + assertThat(filter.filterRequest(privateResourceRequest).getHeader(AUTHORIZATION)).isEqualTo("Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); } private static Request createTestRequest(String path) diff --git a/http-client/src/test/java/io/airlift/http/client/TestCacheControl.java b/http-client/src/test/java/io/airlift/http/client/TestCacheControl.java index 81d1b7fcb92..fcb9429b6da 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestCacheControl.java +++ b/http-client/src/test/java/io/airlift/http/client/TestCacheControl.java @@ -5,9 +5,7 @@ import java.util.List; import java.util.Map; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; // This code was forked from Apache CXF CacheControlHeaderProviderTest public class TestCacheControl @@ -16,30 +14,30 @@ public class TestCacheControl public void testFromSimpleString() { CacheControl c = CacheControl.valueOf("public,must-revalidate"); - assertFalse(c.isPrivate()); - assertFalse(c.isNoStore()); - assertTrue(c.isMustRevalidate()); - assertFalse(c.isProxyRevalidate()); - assertFalse(c.isNoCache()); - assertFalse(c.isNoTransform()); - assertTrue(c.getNoCacheFields().size() == 0); - assertTrue(c.getPrivateFields().size() == 0); + assertThat(c.isPrivate()).isFalse(); + assertThat(c.isNoStore()).isFalse(); + assertThat(c.isMustRevalidate()).isTrue(); + assertThat(c.isProxyRevalidate()).isFalse(); + assertThat(c.isNoCache()).isFalse(); + assertThat(c.isNoTransform()).isFalse(); + assertThat(c.getNoCacheFields().size() == 0).isTrue(); + assertThat(c.getPrivateFields().size() == 0).isTrue(); } @Test public void testFromComplexString() { CacheControl c = CacheControl.valueOf("private=\"foo\",no-cache=\"bar\",no-store,no-transform,must-revalidate,proxy-revalidate,max-age=2,s-maxage=3"); - assertTrue(c.isPrivate()); - assertTrue(c.isNoStore()); - assertTrue(c.isMustRevalidate()); - assertTrue(c.isProxyRevalidate()); - assertTrue(c.isNoCache()); - assertTrue(c.isNoTransform()); - assertTrue(c.getNoCacheFields().size() == 1); - assertTrue(c.getPrivateFields().size() == 1); - assertEquals(c.getPrivateFields().get(0), "foo"); - assertEquals(c.getNoCacheFields().get(0), "bar"); + assertThat(c.isPrivate()).isTrue(); + assertThat(c.isNoStore()).isTrue(); + assertThat(c.isMustRevalidate()).isTrue(); + assertThat(c.isProxyRevalidate()).isTrue(); + assertThat(c.isNoCache()).isTrue(); + assertThat(c.isNoTransform()).isTrue(); + assertThat(c.getNoCacheFields().size() == 1).isTrue(); + assertThat(c.getPrivateFields().size() == 1).isTrue(); + assertThat(c.getPrivateFields().get(0)).isEqualTo("foo"); + assertThat(c.getNoCacheFields().get(0)).isEqualTo("bar"); } @Test @@ -47,7 +45,7 @@ public void testToString() { String expected = "private=\"foo\",no-cache=\"bar\",no-store,no-transform,must-revalidate,proxy-revalidate,max-age=2,s-maxage=3"; String parsed = CacheControl.valueOf(expected).toString(); - assertEquals(parsed, expected); + assertThat(parsed).isEqualTo(expected); } @Test @@ -55,7 +53,7 @@ public void testNoCacheEnabled() { CacheControl cc = new CacheControl(); cc.setNoCache(true); - assertEquals(cc.toString(), "no-cache,no-transform"); + assertThat(cc.toString()).isEqualTo("no-cache,no-transform"); } @Test @@ -63,7 +61,7 @@ public void testNoCacheDisabled() { CacheControl cc = new CacheControl(); cc.setNoCache(false); - assertEquals(cc.toString(), "no-transform"); + assertThat(cc.toString()).isEqualTo("no-transform"); } @Test @@ -73,7 +71,7 @@ public void testMultiplePrivateFields() cc.setPrivate(true); cc.getPrivateFields().add("a"); cc.getPrivateFields().add("b"); - assertTrue(cc.toString().contains("private=\"a,b\"")); + assertThat(cc.toString().contains("private=\"a,b\"")).isTrue(); } @Test @@ -83,7 +81,7 @@ public void testMultipleNoCacheFields() cc.setNoCache(true); cc.getNoCacheFields().add("c"); cc.getNoCacheFields().add("d"); - assertTrue(cc.toString().contains("no-cache=\"c,d\"")); + assertThat(cc.toString().contains("no-cache=\"c,d\"")).isTrue(); } @Test @@ -92,27 +90,27 @@ public void testReadMultiplePrivateAndNoCacheFields() String s = "private=\"foo1,foo2\",no-store,no-transform,must-revalidate,proxy-revalidate,max-age=2,s-maxage=3,no-cache=\"bar1,bar2\",ext=1"; CacheControl cacheControl = CacheControl.valueOf(s); - assertTrue(cacheControl.isPrivate()); + assertThat(cacheControl.isPrivate()).isTrue(); List privateFields = cacheControl.getPrivateFields(); - assertEquals(privateFields.size(), 2); - assertEquals(privateFields.get(0), "foo1"); - assertEquals(privateFields.get(1), "foo2"); - assertTrue(cacheControl.isNoCache()); + assertThat(privateFields.size()).isEqualTo(2); + assertThat(privateFields.get(0)).isEqualTo("foo1"); + assertThat(privateFields.get(1)).isEqualTo("foo2"); + assertThat(cacheControl.isNoCache()).isTrue(); List noCacheFields = cacheControl.getNoCacheFields(); - assertEquals(2, noCacheFields.size()); - assertEquals(noCacheFields.get(0), "bar1"); - assertEquals(noCacheFields.get(1), "bar2"); + assertThat(2).isEqualTo(noCacheFields.size()); + assertThat(noCacheFields.get(0)).isEqualTo("bar1"); + assertThat(noCacheFields.get(1)).isEqualTo("bar2"); - assertTrue(cacheControl.isNoStore()); - assertTrue(cacheControl.isNoTransform()); - assertTrue(cacheControl.isMustRevalidate()); - assertTrue(cacheControl.isProxyRevalidate()); - assertEquals(cacheControl.getMaxAge(), 2); - assertEquals(cacheControl.getSMaxAge(), 3); + assertThat(cacheControl.isNoStore()).isTrue(); + assertThat(cacheControl.isNoTransform()).isTrue(); + assertThat(cacheControl.isMustRevalidate()).isTrue(); + assertThat(cacheControl.isProxyRevalidate()).isTrue(); + assertThat(cacheControl.getMaxAge()).isEqualTo(2); + assertThat(cacheControl.getSMaxAge()).isEqualTo(3); Map cacheExtension = cacheControl.getCacheExtension(); - assertEquals(cacheExtension.size(), 1); - assertEquals(cacheExtension.get("ext"), "1"); + assertThat(cacheExtension.size()).isEqualTo(1); + assertThat(cacheExtension.get("ext")).isEqualTo("1"); } @Test @@ -123,8 +121,8 @@ public void testCacheExtensionToString() cc.getCacheExtension().put("ext2", "value2"); cc.getCacheExtension().put("ext3", "value 3"); String value = cc.toString(); - assertTrue(value.contains("ext1") && !value.contains("ext1=")); - assertTrue(value.contains("ext2=value2")); - assertTrue(value.contains("ext3=\"value 3\"")); + assertThat(value.contains("ext1") && !value.contains("ext1=")).isTrue(); + assertThat(value.contains("ext2=value2")).isTrue(); + assertThat(value.contains("ext3=\"value 3\"")).isTrue(); } } diff --git a/http-client/src/test/java/io/airlift/http/client/TestDefaultingJsonResponseHandler.java b/http-client/src/test/java/io/airlift/http/client/TestDefaultingJsonResponseHandler.java index 76ae64729ec..ef9a6fb5da2 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestDefaultingJsonResponseHandler.java +++ b/http-client/src/test/java/io/airlift/http/client/TestDefaultingJsonResponseHandler.java @@ -11,7 +11,7 @@ import static io.airlift.http.client.HttpStatus.INTERNAL_SERVER_ERROR; import static io.airlift.http.client.HttpStatus.OK; import static io.airlift.http.client.testing.TestingResponse.mockResponse; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertSame; public class TestDefaultingJsonResponseHandler @@ -28,8 +28,8 @@ public void testValidJson() String json = codec.toJson(user); User response = handler.handle(null, mockResponse(OK, JSON_UTF_8, json)); - assertEquals(response.getName(), user.getName()); - assertEquals(response.getAge(), user.getAge()); + assertThat(response.getName()).isEqualTo(user.getName()); + assertThat(response.getAge()).isEqualTo(user.getAge()); } @Test diff --git a/http-client/src/test/java/io/airlift/http/client/TestFormDataBodyBuilder.java b/http-client/src/test/java/io/airlift/http/client/TestFormDataBodyBuilder.java index ba1712b5214..b77c317d957 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestFormDataBodyBuilder.java +++ b/http-client/src/test/java/io/airlift/http/client/TestFormDataBodyBuilder.java @@ -3,7 +3,7 @@ import org.testng.annotations.Test; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestFormDataBodyBuilder { @@ -17,6 +17,6 @@ public void test() .addField(":", "colon") .build() .getBody(); - assertEquals(new String(body, UTF_8), "a=apple&b=banana+split&c=com%2Cma&%3A=colon"); + assertThat(new String(body, UTF_8)).isEqualTo("a=apple&b=banana+split&c=com%2Cma&%3A=colon"); } } diff --git a/http-client/src/test/java/io/airlift/http/client/TestFullJsonResponseHandler.java b/http-client/src/test/java/io/airlift/http/client/TestFullJsonResponseHandler.java index 11b343617df..843b920a5c2 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestFullJsonResponseHandler.java +++ b/http-client/src/test/java/io/airlift/http/client/TestFullJsonResponseHandler.java @@ -16,12 +16,9 @@ import static io.airlift.http.client.testing.TestingResponse.mockResponse; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.testng.Assert.assertNotSame; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public class TestFullJsonResponseHandler @@ -36,19 +33,19 @@ public void testValidJson() String json = codec.toJson(user); JsonResponse response = handler.handle(null, mockResponse(OK, JSON_UTF_8, json)); - assertTrue(response.hasValue()); - assertEquals(response.getJsonBytes(), json.getBytes(UTF_8)); - assertEquals(response.getJson(), json); - assertEquals(response.getValue().getName(), user.getName()); - assertEquals(response.getValue().getAge(), user.getAge()); + assertThat(response.hasValue()).isTrue(); + assertThat(response.getJsonBytes()).isEqualTo(json.getBytes(UTF_8)); + assertThat(response.getJson()).isEqualTo(json); + assertThat(response.getValue().getName()).isEqualTo(user.getName()); + assertThat(response.getValue().getAge()).isEqualTo(user.getAge()); assertNotSame(response.getJson(), response.getJson()); assertNotSame(response.getJsonBytes(), response.getJsonBytes()); assertNotSame(response.getResponseBytes(), response.getResponseBytes()); assertNotSame(response.getResponseBody(), response.getResponseBody()); - assertEquals(response.getResponseBytes(), response.getJsonBytes()); - assertEquals(response.getResponseBody(), response.getJson()); + assertThat(response.getResponseBytes()).isEqualTo(response.getJsonBytes()); + assertThat(response.getResponseBody()).isEqualTo(response.getJson()); } @Test @@ -57,16 +54,16 @@ public void testInvalidJson() String json = "{\"age\": \"foo\"}"; JsonResponse response = handler.handle(null, mockResponse(OK, JSON_UTF_8, json)); - assertFalse(response.hasValue()); - assertEquals(response.getException().getMessage(), format("Unable to create %s from JSON response:\n[%s]", User.class, json)); - assertTrue(response.getException().getCause() instanceof IllegalArgumentException); - assertEquals(response.getException().getCause().getMessage(), "Invalid JSON bytes for [simple type, class io.airlift.http.client.TestFullJsonResponseHandler$User]"); + assertThat(response.hasValue()).isFalse(); + assertThat(response.getException().getMessage()).isEqualTo(format("Unable to create %s from JSON response:\n[%s]", User.class, json)); + assertThat(response.getException().getCause() instanceof IllegalArgumentException).isTrue(); + assertThat(response.getException().getCause().getMessage()).isEqualTo("Invalid JSON bytes for [simple type, class io.airlift.http.client.TestFullJsonResponseHandler$User]"); - assertEquals(response.getJsonBytes(), json.getBytes(UTF_8)); - assertEquals(response.getJson(), json); + assertThat(response.getJsonBytes()).isEqualTo(json.getBytes(UTF_8)); + assertThat(response.getJson()).isEqualTo(json); - assertEquals(response.getResponseBytes(), response.getJsonBytes()); - assertEquals(response.getResponseBody(), response.getJson()); + assertThat(response.getResponseBytes()).isEqualTo(response.getJsonBytes()); + assertThat(response.getResponseBody()).isEqualTo(response.getJson()); } @Test @@ -80,14 +77,14 @@ public void testInvalidJsonGetValue() fail("expected exception"); } catch (IllegalStateException e) { - assertEquals(e.getMessage(), "Response does not contain a JSON value"); - assertEquals(e.getCause(), response.getException()); + assertThat(e.getMessage()).isEqualTo("Response does not contain a JSON value"); + assertThat(e.getCause()).isEqualTo(response.getException()); - assertEquals(response.getJsonBytes(), json.getBytes(UTF_8)); - assertEquals(response.getJson(), json); + assertThat(response.getJsonBytes()).isEqualTo(json.getBytes(UTF_8)); + assertThat(response.getJson()).isEqualTo(json); - assertEquals(response.getResponseBytes(), response.getJsonBytes()); - assertEquals(response.getResponseBody(), response.getJson()); + assertThat(response.getResponseBytes()).isEqualTo(response.getJsonBytes()); + assertThat(response.getResponseBody()).isEqualTo(response.getJson()); } } @@ -96,13 +93,13 @@ public void testNonJsonResponse() { JsonResponse response = handler.handle(null, mockResponse(OK, PLAIN_TEXT_UTF_8, "hello")); - assertFalse(response.hasValue()); - assertNull(response.getException()); - assertNull(response.getJson()); - assertNull(response.getJsonBytes()); + assertThat(response.hasValue()).isFalse(); + assertThat(response.getException()).isNull(); + assertThat(response.getJson()).isNull(); + assertThat(response.getJsonBytes()).isNull(); - assertEquals(response.getResponseBytes(), "hello".getBytes(UTF_8)); - assertEquals(response.getResponseBody(), "hello"); + assertThat(response.getResponseBytes()).isEqualTo("hello".getBytes(UTF_8)); + assertThat(response.getResponseBody()).isEqualTo("hello"); } @Test @@ -111,15 +108,15 @@ public void testMissingContentType() JsonResponse response = handler.handle(null, new TestingResponse(OK, ImmutableListMultimap.of(), "hello".getBytes(UTF_8))); - assertFalse(response.hasValue()); - assertNull(response.getException()); - assertNull(response.getJson()); - assertNull(response.getJsonBytes()); + assertThat(response.hasValue()).isFalse(); + assertThat(response.getException()).isNull(); + assertThat(response.getJson()).isNull(); + assertThat(response.getJsonBytes()).isNull(); - assertEquals(response.getResponseBytes(), "hello".getBytes(UTF_8)); - assertEquals(response.getResponseBody(), "hello"); + assertThat(response.getResponseBytes()).isEqualTo("hello".getBytes(UTF_8)); + assertThat(response.getResponseBody()).isEqualTo("hello"); - assertTrue(response.getHeaders().isEmpty()); + assertThat(response.getHeaders().isEmpty()).isTrue(); } @Test @@ -128,14 +125,14 @@ public void testJsonErrorResponse() String json = "{\"error\": true}"; JsonResponse response = handler.handle(null, mockResponse(INTERNAL_SERVER_ERROR, JSON_UTF_8, json)); - assertTrue(response.hasValue()); - assertEquals(response.getJson(), json); - assertEquals(response.getJsonBytes(), json.getBytes(UTF_8)); - assertNull(response.getValue().getName()); - assertEquals(response.getValue().getAge(), 0); + assertThat(response.hasValue()).isTrue(); + assertThat(response.getJson()).isEqualTo(json); + assertThat(response.getJsonBytes()).isEqualTo(json.getBytes(UTF_8)); + assertThat(response.getValue().getName()).isNull(); + assertThat(response.getValue().getAge()).isEqualTo(0); - assertEquals(response.getResponseBytes(), response.getJsonBytes()); - assertEquals(response.getResponseBody(), response.getJson()); + assertThat(response.getResponseBytes()).isEqualTo(response.getJsonBytes()); + assertThat(response.getResponseBody()).isEqualTo(response.getJson()); } public static class User diff --git a/http-client/src/test/java/io/airlift/http/client/TestGatheringByteArrayInputStream.java b/http-client/src/test/java/io/airlift/http/client/TestGatheringByteArrayInputStream.java index a2a78ed26ee..0ac245e41d0 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestGatheringByteArrayInputStream.java +++ b/http-client/src/test/java/io/airlift/http/client/TestGatheringByteArrayInputStream.java @@ -10,7 +10,7 @@ import static java.lang.Math.min; import static java.lang.System.arraycopy; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestGatheringByteArrayInputStream { @@ -34,19 +34,19 @@ public void testNormal() byte[] buffer = new byte[expectedAll.length + 32]; // read the first part - assertEquals(in.read(buffer, 0, expectedPartial.length), expectedPartial.length); + assertThat(in.read(buffer, 0, expectedPartial.length)).isEqualTo(expectedPartial.length); // verify the first part assertByteArrayEquals(buffer, 0, expectedPartial, 0, expectedPartial.length); // read the remaining part - assertEquals(in.read(buffer, expectedPartial.length, buffer.length - expectedPartial.length), expectedAll.length - expectedPartial.length); + assertThat(in.read(buffer, expectedPartial.length, buffer.length - expectedPartial.length)).isEqualTo(expectedAll.length - expectedPartial.length); // verify the whole string assertByteArrayEquals(buffer, 0, expectedAll, 0, expectedAll.length); // make sure there is no more data - assertEquals(-1, in.read(buffer, 0, expectedAll.length)); + assertThat(-1).isEqualTo(in.read(buffer, 0, expectedAll.length)); } } @@ -67,7 +67,7 @@ public void testSingleByteRead() resultBuffer[i] = (byte) in.read(); } assertByteArrayEquals(resultBuffer, 0, expected, 0, expected.length); - assertEquals(in.read(), -1); + assertThat(in.read()).isEqualTo(-1); } } @@ -77,8 +77,8 @@ public void testNegativeSingleByteRead() byte[] expected = new byte[1]; expected[0] = -100; try (GatheringByteArrayInputStream in = new GatheringByteArrayInputStream(ImmutableList.of(expected), expected.length)) { - assertEquals(in.read(), expected[0] & 0x000000ff); - assertEquals(in.read(), -1); + assertThat(in.read()).isEqualTo(expected[0] & 0x000000ff); + assertThat(in.read()).isEqualTo(-1); } } @@ -99,18 +99,18 @@ public void testSkip() byte[] actual = new byte[length - skipped + 10]; // read the first part - assertEquals(in.read(actual, 0, firstPartLength), firstPartLength); + assertThat(in.read(actual, 0, firstPartLength)).isEqualTo(firstPartLength); assertByteArrayEquals(actual, 0, allDataBytes, 0, firstPartLength); // skip some bytes - assertEquals(in.skip(skipped), skipped); + assertThat(in.skip(skipped)).isEqualTo(skipped); // read the rest part - assertEquals(in.read(actual, firstPartLength, restPartLength + 10), restPartLength); + assertThat(in.read(actual, firstPartLength, restPartLength + 10)).isEqualTo(restPartLength); assertByteArrayEquals(actual, firstPartLength, allDataBytes, firstPartLength + skipped, restPartLength); - assertEquals(in.skip(10), 0); - assertEquals(in.read(), -1); + assertThat(in.skip(10)).isEqualTo(0); + assertThat(in.read()).isEqualTo(-1); } } @@ -135,12 +135,12 @@ public void testLargeData() copyBytes = 0; while (copyBytes < length) { int currentLength = min(length - copyBytes, random.nextInt(1 << 20) + 64); - assertEquals(in.read(actual, copyBytes, currentLength), currentLength); + assertThat(in.read(actual, copyBytes, currentLength)).isEqualTo(currentLength); assertByteArrayEquals(actual, copyBytes, expected, copyBytes, currentLength); copyBytes += currentLength; } - assertEquals(in.skip(100), 0); - assertEquals(in.read(), -1); + assertThat(in.skip(100)).isEqualTo(0); + assertThat(in.read()).isEqualTo(-1); } } @@ -152,7 +152,7 @@ private static void assertByteArrayEquals( int length) { for (int i = 0; i < length; i++) { - assertEquals(actual[i + actualStart], expected[i + expectedStart]); + assertThat(actual[i + actualStart]).isEqualTo(expected[i + expectedStart]); } } } diff --git a/http-client/src/test/java/io/airlift/http/client/TestHeaderName.java b/http-client/src/test/java/io/airlift/http/client/TestHeaderName.java index 425304300d7..93e330dbb1b 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestHeaderName.java +++ b/http-client/src/test/java/io/airlift/http/client/TestHeaderName.java @@ -3,7 +3,7 @@ import org.testng.annotations.Test; import static io.airlift.testing.EquivalenceTester.equivalenceTester; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestHeaderName { @@ -19,7 +19,7 @@ public void testEquivalence() @Test public void testToString() { - assertEquals(HeaderName.of("FOO").toString(), "FOO"); - assertEquals(HeaderName.of("foo").toString(), "foo"); + assertThat(HeaderName.of("FOO").toString()).isEqualTo("FOO"); + assertThat(HeaderName.of("foo").toString()).isEqualTo("foo"); } } diff --git a/http-client/src/test/java/io/airlift/http/client/TestHttpClientBinder.java b/http-client/src/test/java/io/airlift/http/client/TestHttpClientBinder.java index 368900c6745..063c60f7921 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestHttpClientBinder.java +++ b/http-client/src/test/java/io/airlift/http/client/TestHttpClientBinder.java @@ -38,12 +38,8 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; import static java.util.concurrent.TimeUnit.MINUTES; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; public class TestHttpClientBinder { @@ -59,7 +55,7 @@ public void testConfigDefaults() .initialize(); JettyHttpClient httpClient = (JettyHttpClient) injector.getInstance(Key.get(HttpClient.class, FooClient.class)); - assertEquals(httpClient.getRequestTimeoutMillis(), MINUTES.toMillis(33)); + assertThat(httpClient.getRequestTimeoutMillis()).isEqualTo(MINUTES.toMillis(33)); } @Test @@ -117,15 +113,15 @@ public void testGlobalFilterBinding() JettyHttpClient fooClient = (JettyHttpClient) injector.getInstance(Key.get(HttpClient.class, FooClient.class)); assertFilterCount(fooClient, 3); - assertEquals(fooClient.getRequestFilters().get(0), globalFilter1); - assertEquals(fooClient.getRequestFilters().get(1), globalFilter2); - assertEquals(fooClient.getRequestFilters().get(2), filter1); + assertThat(fooClient.getRequestFilters().get(0)).isEqualTo(globalFilter1); + assertThat(fooClient.getRequestFilters().get(1)).isEqualTo(globalFilter2); + assertThat(fooClient.getRequestFilters().get(2)).isEqualTo(filter1); JettyHttpClient barClient = (JettyHttpClient) injector.getInstance(Key.get(HttpClient.class, BarClient.class)); assertFilterCount(barClient, 3); - assertEquals(barClient.getRequestFilters().get(0), globalFilter1); - assertEquals(barClient.getRequestFilters().get(1), globalFilter2); - assertEquals(barClient.getRequestFilters().get(2), filter2); + assertThat(barClient.getRequestFilters().get(0)).isEqualTo(globalFilter1); + assertThat(barClient.getRequestFilters().get(1)).isEqualTo(globalFilter2); + assertThat(barClient.getRequestFilters().get(2)).isEqualTo(filter2); } @Test @@ -189,7 +185,7 @@ public void testWithoutFilters() .quiet() .initialize(); - assertNotNull(injector.getInstance(Key.get(HttpClient.class, FooClient.class))); + assertThat(injector.getInstance(Key.get(HttpClient.class, FooClient.class))).isNotNull(); } @Test @@ -253,20 +249,20 @@ public void testClientShutdown() HttpClient fooClient = injector.getInstance(Key.get(HttpClient.class, FooClient.class)); HttpClient barClient = injector.getInstance(Key.get(HttpClient.class, BarClient.class)); - assertFalse(fooClient.isClosed()); - assertFalse(barClient.isClosed()); + assertThat(fooClient.isClosed()).isFalse(); + assertThat(barClient.isClosed()).isFalse(); injector.getInstance(LifeCycleManager.class).stop(); - assertTrue(fooClient.isClosed()); - assertTrue(barClient.isClosed()); + assertThat(fooClient.isClosed()).isTrue(); + assertThat(barClient.isClosed()).isTrue(); } private static void assertFilterCount(HttpClient httpClient, int filterCount) { - assertNotNull(httpClient); + assertThat(httpClient).isNotNull(); assertInstanceOf(httpClient, JettyHttpClient.class); - assertEquals(((JettyHttpClient) httpClient).getRequestFilters().size(), filterCount); + assertThat(((JettyHttpClient) httpClient).getRequestFilters().size()).isEqualTo(filterCount); } private static void assertStatusListenerCount(HttpClient httpClient, int statusListenerCount) diff --git a/http-client/src/test/java/io/airlift/http/client/TestHttpUriBuilder.java b/http-client/src/test/java/io/airlift/http/client/TestHttpUriBuilder.java index 31e1d3ffbb0..16a766a14ae 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestHttpUriBuilder.java +++ b/http-client/src/test/java/io/airlift/http/client/TestHttpUriBuilder.java @@ -7,8 +7,8 @@ import static io.airlift.http.client.HttpUriBuilder.uriBuilder; import static io.airlift.http.client.HttpUriBuilder.uriBuilderFrom; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; public class TestHttpUriBuilder { @@ -16,7 +16,7 @@ public class TestHttpUriBuilder public void testCreateFromUri() { URI original = URI.create("http://www.example.com:8081/a%20/%C3%A5?k=1&k=2&%C3%A5=3"); - assertEquals(uriBuilderFrom(original).build(), original); + assertThat(uriBuilderFrom(original).build()).isEqualTo(original); } @Test @@ -27,7 +27,7 @@ public void testBasic() .host("www.example.com") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com"); } @Test @@ -39,7 +39,7 @@ public void testWithPath() .replacePath("/a/b/c") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/a/b/c"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/a/b/c"); } @Test @@ -51,7 +51,7 @@ public void testReplacePathWithRelative() .replacePath("a/b/c") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/a/b/c"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/a/b/c"); } @Test @@ -63,7 +63,7 @@ public void testAppendToDefaultPath() .appendPath("/a/b/c") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/a/b/c"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/a/b/c"); } @Test @@ -75,7 +75,7 @@ public void testAppendRelativePathToDefault() .appendPath("a/b/c") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/a/b/c"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/a/b/c"); } @Test @@ -88,7 +88,7 @@ public void testAppendAbsolutePath() .appendPath("/x/y/z") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/a/b/c/x/y/z"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/a/b/c/x/y/z"); } @Test @@ -101,7 +101,7 @@ public void testAppendRelativePath() .appendPath("x/y/z") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/a/b/c/x/y/z"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/a/b/c/x/y/z"); } @Test @@ -114,7 +114,7 @@ public void testAppendPathElidesSlashes() .appendPath("/x/y/z") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/a/b/c/x/y/z"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/a/b/c/x/y/z"); } @Test @@ -126,7 +126,7 @@ public void testDoesNotStripTrailingSlash() .appendPath("/a/b/c/") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/a/b/c/"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/a/b/c/"); } @Test @@ -140,7 +140,7 @@ public void testFull() .replaceParameter("k", "1") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com:8081/a/b/c?k=1"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com:8081/a/b/c?k=1"); } @Test @@ -156,7 +156,7 @@ public void testAddParameter() .addParameter("k2", "3") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/?k1=1&k1=2&k1=0&k2=3"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/?k1=1&k1=2&k1=0&k2=3"); } @Test @@ -169,7 +169,7 @@ public void testAddParameterMultivalued() .addParameter("k1", "1", "2", "0") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/?k1=1&k1=2&k1=0"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/?k1=1&k1=2&k1=0"); } @Test @@ -181,7 +181,7 @@ public void testAddEmptyParameter() .addParameter("pretty") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/?pretty"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/?pretty"); } @Test @@ -194,7 +194,7 @@ public void testAddMultipleEmptyParameters() .addParameter("pretty") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/?pretty&pretty"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/?pretty&pretty"); } @Test @@ -208,7 +208,7 @@ public void testAddMixedEmptyAndNonEmptyParameters() .addParameter("pretty") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/?pretty&pretty=true&pretty"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/?pretty&pretty=true&pretty"); } @Test @@ -218,7 +218,7 @@ public void testReplaceParameters() .replaceParameter("k1", "4") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com:8081/?k2=3&k1=4"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com:8081/?k2=3&k1=4"); } @Test @@ -228,7 +228,7 @@ public void testReplaceParameterMultivalued() .replaceParameter("k1", "a", "b", "c") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/?k2=3&k1=a&k1=b&k1=c"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/?k2=3&k1=a&k1=b&k1=c"); } @Test @@ -238,7 +238,7 @@ public void testReplacePort() .port(801) .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com:801/"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com:801/"); } @Test @@ -248,19 +248,19 @@ public void testDefaultPort() .defaultPort() .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com"); uri = uriBuilderFrom(URI.create("http://www.example.com:8081")) .port(80) .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com"); uri = uriBuilderFrom(URI.create("https://www.example.com:8081")) .port(443) .build(); - assertEquals(uri.toASCIIString(), "https://www.example.com"); + assertThat(uri.toASCIIString()).isEqualTo("https://www.example.com"); } @Test @@ -273,7 +273,7 @@ public void testHostWithIpv6() .replacePath("/a/b") .build(); - assertEquals(uri.toASCIIString(), "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8081/a/b"); + assertThat(uri.toASCIIString()).isEqualTo("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8081/a/b"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "host starts with a bracket") @@ -286,7 +286,7 @@ public void testHostWithBracketedIpv6() .replacePath("/a/b") .build(); - assertEquals(uri.toASCIIString(), "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8081/a/b"); + assertThat(uri.toASCIIString()).isEqualTo("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8081/a/b"); } @Test @@ -298,7 +298,7 @@ public void testHostAndPortWithHostPort() .hostAndPort(HostAndPort.fromParts("example.com", 8081)) .build(); - assertEquals(uri.toASCIIString(), "http://example.com:8081"); + assertThat(uri.toASCIIString()).isEqualTo("http://example.com:8081"); } @Test @@ -310,7 +310,7 @@ public void testHostAndPortWithHostOnly() .hostAndPort(HostAndPort.fromString("example.com")) .build(); - assertEquals(uri.toASCIIString(), "http://example.com"); + assertThat(uri.toASCIIString()).isEqualTo("http://example.com"); } @Test @@ -322,7 +322,7 @@ public void testHostAndPortWithBracketedIpv6() .hostAndPort(HostAndPort.fromParts("[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]", 8081)) .build(); - assertEquals(uri.toASCIIString(), "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8081"); + assertThat(uri.toASCIIString()).isEqualTo("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8081"); } @Test @@ -334,7 +334,7 @@ public void testHostAndPortWithUnbracketedIpv6() .hostAndPort(HostAndPort.fromParts("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210", 8081)) .build(); - assertEquals(uri.toASCIIString(), "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8081"); + assertThat(uri.toASCIIString()).isEqualTo("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:8081"); } @Test @@ -346,7 +346,7 @@ public void testHostAndPortWithUnbracketedIpv6String() .hostAndPort(HostAndPort.fromString("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210")) .build(); - assertEquals(uri.toASCIIString(), "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]"); + assertThat(uri.toASCIIString()).isEqualTo("http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]"); } @Test @@ -358,7 +358,7 @@ public void testEncodesPath() .replacePath("/`#%^{}|[]<>?áéíóú") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/%60%23%25%5E%7B%7D%7C%5B%5D%3C%3E%3F%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/%60%23%25%5E%7B%7D%7C%5B%5D%3C%3E%3F%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA"); } @Test @@ -395,7 +395,7 @@ public void testQueryParametersNoPath() .addParameter("a", "1") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/?a=1"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/?a=1"); } @Test @@ -407,7 +407,7 @@ public void testEncodesQueryParameters() .replaceParameter("a", "&") .build(); - assertEquals(uri.toASCIIString(), "http://www.example.com/?a=%26"); + assertThat(uri.toASCIIString()).isEqualTo("http://www.example.com/?a=%26"); } @Test diff --git a/http-client/src/test/java/io/airlift/http/client/TestJsonResponseHandler.java b/http-client/src/test/java/io/airlift/http/client/TestJsonResponseHandler.java index 6b252ecefbe..3fdc3cf5bb3 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestJsonResponseHandler.java +++ b/http-client/src/test/java/io/airlift/http/client/TestJsonResponseHandler.java @@ -14,8 +14,7 @@ import static io.airlift.http.client.testing.TestingResponse.mockResponse; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestJsonResponseHandler { @@ -28,8 +27,8 @@ public void testValidJson() User user = new User("Joe", 25); User response = handler.handle(null, mockResponse(OK, JSON_UTF_8, codec.toJson(user))); - assertEquals(response.getName(), user.getName()); - assertEquals(response.getAge(), user.getAge()); + assertThat(response.getName()).isEqualTo(user.getName()); + assertThat(response.getAge()).isEqualTo(user.getAge()); } @Test @@ -40,9 +39,9 @@ public void testInvalidJson() handler.handle(null, mockResponse(OK, JSON_UTF_8, json)); } catch (IllegalArgumentException e) { - assertEquals(e.getMessage(), format("Unable to create %s from JSON response:\n[%s]", User.class, json)); - assertTrue(e.getCause() instanceof IllegalArgumentException); - assertEquals(e.getCause().getMessage(), "Invalid JSON bytes for [simple type, class io.airlift.http.client.TestFullJsonResponseHandler$User]"); + assertThat(e.getMessage()).isEqualTo(format("Unable to create %s from JSON response:\n[%s]", User.class, json)); + assertThat(e.getCause() instanceof IllegalArgumentException).isTrue(); + assertThat(e.getCause().getMessage()).isEqualTo("Invalid JSON bytes for [simple type, class io.airlift.http.client.TestFullJsonResponseHandler$User]"); } } diff --git a/http-client/src/test/java/io/airlift/http/client/TestRequestBuilder.java b/http-client/src/test/java/io/airlift/http/client/TestRequestBuilder.java index 421bf359a3c..cb149fc4472 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestRequestBuilder.java +++ b/http-client/src/test/java/io/airlift/http/client/TestRequestBuilder.java @@ -23,8 +23,7 @@ import static io.airlift.http.client.Request.Builder.fromRequest; import static io.airlift.http.client.Request.Builder.prepareGet; import static io.airlift.http.client.StaticBodyGenerator.createStaticBodyGenerator; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import static org.assertj.core.api.Assertions.assertThat; public class TestRequestBuilder { @@ -34,12 +33,12 @@ public class TestRequestBuilder public void testRequestBuilder() { Request request = createRequest(); - assertEquals(request.getMethod(), "GET"); - assertEquals(request.getBodyGenerator(), NULL_BODY_GENERATOR); - assertEquals(request.getUri(), URI.create("http://example.com")); - assertEquals(request.getHeaders(), ImmutableListMultimap.of( + assertThat(request.getMethod()).isEqualTo("GET"); + assertThat(request.getBodyGenerator()).isEqualTo(NULL_BODY_GENERATOR); + assertThat(request.getUri()).isEqualTo(URI.create("http://example.com")); + assertThat(request.getHeaders()).isEqualTo(ImmutableListMultimap.of( "newheader", "withvalue", "anotherheader", "anothervalue")); - assertFalse(request.isFollowRedirects()); + assertThat(request.isFollowRedirects()).isFalse(); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Cannot make requests to HTTP port 0") @@ -53,7 +52,7 @@ public void testCannotBuildRequestToIllegalPort() public void testBuilderFromRequest() { Request request = createRequest(); - assertEquals(fromRequest(request).build(), request); + assertThat(fromRequest(request).build()).isEqualTo(request); } private static Request createRequest() diff --git a/http-client/src/test/java/io/airlift/http/client/TestTraceTokenRequestFilter.java b/http-client/src/test/java/io/airlift/http/client/TestTraceTokenRequestFilter.java index da7a1805bdc..e0066851187 100644 --- a/http-client/src/test/java/io/airlift/http/client/TestTraceTokenRequestFilter.java +++ b/http-client/src/test/java/io/airlift/http/client/TestTraceTokenRequestFilter.java @@ -23,7 +23,7 @@ import static io.airlift.http.client.Request.Builder.prepareGet; import static io.airlift.http.client.TraceTokenRequestFilter.TRACETOKEN_HEADER; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertNotSame; import static org.testng.Assert.assertSame; @@ -40,10 +40,10 @@ public void testBasic() Request filtered = filter.filterRequest(original); assertNotSame(filter, original); - assertEquals(filtered.getUri(), original.getUri()); - assertEquals(original.getHeaders().size(), 0); - assertEquals(filtered.getHeaders().size(), 1); - assertEquals(filtered.getHeaders().get(TRACETOKEN_HEADER), ImmutableList.of("testBasic")); + assertThat(filtered.getUri()).isEqualTo(original.getUri()); + assertThat(original.getHeaders().size()).isEqualTo(0); + assertThat(filtered.getHeaders().size()).isEqualTo(1); + assertThat(filtered.getHeaders().get(TRACETOKEN_HEADER)).isEqualTo(ImmutableList.of("testBasic")); } @Test diff --git a/http-client/src/test/java/io/airlift/http/client/jetty/TestHttpClientLogger.java b/http-client/src/test/java/io/airlift/http/client/jetty/TestHttpClientLogger.java index a8bfe8e2498..8e87fb773c0 100644 --- a/http-client/src/test/java/io/airlift/http/client/jetty/TestHttpClientLogger.java +++ b/http-client/src/test/java/io/airlift/http/client/jetty/TestHttpClientLogger.java @@ -62,8 +62,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.jetty.http.HttpVersion.HTTP_1_1; import static org.eclipse.jetty.http.HttpVersion.HTTP_2; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; @Test(singleThreaded = true) public class TestHttpClientLogger @@ -127,19 +125,19 @@ public void testClientLog() String actual = Files.asCharSource(file, UTF_8).read(); String[] columns = actual.trim().split("\\t"); - assertEquals(columns[0], ISO_FORMATTER.format(Instant.ofEpochMilli(requestTimestamp))); - assertEquals(columns[1], HTTP_2.toString()); - assertEquals(columns[2], method); - assertEquals(columns[3], uri.toString()); - assertEquals(columns[4], Integer.toString(status)); - assertEquals(columns[5], Long.toString(responseSize)); - assertEquals(columns[6], Long.toString(NANOSECONDS.toMillis(requestTotalTime))); - assertEquals(columns[7], Long.toString(NANOSECONDS.toMillis(queueTime))); - assertEquals(columns[8], Long.toString(NANOSECONDS.toMillis(requestEnd - requestBegin))); - assertEquals(columns[9], Long.toString(NANOSECONDS.toMillis(responseBegin - requestEnd))); - assertEquals(columns[10], Long.toString(NANOSECONDS.toMillis(responseComplete - responseBegin))); - assertEquals(columns[11], Long.toString(responseInfo.getResponseTimestampMillis() - requestTimestamp)); - assertEquals(columns[12], "test-token"); + assertThat(columns[0]).isEqualTo(ISO_FORMATTER.format(Instant.ofEpochMilli(requestTimestamp))); + assertThat(columns[1]).isEqualTo(HTTP_2.toString()); + assertThat(columns[2]).isEqualTo(method); + assertThat(columns[3]).isEqualTo(uri.toString()); + assertThat(columns[4]).isEqualTo(Integer.toString(status)); + assertThat(columns[5]).isEqualTo(Long.toString(responseSize)); + assertThat(columns[6]).isEqualTo(Long.toString(NANOSECONDS.toMillis(requestTotalTime))); + assertThat(columns[7]).isEqualTo(Long.toString(NANOSECONDS.toMillis(queueTime))); + assertThat(columns[8]).isEqualTo(Long.toString(NANOSECONDS.toMillis(requestEnd - requestBegin))); + assertThat(columns[9]).isEqualTo(Long.toString(NANOSECONDS.toMillis(responseBegin - requestEnd))); + assertThat(columns[10]).isEqualTo(Long.toString(NANOSECONDS.toMillis(responseComplete - responseBegin))); + assertThat(columns[11]).isEqualTo(Long.toString(responseInfo.getResponseTimestampMillis() - requestTimestamp)); + assertThat(columns[12]).isEqualTo("test-token"); } @Test @@ -169,19 +167,19 @@ public void testClientLogNoResponse() String actual = Files.asCharSource(file, UTF_8).read(); String[] columns = actual.trim().split("\\t"); - assertEquals(columns[0], ISO_FORMATTER.format(Instant.ofEpochMilli(requestTimestamp))); - assertEquals(columns[1], HTTP_1_1.toString()); - assertEquals(columns[2], method); - assertEquals(columns[3], uri.toString()); - assertEquals(columns[4], getFailureReason(responseInfo).get()); - assertEquals(columns[5], Integer.toString(NO_RESPONSE)); - assertNotEquals(columns[6], Long.toString(0)); - assertEquals(columns[7], Long.toString(0)); - assertEquals(columns[8], Long.toString(0)); - assertEquals(columns[9], Long.toString(0)); - assertEquals(columns[10], Long.toString(0)); - assertEquals(columns[11], Long.toString(responseInfo.getResponseTimestampMillis() - requestTimestamp)); - assertEquals(columns[12], "test-token"); + assertThat(columns[0]).isEqualTo(ISO_FORMATTER.format(Instant.ofEpochMilli(requestTimestamp))); + assertThat(columns[1]).isEqualTo(HTTP_1_1.toString()); + assertThat(columns[2]).isEqualTo(method); + assertThat(columns[3]).isEqualTo(uri.toString()); + assertThat(columns[4]).isEqualTo(getFailureReason(responseInfo).get()); + assertThat(columns[5]).isEqualTo(Integer.toString(NO_RESPONSE)); + assertThat(columns[6]).isNotEqualTo(Long.toString(0)); + assertThat(columns[7]).isEqualTo(Long.toString(0)); + assertThat(columns[8]).isEqualTo(Long.toString(0)); + assertThat(columns[9]).isEqualTo(Long.toString(0)); + assertThat(columns[10]).isEqualTo(Long.toString(0)); + assertThat(columns[11]).isEqualTo(Long.toString(responseInfo.getResponseTimestampMillis() - requestTimestamp)); + assertThat(columns[12]).isEqualTo("test-token"); } @Test diff --git a/http-client/src/test/java/io/airlift/http/client/testing/TestTestingHttpClient.java b/http-client/src/test/java/io/airlift/http/client/testing/TestTestingHttpClient.java index 70c71e1c240..bd5ac56806f 100644 --- a/http-client/src/test/java/io/airlift/http/client/testing/TestTestingHttpClient.java +++ b/http-client/src/test/java/io/airlift/http/client/testing/TestTestingHttpClient.java @@ -11,8 +11,8 @@ import static io.airlift.http.client.Request.Builder.prepareGet; import static io.airlift.testing.Assertions.assertInstanceOf; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; public class TestTestingHttpClient { @@ -37,7 +37,7 @@ public void testExceptionFromProcessor() catch (ExecutionException e) { Throwable cause = e.getCause(); assertInstanceOf(cause, CapturedException.class); - assertEquals(cause.getCause(), expectedException); + assertThat(cause.getCause()).isEqualTo(expectedException); } } } diff --git a/http-server/src/test/java/io/airlift/http/server/TestDelimitedRequestLog.java b/http-server/src/test/java/io/airlift/http/server/TestDelimitedRequestLog.java index cb94361c802..3e20ae14005 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestDelimitedRequestLog.java +++ b/http-server/src/test/java/io/airlift/http/server/TestDelimitedRequestLog.java @@ -44,12 +44,12 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.assertj.core.api.Assertions.assertThat; import static org.eclipse.jetty.http.HttpVersion.HTTP_2; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; @Test(singleThreaded = true) public class TestDelimitedRequestLog @@ -104,13 +104,13 @@ public void testTraceTokenHeader() logger.stop(); List events = eventClient.getEvents(); - assertEquals(events.size(), 3); + assertThat(events.size()).isEqualTo(3); // first two events should have the token set from the header for (int i = 0; i < 2; i++) { - assertEquals(((HttpRequestEvent) events.get(i)).traceToken(), token); + assertThat(((HttpRequestEvent) events.get(i)).traceToken()).isEqualTo(token); } // last event should have the token set by the tokenManager - assertEquals(((HttpRequestEvent) events.get(2)).traceToken(), tokenManager.getCurrentRequestToken()); + assertThat(((HttpRequestEvent) events.get(2)).traceToken()).isEqualTo(tokenManager.getCurrentRequestToken()); } } @@ -176,28 +176,28 @@ public void testWriteLog() logger.stop(); List events = eventClient.getEvents(); - assertEquals(events.size(), 1); + assertThat(events.size()).isEqualTo(1); HttpRequestEvent event = (HttpRequestEvent) events.get(0); - assertEquals(event.timeStamp().toEpochMilli(), timings.requestStarted().toEpochMilli()); - assertEquals(event.clientAddress(), ip); - assertEquals(event.protocol(), protocol); - assertEquals(event.method(), method); - assertEquals(event.requestUri(), uri.toString()); - assertEquals(event.user(), user); - assertEquals(event.agent(), agent); - assertEquals(event.referrer(), referrer); - assertEquals(event.requestSize(), requestSize); - assertEquals(event.requestContentType(), requestContentType); - assertEquals(event.responseSize(), responseSize); - assertEquals(event.responseCode(), responseCode); - assertEquals(event.responseContentType(), responseContentType); - assertEquals(event.timeToFirstByte(), timeToFirstByte); - assertEquals(event.timeToLastByte(), timeToLastByte); - assertEquals(event.traceToken(), tokenManager.getCurrentRequestToken()); - assertEquals(event.timeToHandle(), timeToHandle); - assertEquals(event.timeFromFirstToLastContent(), event.timeToLastByte() - event.timeToFirstByte()); - assertEquals(event.responseContentInterarrivalStats(), responseContentInterarrivalStats); + assertThat(event.timeStamp().toEpochMilli()).isEqualTo(timings.requestStarted().toEpochMilli()); + assertThat(event.clientAddress()).isEqualTo(ip); + assertThat(event.protocol()).isEqualTo(protocol); + assertThat(event.method()).isEqualTo(method); + assertThat(event.requestUri()).isEqualTo(uri.toString()); + assertThat(event.user()).isEqualTo(user); + assertThat(event.agent()).isEqualTo(agent); + assertThat(event.referrer()).isEqualTo(referrer); + assertThat(event.requestSize()).isEqualTo(requestSize); + assertThat(event.requestContentType()).isEqualTo(requestContentType); + assertThat(event.responseSize()).isEqualTo(responseSize); + assertThat(event.responseCode()).isEqualTo(responseCode); + assertThat(event.responseContentType()).isEqualTo(responseContentType); + assertThat(event.timeToFirstByte()).isEqualTo(timeToFirstByte); + assertThat(event.timeToLastByte()).isEqualTo(timeToLastByte); + assertThat(event.traceToken()).isEqualTo(tokenManager.getCurrentRequestToken()); + assertThat(event.timeToHandle()).isEqualTo(timeToHandle); + assertThat(event.timeFromFirstToLastContent()).isEqualTo(event.timeToLastByte() - event.timeToFirstByte()); + assertThat(event.responseContentInterarrivalStats()).isEqualTo(responseContentInterarrivalStats); String actual = asCharSource(file, UTF_8).read(); String expected = String.format("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", @@ -218,7 +218,7 @@ public void testWriteLog() firstToLastContentTimeInMillis, format("%.2f, %.2f, %.2f, %d", stats.getMin(), stats.getAverage(), stats.getMax(), stats.getCount())); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } } @@ -239,10 +239,10 @@ public void testNoXForwardedProto() logger.stop(); List events = eventClient.getEvents(); - assertEquals(events.size(), 1); + assertThat(events.size()).isEqualTo(1); HttpRequestEvent event = (HttpRequestEvent) events.get(0); - assertEquals(event.protocol(), protocol); + assertThat(event.protocol()).isEqualTo(protocol); } } @@ -263,10 +263,10 @@ public void testNoXForwardedFor() logger.stop(); List events = eventClient.getEvents(); - assertEquals(events.size(), 1); + assertThat(events.size()).isEqualTo(1); HttpRequestEvent event = (HttpRequestEvent) events.get(0); - assertEquals(event.clientAddress(), clientIp); + assertThat(event.clientAddress()).isEqualTo(clientIp); } } @@ -288,10 +288,10 @@ public void testXForwardedForSkipPrivateAddresses() logger.stop(); List events = eventClient.getEvents(); - assertEquals(events.size(), 1); + assertThat(events.size()).isEqualTo(1); HttpRequestEvent event = (HttpRequestEvent) events.get(0); - assertEquals(event.clientAddress(), clientIp); + assertThat(event.clientAddress()).isEqualTo(clientIp); } } diff --git a/http-server/src/test/java/io/airlift/http/server/TestHttpServerCipher.java b/http-server/src/test/java/io/airlift/http/server/TestHttpServerCipher.java index fd975dfd46f..ecf55190346 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestHttpServerCipher.java +++ b/http-server/src/test/java/io/airlift/http/server/TestHttpServerCipher.java @@ -38,7 +38,7 @@ import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE; import static com.google.common.io.Resources.getResource; import static java.nio.file.Files.createTempDirectory; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.fail; @Test(singleThreaded = true) public class TestHttpServerCipher diff --git a/http-server/src/test/java/io/airlift/http/server/TestHttpServerInfo.java b/http-server/src/test/java/io/airlift/http/server/TestHttpServerInfo.java index 6e12dacbcd4..b4769445222 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestHttpServerInfo.java +++ b/http-server/src/test/java/io/airlift/http/server/TestHttpServerInfo.java @@ -24,7 +24,7 @@ import java.util.Optional; import static io.airlift.testing.Closeables.closeAll; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestHttpServerInfo { @@ -51,16 +51,16 @@ public void testIPv6Url() HttpServerInfo httpServerInfo = new HttpServerInfo(serverConfig, Optional.ofNullable(httpsConfig), nodeInfo); int httpPort = httpServerInfo.getHttpUri().getPort(); - assertEquals(httpServerInfo.getHttpUri(), new URI("http://[::1]:" + httpPort)); - assertEquals(httpServerInfo.getHttpExternalUri(), new URI("http://[2001:db8::2:1]:" + httpPort)); + assertThat(httpServerInfo.getHttpUri()).isEqualTo(new URI("http://[::1]:" + httpPort)); + assertThat(httpServerInfo.getHttpExternalUri()).isEqualTo(new URI("http://[2001:db8::2:1]:" + httpPort)); int httpsPort = httpServerInfo.getHttpsUri().getPort(); - assertEquals(httpServerInfo.getHttpsUri(), new URI("https://[::1]:" + httpsPort)); - assertEquals(httpServerInfo.getHttpsExternalUri(), new URI("https://[2001:db8::2:1]:" + httpsPort)); + assertThat(httpServerInfo.getHttpsUri()).isEqualTo(new URI("https://[::1]:" + httpsPort)); + assertThat(httpServerInfo.getHttpsExternalUri()).isEqualTo(new URI("https://[2001:db8::2:1]:" + httpsPort)); int adminPort = httpServerInfo.getAdminUri().getPort(); - assertEquals(httpServerInfo.getAdminUri(), new URI("https://[::1]:" + adminPort)); - assertEquals(httpServerInfo.getAdminExternalUri(), new URI("https://[2001:db8::2:1]:" + adminPort)); + assertThat(httpServerInfo.getAdminUri()).isEqualTo(new URI("https://[::1]:" + adminPort)); + assertThat(httpServerInfo.getAdminExternalUri()).isEqualTo(new URI("https://[2001:db8::2:1]:" + adminPort)); closeChannels(httpServerInfo); } diff --git a/http-server/src/test/java/io/airlift/http/server/TestHttpServerModule.java b/http-server/src/test/java/io/airlift/http/server/TestHttpServerModule.java index 6f7c55d8a05..62fe3411554 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestHttpServerModule.java +++ b/http-server/src/test/java/io/airlift/http/server/TestHttpServerModule.java @@ -82,10 +82,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.createTempDirectory; import static java.util.Collections.nCopies; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public class TestHttpServerModule @@ -132,7 +129,7 @@ public void testCanConstructServer() .initialize(); HttpServer server = injector.getInstance(HttpServer.class); - assertNotNull(server); + assertThat(server).isNotNull(); } @Test @@ -157,15 +154,15 @@ public void testHttpServerUri() NodeInfo nodeInfo = injector.getInstance(NodeInfo.class); HttpServer server = injector.getInstance(HttpServer.class); - assertNotNull(server); + assertThat(server).isNotNull(); server.start(); try { HttpServerInfo httpServerInfo = injector.getInstance(HttpServerInfo.class); - assertNotNull(httpServerInfo); - assertNotNull(httpServerInfo.getHttpUri()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), "http"); - assertEquals(httpServerInfo.getHttpUri().getHost(), nodeInfo.getInternalAddress()); - assertNull(httpServerInfo.getHttpsUri()); + assertThat(httpServerInfo).isNotNull(); + assertThat(httpServerInfo.getHttpUri()).isNotNull(); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo("http"); + assertThat(httpServerInfo.getHttpUri().getHost()).isEqualTo(nodeInfo.getInternalAddress()); + assertThat(httpServerInfo.getHttpsUri()).isNull(); } catch (Exception e) { server.stop(); @@ -218,16 +215,16 @@ public void testServer(boolean enableLegacyUriCompliance) URI httpUri = httpServerInfo.getHttpUri(); StatusResponse response = client.execute(prepareGet().setUri(httpUri).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); // test filter bound correctly response = client.execute(prepareGet().setUri(httpUri.resolve("/filter")).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_PAYMENT_REQUIRED); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_PAYMENT_REQUIRED); if (enableLegacyUriCompliance) { // test legacy URI code for encoded slashes response = client.execute(prepareGet().setUri(httpUri.resolve("/slashtest/one/two%2fthree/four/%2f/five")).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); } // test http resources @@ -250,12 +247,12 @@ private void assertResource(URI baseUri, HttpClient client, String path, String { HttpUriBuilder uriBuilder = uriBuilderFrom(baseUri); StringResponse response = client.execute(prepareGet().setUri(uriBuilder.appendPath(path).build()).build(), createStringResponseHandler()); - assertEquals(response.getStatusCode(), HttpStatus.OK.code()); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK.code()); String contentType = response.getHeader(CONTENT_TYPE); - assertNotNull(contentType, CONTENT_TYPE + " header is absent"); + assertThat(contentType).as(CONTENT_TYPE + " header is absent").isNotNull(); MediaType mediaType = MediaType.parse(contentType); - assertTrue(PLAIN_TEXT_UTF_8.is(mediaType), "Expected text/plain but got " + mediaType); - assertEquals(response.getBody().trim(), contents); + assertThat(PLAIN_TEXT_UTF_8.is(mediaType)).as("Expected text/plain but got " + mediaType).isTrue(); + assertThat(response.getBody().trim()).isEqualTo(contents); } private void assertRedirect(URI baseUri, HttpClient client, String path, String redirect) @@ -267,10 +264,10 @@ private void assertRedirect(URI baseUri, HttpClient client, String path, String .setUri(uriBuilder.appendPath(path).build()) .build(), createStringResponseHandler()); - assertEquals(response.getStatusCode(), HttpStatus.TEMPORARY_REDIRECT.code()); - assertEquals(response.getHeader(LOCATION), redirect); - assertNull(response.getHeader(CONTENT_TYPE), CONTENT_TYPE + " header should be absent"); - assertEquals(response.getBody(), "", "Response body"); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.TEMPORARY_REDIRECT.code()); + assertThat(response.getHeader(LOCATION)).isEqualTo(redirect); + assertThat(response.getHeader(CONTENT_TYPE)).as(CONTENT_TYPE + " header should be absent").isNull(); + assertThat(response.getBody()).as("Response body").isEqualTo(""); } @Test @@ -335,9 +332,9 @@ public void testHttpRequestEvent() afterRequest = System.currentTimeMillis(); - assertEquals(response.getStatusCode(), responseCode); - assertEquals(response.getBody(), responseBody); - assertEquals(response.getHeader("Content-Type"), responseContentType); + assertThat(response.getStatusCode()).isEqualTo(responseCode); + assertThat(response.getBody()).isEqualTo(responseBody); + assertThat(response.getHeader("Content-Type")).isEqualTo(responseContentType); event = (HttpRequestEvent) eventClient.getEvent().get(10, TimeUnit.SECONDS); } @@ -345,25 +342,25 @@ public void testHttpRequestEvent() server.stop(); } - assertEquals(event.clientAddress(), echoServlet.remoteAddress); - assertEquals(event.protocol(), "http"); - assertEquals(event.method(), "POST"); - assertEquals(event.requestUri(), requestUri.getPath()); - assertNull(event.user()); - assertEquals(event.agent(), userAgent); - assertEquals(event.referrer(), referrer); - assertEquals(event.traceToken(), token); - - assertEquals(event.requestSize(), requestBody.length()); - assertEquals(event.requestContentType(), requestContentType); - assertEquals(event.responseSize(), responseBody.length()); - assertEquals(event.responseCode(), responseCode); - assertEquals(event.responseContentType(), responseContentType); - assertTrue(event.timeStamp().toEpochMilli() >= beforeRequest); - assertTrue(event.timeToLastByte() <= afterRequest - beforeRequest); - assertTrue(event.timeToFirstByte() <= event.timeToLastByte()); - assertTrue(event.timeToDispatch() <= event.timeToFirstByte()); - assertTrue(event.timeToFirstByte() <= event.timeToLastByte()); + assertThat(event.clientAddress()).isEqualTo(echoServlet.remoteAddress); + assertThat(event.protocol()).isEqualTo("http"); + assertThat(event.method()).isEqualTo("POST"); + assertThat(event.requestUri()).isEqualTo(requestUri.getPath()); + assertThat(event.user()).isNull(); + assertThat(event.agent()).isEqualTo(userAgent); + assertThat(event.referrer()).isEqualTo(referrer); + assertThat(event.traceToken()).isEqualTo(token); + + assertThat(event.requestSize()).isEqualTo(requestBody.length()); + assertThat(event.requestContentType()).isEqualTo(requestContentType); + assertThat(event.responseSize()).isEqualTo(responseBody.length()); + assertThat(event.responseCode()).isEqualTo(responseCode); + assertThat(event.responseContentType()).isEqualTo(responseContentType); + assertThat(event.timeStamp().toEpochMilli() >= beforeRequest).isTrue(); + assertThat(event.timeToLastByte() <= afterRequest - beforeRequest).isTrue(); + assertThat(event.timeToFirstByte() <= event.timeToLastByte()).isTrue(); + assertThat(event.timeToDispatch() <= event.timeToFirstByte()).isTrue(); + assertThat(event.timeToFirstByte() <= event.timeToLastByte()).isTrue(); } private static final class EchoServlet diff --git a/http-server/src/test/java/io/airlift/http/server/TestHttpServerProvider.java b/http-server/src/test/java/io/airlift/http/server/TestHttpServerProvider.java index c270cb4664a..f72c678dc1b 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestHttpServerProvider.java +++ b/http-server/src/test/java/io/airlift/http/server/TestHttpServerProvider.java @@ -95,10 +95,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; @Test(singleThreaded = true) public class TestHttpServerProvider @@ -146,22 +142,22 @@ public void teardown() @Test public void testConnectorDefaults() { - assertTrue(config.isHttpEnabled()); - assertNotNull(httpServerInfo.getHttpUri()); - assertNotNull(httpServerInfo.getHttpExternalUri()); - assertNotNull(httpServerInfo.getHttpChannel()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), httpServerInfo.getHttpExternalUri().getScheme()); - assertEquals(httpServerInfo.getHttpUri().getPort(), httpServerInfo.getHttpExternalUri().getPort()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), "http"); + assertThat(config.isHttpEnabled()).isTrue(); + assertThat(httpServerInfo.getHttpUri()).isNotNull(); + assertThat(httpServerInfo.getHttpExternalUri()).isNotNull(); + assertThat(httpServerInfo.getHttpChannel()).isNotNull(); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo(httpServerInfo.getHttpExternalUri().getScheme()); + assertThat(httpServerInfo.getHttpUri().getPort()).isEqualTo(httpServerInfo.getHttpExternalUri().getPort()); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo("http"); - assertFalse(config.isHttpsEnabled()); - assertNull(httpServerInfo.getHttpsUri()); - assertNull(httpServerInfo.getHttpsExternalUri()); - assertNull(httpServerInfo.getHttpsChannel()); + assertThat(config.isHttpsEnabled()).isFalse(); + assertThat(httpServerInfo.getHttpsUri()).isNull(); + assertThat(httpServerInfo.getHttpsExternalUri()).isNull(); + assertThat(httpServerInfo.getHttpsChannel()).isNull(); - assertNull(httpServerInfo.getAdminUri()); - assertNull(httpServerInfo.getAdminExternalUri()); - assertNull(httpServerInfo.getAdminChannel()); + assertThat(httpServerInfo.getAdminUri()).isNull(); + assertThat(httpServerInfo.getAdminExternalUri()).isNull(); + assertThat(httpServerInfo.getAdminChannel()).isNull(); } @Test @@ -170,17 +166,17 @@ public void testHttpDisabled() config.setHttpEnabled(false); httpServerInfo = createHttpServerInfo(); - assertNull(httpServerInfo.getHttpUri()); - assertNull(httpServerInfo.getHttpExternalUri()); - assertNull(httpServerInfo.getHttpChannel()); + assertThat(httpServerInfo.getHttpUri()).isNull(); + assertThat(httpServerInfo.getHttpExternalUri()).isNull(); + assertThat(httpServerInfo.getHttpChannel()).isNull(); - assertNull(httpServerInfo.getHttpsUri()); - assertNull(httpServerInfo.getHttpsExternalUri()); - assertNull(httpServerInfo.getHttpsChannel()); + assertThat(httpServerInfo.getHttpsUri()).isNull(); + assertThat(httpServerInfo.getHttpsExternalUri()).isNull(); + assertThat(httpServerInfo.getHttpsChannel()).isNull(); - assertNull(httpServerInfo.getAdminUri()); - assertNull(httpServerInfo.getAdminExternalUri()); - assertNull(httpServerInfo.getAdminChannel()); + assertThat(httpServerInfo.getAdminUri()).isNull(); + assertThat(httpServerInfo.getAdminExternalUri()).isNull(); + assertThat(httpServerInfo.getAdminChannel()).isNull(); } @Test @@ -189,23 +185,23 @@ public void testHttpsEnabled() config.setHttpsEnabled(true); httpServerInfo = createHttpServerInfo(); - assertNotNull(httpServerInfo.getHttpUri()); - assertNotNull(httpServerInfo.getHttpExternalUri()); - assertNotNull(httpServerInfo.getHttpChannel()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), httpServerInfo.getHttpExternalUri().getScheme()); - assertEquals(httpServerInfo.getHttpUri().getPort(), httpServerInfo.getHttpExternalUri().getPort()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), "http"); + assertThat(httpServerInfo.getHttpUri()).isNotNull(); + assertThat(httpServerInfo.getHttpExternalUri()).isNotNull(); + assertThat(httpServerInfo.getHttpChannel()).isNotNull(); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo(httpServerInfo.getHttpExternalUri().getScheme()); + assertThat(httpServerInfo.getHttpUri().getPort()).isEqualTo(httpServerInfo.getHttpExternalUri().getPort()); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo("http"); - assertNotNull(httpServerInfo.getHttpsUri()); - assertNotNull(httpServerInfo.getHttpsExternalUri()); - assertNotNull(httpServerInfo.getHttpsChannel()); - assertEquals(httpServerInfo.getHttpsUri().getScheme(), httpServerInfo.getHttpsExternalUri().getScheme()); - assertEquals(httpServerInfo.getHttpsUri().getPort(), httpServerInfo.getHttpsExternalUri().getPort()); - assertEquals(httpServerInfo.getHttpsUri().getScheme(), "https"); + assertThat(httpServerInfo.getHttpsUri()).isNotNull(); + assertThat(httpServerInfo.getHttpsExternalUri()).isNotNull(); + assertThat(httpServerInfo.getHttpsChannel()).isNotNull(); + assertThat(httpServerInfo.getHttpsUri().getScheme()).isEqualTo(httpServerInfo.getHttpsExternalUri().getScheme()); + assertThat(httpServerInfo.getHttpsUri().getPort()).isEqualTo(httpServerInfo.getHttpsExternalUri().getPort()); + assertThat(httpServerInfo.getHttpsUri().getScheme()).isEqualTo("https"); - assertNull(httpServerInfo.getAdminUri()); - assertNull(httpServerInfo.getAdminExternalUri()); - assertNull(httpServerInfo.getAdminChannel()); + assertThat(httpServerInfo.getAdminUri()).isNull(); + assertThat(httpServerInfo.getAdminExternalUri()).isNull(); + assertThat(httpServerInfo.getAdminChannel()).isNull(); assertNotEquals(httpServerInfo.getHttpUri().getPort(), httpServerInfo.getHttpsUri().getPort()); } @@ -216,23 +212,23 @@ public void testAdminEnabled() config.setAdminEnabled(true); httpServerInfo = createHttpServerInfo(); - assertNotNull(httpServerInfo.getHttpUri()); - assertNotNull(httpServerInfo.getHttpExternalUri()); - assertNotNull(httpServerInfo.getHttpChannel()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), httpServerInfo.getHttpExternalUri().getScheme()); - assertEquals(httpServerInfo.getHttpUri().getPort(), httpServerInfo.getHttpExternalUri().getPort()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), "http"); + assertThat(httpServerInfo.getHttpUri()).isNotNull(); + assertThat(httpServerInfo.getHttpExternalUri()).isNotNull(); + assertThat(httpServerInfo.getHttpChannel()).isNotNull(); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo(httpServerInfo.getHttpExternalUri().getScheme()); + assertThat(httpServerInfo.getHttpUri().getPort()).isEqualTo(httpServerInfo.getHttpExternalUri().getPort()); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo("http"); - assertNull(httpServerInfo.getHttpsUri()); - assertNull(httpServerInfo.getHttpsExternalUri()); - assertNull(httpServerInfo.getHttpsChannel()); + assertThat(httpServerInfo.getHttpsUri()).isNull(); + assertThat(httpServerInfo.getHttpsExternalUri()).isNull(); + assertThat(httpServerInfo.getHttpsChannel()).isNull(); - assertNotNull(httpServerInfo.getAdminUri()); - assertNotNull(httpServerInfo.getAdminExternalUri()); - assertNotNull(httpServerInfo.getAdminChannel()); - assertEquals(httpServerInfo.getAdminUri().getScheme(), httpServerInfo.getAdminExternalUri().getScheme()); - assertEquals(httpServerInfo.getAdminUri().getPort(), httpServerInfo.getAdminExternalUri().getPort()); - assertEquals(httpServerInfo.getAdminUri().getScheme(), "http"); + assertThat(httpServerInfo.getAdminUri()).isNotNull(); + assertThat(httpServerInfo.getAdminExternalUri()).isNotNull(); + assertThat(httpServerInfo.getAdminChannel()).isNotNull(); + assertThat(httpServerInfo.getAdminUri().getScheme()).isEqualTo(httpServerInfo.getAdminExternalUri().getScheme()); + assertThat(httpServerInfo.getAdminUri().getPort()).isEqualTo(httpServerInfo.getAdminExternalUri().getPort()); + assertThat(httpServerInfo.getAdminUri().getScheme()).isEqualTo("http"); assertNotEquals(httpServerInfo.getHttpUri().getPort(), httpServerInfo.getAdminUri().getPort()); } @@ -244,26 +240,26 @@ public void testHttpsAndAdminEnabled() .setAdminEnabled(true); httpServerInfo = createHttpServerInfo(); - assertNotNull(httpServerInfo.getHttpUri()); - assertNotNull(httpServerInfo.getHttpExternalUri()); - assertNotNull(httpServerInfo.getHttpChannel()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), httpServerInfo.getHttpExternalUri().getScheme()); - assertEquals(httpServerInfo.getHttpUri().getPort(), httpServerInfo.getHttpExternalUri().getPort()); - assertEquals(httpServerInfo.getHttpUri().getScheme(), "http"); - - assertNotNull(httpServerInfo.getHttpsUri()); - assertNotNull(httpServerInfo.getHttpsExternalUri()); - assertNotNull(httpServerInfo.getHttpsChannel()); - assertEquals(httpServerInfo.getHttpsUri().getScheme(), httpServerInfo.getHttpsExternalUri().getScheme()); - assertEquals(httpServerInfo.getHttpsUri().getPort(), httpServerInfo.getHttpsExternalUri().getPort()); - assertEquals(httpServerInfo.getHttpsUri().getScheme(), "https"); - - assertNotNull(httpServerInfo.getAdminUri()); - assertNotNull(httpServerInfo.getAdminExternalUri()); - assertNotNull(httpServerInfo.getAdminChannel()); - assertEquals(httpServerInfo.getAdminUri().getScheme(), httpServerInfo.getAdminExternalUri().getScheme()); - assertEquals(httpServerInfo.getAdminUri().getPort(), httpServerInfo.getAdminExternalUri().getPort()); - assertEquals(httpServerInfo.getAdminUri().getScheme(), "https"); + assertThat(httpServerInfo.getHttpUri()).isNotNull(); + assertThat(httpServerInfo.getHttpExternalUri()).isNotNull(); + assertThat(httpServerInfo.getHttpChannel()).isNotNull(); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo(httpServerInfo.getHttpExternalUri().getScheme()); + assertThat(httpServerInfo.getHttpUri().getPort()).isEqualTo(httpServerInfo.getHttpExternalUri().getPort()); + assertThat(httpServerInfo.getHttpUri().getScheme()).isEqualTo("http"); + + assertThat(httpServerInfo.getHttpsUri()).isNotNull(); + assertThat(httpServerInfo.getHttpsExternalUri()).isNotNull(); + assertThat(httpServerInfo.getHttpsChannel()).isNotNull(); + assertThat(httpServerInfo.getHttpsUri().getScheme()).isEqualTo(httpServerInfo.getHttpsExternalUri().getScheme()); + assertThat(httpServerInfo.getHttpsUri().getPort()).isEqualTo(httpServerInfo.getHttpsExternalUri().getPort()); + assertThat(httpServerInfo.getHttpsUri().getScheme()).isEqualTo("https"); + + assertThat(httpServerInfo.getAdminUri()).isNotNull(); + assertThat(httpServerInfo.getAdminExternalUri()).isNotNull(); + assertThat(httpServerInfo.getAdminChannel()).isNotNull(); + assertThat(httpServerInfo.getAdminUri().getScheme()).isEqualTo(httpServerInfo.getAdminExternalUri().getScheme()); + assertThat(httpServerInfo.getAdminUri().getPort()).isEqualTo(httpServerInfo.getAdminExternalUri().getPort()); + assertThat(httpServerInfo.getAdminUri().getScheme()).isEqualTo("https"); assertNotEquals(httpServerInfo.getHttpUri().getPort(), httpServerInfo.getHttpsUri().getPort()); assertNotEquals(httpServerInfo.getHttpUri().getPort(), httpServerInfo.getAdminUri().getPort()); @@ -279,15 +275,15 @@ public void testHttp() try (JettyHttpClient httpClient = new JettyHttpClient(new HttpClientConfig().setHttp2Enabled(false))) { StatusResponse response = httpClient.execute(prepareGet().setUri(httpServerInfo.getHttpUri()).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(response.getHeader("X-Protocol"), "HTTP/1.1"); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(response.getHeader("X-Protocol")).isEqualTo("HTTP/1.1"); } try (JettyHttpClient httpClient = new JettyHttpClient(new HttpClientConfig().setHttp2Enabled(true))) { StatusResponse response = httpClient.execute(prepareGet().setUri(httpServerInfo.getHttpUri()).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(response.getHeader("X-Protocol"), "HTTP/2.0"); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(response.getHeader("X-Protocol")).isEqualTo("HTTP/2.0"); } } @@ -323,8 +319,8 @@ private void verifyHttps(JettyHttpClient httpClient, String name) URI uri = URI.create(format("https://%s:%s", name, httpServerInfo.getHttpsUri().getPort())); StatusResponse response = httpClient.execute(prepareGet().setUri(uri).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(response.getHeader("X-Protocol"), "HTTP/1.1"); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(response.getHeader("X-Protocol")).isEqualTo("HTTP/1.1"); } @Test @@ -337,7 +333,7 @@ public void testFilter() try (JettyHttpClient client = new JettyHttpClient()) { StatusResponse response = client.execute(prepareGet().setUri(httpServerInfo.getHttpUri().resolve("/filter")).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_PAYMENT_REQUIRED); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_PAYMENT_REQUIRED); } } @@ -373,15 +369,15 @@ private void assertForward(ForwardedServlet servlet, Optional proto, Opt host.ifPresent(value -> builder.addHeader(X_FORWARDED_HOST, value)); remoteHost.ifPresent(value -> builder.addHeader(X_FORWARDED_FOR, value)); StringResponse response = client.execute(builder.build(), createStringResponseHandler()); - assertEquals(response.getStatusCode(), 200); + assertThat(response.getStatusCode()).isEqualTo(200); } proto.ifPresent(uriBuilder::scheme); host.map(HostAndPort::fromString).ifPresent(uriBuilder::hostAndPort); URI forwardedUri = uriBuilder.build(); - assertEquals(servlet.getRequestUrl(), forwardedUri.toString()); - assertEquals(servlet.getScheme(), forwardedUri.getScheme()); - assertEquals(servlet.getIsSecure(), (Boolean) forwardedUri.getScheme().equals("https")); + assertThat(servlet.getRequestUrl()).isEqualTo(forwardedUri.toString()); + assertThat(servlet.getScheme()).isEqualTo(forwardedUri.getScheme()); + assertThat(servlet.getIsSecure()).isEqualTo((Boolean) forwardedUri.getScheme().equals("https")); remoteHost.ifPresent(value -> assertEquals(servlet.getRemoteAddress(), value)); } @@ -406,8 +402,8 @@ public void testAuth() .build(), createStringResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(response.getBody(), "user"); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(response.getBody()).isEqualTo("user"); } } @@ -464,8 +460,8 @@ private void assertClientCertificateRequest(HttpClientConfig clientConfig, Strin URI uri = URI.create(format("https://%s:%s", name, httpServerInfo.getHttpsUri().getPort())); StringResponse response = httpClient.execute(prepareGet().setUri(uri).build(), createStringResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(response.getBody(), "CN=testing,OU=Client,O=Airlift,L=Palo Alto,ST=CA,C=US"); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(response.getBody()).isEqualTo("CN=testing,OU=Client,O=Airlift,L=Palo Alto,ST=CA,C=US"); } } @@ -500,7 +496,7 @@ public void testShowStackTraceEnabled() try (HttpClient client = new JettyHttpClient()) { StringResponse response = client.execute(prepareGet().setUri(httpServerInfo.getHttpUri()).build(), createStringResponseHandler()); - assertEquals(response.getStatusCode(), 500); + assertThat(response.getStatusCode()).isEqualTo(500); assertContains(response.getBody(), "ErrorServlet.java"); } } @@ -515,7 +511,7 @@ public void testShowStackTraceDisabled() try (HttpClient client = new JettyHttpClient()) { StringResponse response = client.execute(prepareGet().setUri(httpServerInfo.getHttpUri()).build(), createStringResponseHandler()); - assertEquals(response.getStatusCode(), 500); + assertThat(response.getStatusCode()).isEqualTo(500); assertThat(response.getBody()).doesNotContain("ErrorServlet.java"); } } @@ -610,7 +606,7 @@ public void testNoHttpsDaysUntilCertificateExpiration() createAndStartServer(); - assertNull(server.getDaysUntilCertificateExpiration()); + assertThat(server.getDaysUntilCertificateExpiration()).isNull(); } @Test diff --git a/http-server/src/test/java/io/airlift/http/server/TestInet4Network.java b/http-server/src/test/java/io/airlift/http/server/TestInet4Network.java index d49e84e60aa..bed59dd02c9 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestInet4Network.java +++ b/http-server/src/test/java/io/airlift/http/server/TestInet4Network.java @@ -23,9 +23,7 @@ import static io.airlift.testing.EquivalenceTester.comparisonTester; import static io.airlift.testing.EquivalenceTester.equivalenceTester; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestInet4Network { @@ -42,7 +40,7 @@ public void testFromCidrValid() private static void assertCidrValid(String cidr) { - assertEquals(Inet4Network.fromCidr(cidr).toString(), cidr); + assertThat(Inet4Network.fromCidr(cidr).toString()).isEqualTo(cidr); } @DataProvider(name = "invalidCidr") @@ -92,8 +90,8 @@ private static void assertStartingAndEndingAddress(String cidr, String endingAdd { String startingAddress = cidr.substring(0, cidr.indexOf('/')); Inet4Network network = Inet4Network.fromCidr(cidr); - assertEquals(network.getStartingAddress(), InetAddresses.forString(startingAddress)); - assertEquals(network.getEndingAddress(), InetAddresses.forString(endingAddress)); + assertThat(network.getStartingAddress()).isEqualTo(InetAddresses.forString(startingAddress)); + assertThat(network.getEndingAddress()).isEqualTo(InetAddresses.forString(endingAddress)); } @Test @@ -109,7 +107,7 @@ public void testAddressToLong() private static void assertAddressToLong(String address, long ip) { Inet4Address addr = (Inet4Address) InetAddresses.forString(address); - assertEquals(Inet4Network.addressToLong(addr), ip); + assertThat(Inet4Network.addressToLong(addr)).isEqualTo(ip); } @Test @@ -124,7 +122,7 @@ public void testFromAddress() private static void assertFromAddress(String address, String cidr, int bits) { Inet4Address addr = (Inet4Address) InetAddresses.forString(address); - assertEquals(Inet4Network.fromAddress(addr, bits), Inet4Network.fromCidr(cidr)); + assertThat(Inet4Network.fromAddress(addr, bits)).isEqualTo(Inet4Network.fromCidr(cidr)); } @Test @@ -144,35 +142,35 @@ public void testTruncatedFromAddress() private static void assertTruncatedFromAddress(String address, String cidr, int bits) { Inet4Address addr = (Inet4Address) InetAddresses.forString(address); - assertEquals(Inet4Network.truncatedFromAddress(addr, bits), Inet4Network.fromCidr(cidr)); + assertThat(Inet4Network.truncatedFromAddress(addr, bits)).isEqualTo(Inet4Network.fromCidr(cidr)); } @Test public void testGetBits() { - assertEquals(Inet4Network.fromCidr("8.0.0.0/8").getBits(), 8); - assertEquals(Inet4Network.fromCidr("8.0.0.0/24").getBits(), 24); - assertEquals(Inet4Network.fromCidr("8.0.0.0/32").getBits(), 32); + assertThat(Inet4Network.fromCidr("8.0.0.0/8").getBits()).isEqualTo(8); + assertThat(Inet4Network.fromCidr("8.0.0.0/24").getBits()).isEqualTo(24); + assertThat(Inet4Network.fromCidr("8.0.0.0/32").getBits()).isEqualTo(32); } @Test public void testContainsAddress() { - assertTrue(containsAddress("0.0.0.0/0", "0.0.0.0")); - assertTrue(containsAddress("0.0.0.0/0", "1.2.3.4")); - assertTrue(containsAddress("0.0.0.0/0", "255.255.255.255")); - assertTrue(containsAddress("8.8.8.0/24", "8.8.8.0")); - assertTrue(containsAddress("8.8.8.0/24", "8.8.8.8")); - assertTrue(containsAddress("8.8.8.0/24", "8.8.8.255")); - assertTrue(containsAddress("202.12.128.0/18", "202.12.128.0")); - assertTrue(containsAddress("202.12.128.0/18", "202.12.128.255")); - assertTrue(containsAddress("202.12.128.0/18", "202.12.157.123")); - assertTrue(containsAddress("202.12.128.0/18", "202.12.191.255")); - - assertFalse(containsAddress("8.8.8.0/24", "8.8.9.0")); - assertFalse(containsAddress("8.8.8.8/32", "8.8.8.9")); - assertFalse(containsAddress("202.12.128.0/18", "202.12.127.255")); - assertFalse(containsAddress("202.12.128.0/18", "202.12.192.0")); + assertThat(containsAddress("0.0.0.0/0", "0.0.0.0")).isTrue(); + assertThat(containsAddress("0.0.0.0/0", "1.2.3.4")).isTrue(); + assertThat(containsAddress("0.0.0.0/0", "255.255.255.255")).isTrue(); + assertThat(containsAddress("8.8.8.0/24", "8.8.8.0")).isTrue(); + assertThat(containsAddress("8.8.8.0/24", "8.8.8.8")).isTrue(); + assertThat(containsAddress("8.8.8.0/24", "8.8.8.255")).isTrue(); + assertThat(containsAddress("202.12.128.0/18", "202.12.128.0")).isTrue(); + assertThat(containsAddress("202.12.128.0/18", "202.12.128.255")).isTrue(); + assertThat(containsAddress("202.12.128.0/18", "202.12.157.123")).isTrue(); + assertThat(containsAddress("202.12.128.0/18", "202.12.191.255")).isTrue(); + + assertThat(containsAddress("8.8.8.0/24", "8.8.9.0")).isFalse(); + assertThat(containsAddress("8.8.8.8/32", "8.8.8.9")).isFalse(); + assertThat(containsAddress("202.12.128.0/18", "202.12.127.255")).isFalse(); + assertThat(containsAddress("202.12.128.0/18", "202.12.192.0")).isFalse(); } private static boolean containsAddress(String cidr, String address) diff --git a/http-server/src/test/java/io/airlift/http/server/TestInet4Networks.java b/http-server/src/test/java/io/airlift/http/server/TestInet4Networks.java index 4c44e2046ab..11432d3a3ae 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestInet4Networks.java +++ b/http-server/src/test/java/io/airlift/http/server/TestInet4Networks.java @@ -18,27 +18,26 @@ import org.testng.annotations.Test; import static io.airlift.http.server.Inet4Networks.isPrivateNetworkAddress; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestInet4Networks { @Test public void test() { - assertTrue(isPrivateNetworkAddress("127.0.0.1")); - assertTrue(isPrivateNetworkAddress("127.1.2.3")); - assertTrue(isPrivateNetworkAddress("169.254.0.1")); - assertTrue(isPrivateNetworkAddress("169.254.1.2")); - assertTrue(isPrivateNetworkAddress("192.168.0.1")); - assertTrue(isPrivateNetworkAddress("192.168.1.2")); - assertTrue(isPrivateNetworkAddress("172.16.0.1")); - assertTrue(isPrivateNetworkAddress("172.16.1.2")); - assertTrue(isPrivateNetworkAddress("172.16.1.2")); - assertTrue(isPrivateNetworkAddress("10.0.0.1")); - assertTrue(isPrivateNetworkAddress("10.1.2.3")); + assertThat(isPrivateNetworkAddress("127.0.0.1")).isTrue(); + assertThat(isPrivateNetworkAddress("127.1.2.3")).isTrue(); + assertThat(isPrivateNetworkAddress("169.254.0.1")).isTrue(); + assertThat(isPrivateNetworkAddress("169.254.1.2")).isTrue(); + assertThat(isPrivateNetworkAddress("192.168.0.1")).isTrue(); + assertThat(isPrivateNetworkAddress("192.168.1.2")).isTrue(); + assertThat(isPrivateNetworkAddress("172.16.0.1")).isTrue(); + assertThat(isPrivateNetworkAddress("172.16.1.2")).isTrue(); + assertThat(isPrivateNetworkAddress("172.16.1.2")).isTrue(); + assertThat(isPrivateNetworkAddress("10.0.0.1")).isTrue(); + assertThat(isPrivateNetworkAddress("10.1.2.3")).isTrue(); - assertFalse(isPrivateNetworkAddress("1.2.3.4")); - assertFalse(isPrivateNetworkAddress("172.33.0.0")); + assertThat(isPrivateNetworkAddress("1.2.3.4")).isFalse(); + assertThat(isPrivateNetworkAddress("172.33.0.0")).isFalse(); } } diff --git a/http-server/src/test/java/io/airlift/http/server/TestJettyMultipleCerts.java b/http-server/src/test/java/io/airlift/http/server/TestJettyMultipleCerts.java index 1c2029bd6fc..319b141c36d 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestJettyMultipleCerts.java +++ b/http-server/src/test/java/io/airlift/http/server/TestJettyMultipleCerts.java @@ -41,8 +41,8 @@ import static io.airlift.http.client.Request.Builder.prepareGet; import static io.airlift.http.client.StatusResponseHandler.createStatusResponseHandler; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; public class TestJettyMultipleCerts { @@ -154,7 +154,7 @@ private static void tryHost(JettyHttpClient client, HostAndPort address) .setUri(URI.create("https://" + address)) .build(), createStatusResponseHandler()); - assertEquals(statusResponse.getStatusCode(), 200); + assertThat(statusResponse.getStatusCode()).isEqualTo(200); } catch (Exception e) { throw new RuntimeException(address.getHost() + " " + e.getMessage(), e); diff --git a/http-server/src/test/java/io/airlift/http/server/TestRequestTimingEventHandler.java b/http-server/src/test/java/io/airlift/http/server/TestRequestTimingEventHandler.java index 330cc6d56d0..f833c019dbb 100644 --- a/http-server/src/test/java/io/airlift/http/server/TestRequestTimingEventHandler.java +++ b/http-server/src/test/java/io/airlift/http/server/TestRequestTimingEventHandler.java @@ -16,11 +16,11 @@ import static io.airlift.http.server.RequestTimingEventHandler.timings; import static java.time.temporal.ChronoUnit.MILLIS; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; -import static org.testng.Assert.assertEquals; public class TestRequestTimingEventHandler { @@ -48,12 +48,12 @@ public void testExtractTimings() RequestTiming timings = timings(request); - assertEquals(timings.requestStarted(), now.truncatedTo(MILLIS)); - assertEquals(timings.timeToDispatch(), Duration.valueOf("100.00ns")); - assertEquals(timings.timeToHandling(), Duration.valueOf("110.00ns")); - assertEquals(timings.timeToFirstByte(), Duration.valueOf("200.00ns")); - assertEquals(timings.timeToLastByte(), Duration.valueOf("250.00ns")); - assertEquals(timings.timeToCompletion(), Duration.valueOf("500.00ns")); + assertThat(timings.requestStarted()).isEqualTo(now.truncatedTo(MILLIS)); + assertThat(timings.timeToDispatch()).isEqualTo(Duration.valueOf("100.00ns")); + assertThat(timings.timeToHandling()).isEqualTo(Duration.valueOf("110.00ns")); + assertThat(timings.timeToFirstByte()).isEqualTo(Duration.valueOf("200.00ns")); + assertThat(timings.timeToLastByte()).isEqualTo(Duration.valueOf("250.00ns")); + assertThat(timings.timeToCompletion()).isEqualTo(Duration.valueOf("500.00ns")); } } } diff --git a/http-server/src/test/java/io/airlift/http/server/testing/AbstractTestTestingHttpServer.java b/http-server/src/test/java/io/airlift/http/server/testing/AbstractTestTestingHttpServer.java index 70aa1d15eca..60df3671887 100644 --- a/http-server/src/test/java/io/airlift/http/server/testing/AbstractTestTestingHttpServer.java +++ b/http-server/src/test/java/io/airlift/http/server/testing/AbstractTestTestingHttpServer.java @@ -71,8 +71,6 @@ import static io.airlift.testing.Assertions.assertGreaterThan; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; public abstract class AbstractTestTestingHttpServer { @@ -104,7 +102,7 @@ public void testInitialization() try { server.start(); - assertEquals(servlet.getSampleInitParam(), "the value"); + assertThat(servlet.getSampleInitParam()).isEqualTo("the value"); assertGreaterThan(server.getPort(), 0); } finally { @@ -126,8 +124,8 @@ public void testRequest() try (HttpClient client = new JettyHttpClient(new HttpClientConfig().setConnectTimeout(new Duration(1, SECONDS)))) { StatusResponse response = client.execute(prepareGet().setUri(server.getBaseUrl()).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(servlet.getCallCount(), 1); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(servlet.getCallCount()).isEqualTo(1); } } finally { @@ -150,9 +148,9 @@ public void testFilteredRequest() try (HttpClient client = new JettyHttpClient(new HttpClientConfig().setConnectTimeout(new Duration(1, SECONDS)))) { StatusResponse response = client.execute(prepareGet().setUri(server.getBaseUrl()).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(servlet.getCallCount(), 1); - assertEquals(filter.getCallCount(), 1); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(servlet.getCallCount()).isEqualTo(1); + assertThat(filter.getCallCount()).isEqualTo(1); } } finally { @@ -184,8 +182,8 @@ public void testGuiceInjectionWithoutFilters() try (HttpClient client = new JettyHttpClient(new HttpClientConfig().setConnectTimeout(new Duration(1, SECONDS)))) { StatusResponse response = client.execute(prepareGet().setUri(server.getBaseUrl()).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(servlet.getCallCount(), 1); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(servlet.getCallCount()).isEqualTo(1); } finally { lifeCycleManager.stop(); @@ -218,9 +216,9 @@ public void testGuiceInjectionWithFilters() try (HttpClient client = new JettyHttpClient(new HttpClientConfig().setConnectTimeout(new Duration(1, SECONDS)))) { StatusResponse response = client.execute(prepareGet().setUri(server.getBaseUrl()).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_OK); - assertEquals(servlet.getCallCount(), 1); - assertEquals(filter.getCallCount(), 1); + assertThat(response.getStatusCode()).isEqualTo(HttpServletResponse.SC_OK); + assertThat(servlet.getCallCount()).isEqualTo(1); + assertThat(filter.getCallCount()).isEqualTo(1); } finally { @@ -270,7 +268,7 @@ public void testGuiceInjectionWithResources() assertResource(uri, client, "path/user2.txt", "user2"); // verify that servlet did not receive resource requests - assertEquals(servlet.getCallCount(), 0); + assertThat(servlet.getCallCount()).isEqualTo(0); } finally { lifeCycleManager.stop(); @@ -307,10 +305,10 @@ public void testHeaderCaseSensitivity() contentTypeHeader = servlet.contentTypeHeader; } if (enableCaseSensitiveHeaderCache) { - assertEquals(contentTypeHeader, finalContentType); + assertThat(contentTypeHeader).isEqualTo(finalContentType); } else { - assertEquals(contentTypeHeader, contentType); + assertThat(contentTypeHeader).isEqualTo(contentType); } } finally { @@ -355,10 +353,10 @@ private static void assertResource(URI baseUri, HttpClient client, String path, { HttpUriBuilder uriBuilder = uriBuilderFrom(baseUri); StringResponseHandler.StringResponse data = client.execute(prepareGet().setUri(uriBuilder.appendPath(path).build()).build(), createStringResponseHandler()); - assertEquals(data.getStatusCode(), HttpStatus.OK.code()); + assertThat(data.getStatusCode()).isEqualTo(HttpStatus.OK.code()); MediaType contentType = MediaType.parse(data.getHeader(HttpHeaders.CONTENT_TYPE)); - assertTrue(PLAIN_TEXT_UTF_8.is(contentType), "Expected text/plain but got " + contentType); - assertEquals(data.getBody().trim(), contents); + assertThat(PLAIN_TEXT_UTF_8.is(contentType)).as("Expected text/plain but got " + contentType).isTrue(); + assertThat(data.getBody().trim()).isEqualTo(contents); } private static TestingHttpServer createTestingHttpServer(boolean enableVirtualThreads, boolean enableLegacyUriCompliance, boolean enableCaseSensitiveHeaderCache, DummyServlet servlet, Map params) diff --git a/jaxrs-testing/src/test/java/io/airlift/jaxrs/testing/TestJaxrsTestingHttpProcessor.java b/jaxrs-testing/src/test/java/io/airlift/jaxrs/testing/TestJaxrsTestingHttpProcessor.java index b46b1c26cbf..3eb4b3f5953 100644 --- a/jaxrs-testing/src/test/java/io/airlift/jaxrs/testing/TestJaxrsTestingHttpProcessor.java +++ b/jaxrs-testing/src/test/java/io/airlift/jaxrs/testing/TestJaxrsTestingHttpProcessor.java @@ -20,8 +20,7 @@ import static jakarta.ws.rs.core.HttpHeaders.CONTENT_TYPE; import static java.net.HttpURLConnection.HTTP_OK; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.fail; @Test public class TestJaxrsTestingHttpProcessor @@ -39,9 +38,9 @@ public void test() StringResponse response = HTTP_CLIENT.execute(request, createStringResponseHandler()); - assertEquals(response.getStatusCode(), HttpStatus.OK.code()); - assertEquals(response.getBody(), "Got xyz"); - assertEquals(response.getHeader("X-Test-Out"), "Got abc"); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK.code()); + assertThat(response.getBody()).isEqualTo("Got xyz"); + assertThat(response.getHeader("X-Test-Out")).isEqualTo("Got abc"); } @Test @@ -56,7 +55,7 @@ public void testException() fail("expected exception"); } catch (TestingException e) { - assertEquals(e.getMessage(), "testException"); + assertThat(e.getMessage()).isEqualTo("testException"); } } @@ -68,7 +67,7 @@ public void testUndefinedResource() .build(); StringResponse response = HTTP_CLIENT.execute(request, createStringResponseHandler()); - assertEquals(response.getStatusCode(), 404); + assertThat(response.getStatusCode()).isEqualTo(404); } @Test diff --git a/jaxrs/pom.xml b/jaxrs/pom.xml index 75a7f576fb1..78f88ab3842 100644 --- a/jaxrs/pom.xml +++ b/jaxrs/pom.xml @@ -174,6 +174,12 @@ test + + org.assertj + assertj-core + test + + org.testng testng diff --git a/jaxrs/src/test/java/io/airlift/jaxrs/TestJsonMapper.java b/jaxrs/src/test/java/io/airlift/jaxrs/TestJsonMapper.java index 587b9b1597c..fc2e0156dba 100644 --- a/jaxrs/src/test/java/io/airlift/jaxrs/TestJsonMapper.java +++ b/jaxrs/src/test/java/io/airlift/jaxrs/TestJsonMapper.java @@ -31,9 +31,8 @@ import java.util.zip.ZipException; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; public class TestJsonMapper { @@ -58,9 +57,9 @@ private static void assertRoundTrip(String value) MultivaluedMap headers = new GuavaMultivaluedMap<>(); jsonMapper.writeTo(value, String.class, null, null, null, headers, outputStream); - assertEquals(jsonCodec.fromJson(outputStream.toString(UTF_8)), value); + assertThat(jsonCodec.fromJson(outputStream.toString(UTF_8))).isEqualTo(value); - assertEquals(headers.getFirst(HttpHeaders.X_CONTENT_TYPE_OPTIONS), "nosniff"); + assertThat(headers.getFirst(HttpHeaders.X_CONTENT_TYPE_OPTIONS)).isEqualTo("nosniff"); } @Test @@ -95,7 +94,7 @@ public int read(byte[] b, int off, int len) fail("Should have thrown a JsonMapperParsingException"); } catch (JsonMapperParsingException e) { - assertTrue((e.getMessage()).startsWith("Invalid json for Java type")); + assertThat((e.getMessage()).startsWith("Invalid json for Java type")).isTrue(); } } @@ -131,7 +130,7 @@ public int read(byte[] b, int off, int len) fail("Should have thrown a JsonMapperParsingException"); } catch (JsonMapperParsingException e) { - assertTrue((e.getMessage()).startsWith("Invalid json for Java type")); + assertThat((e.getMessage()).startsWith("Invalid json for Java type")).isTrue(); } } @@ -167,7 +166,7 @@ public int read(byte[] b, int off, int len) fail("Should have thrown an IOException"); } catch (WebApplicationException e) { - fail("Should not have received a WebApplicationException", e); + org.assertj.core.api.Assertions.fail("Should not have received a WebApplicationException", e); } } diff --git a/jaxrs/src/test/java/io/airlift/jaxrs/programmatic/TestProgrammaticResource.java b/jaxrs/src/test/java/io/airlift/jaxrs/programmatic/TestProgrammaticResource.java index 71d62bfbe3a..4ce3825545c 100644 --- a/jaxrs/src/test/java/io/airlift/jaxrs/programmatic/TestProgrammaticResource.java +++ b/jaxrs/src/test/java/io/airlift/jaxrs/programmatic/TestProgrammaticResource.java @@ -30,7 +30,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList; import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestProgrammaticResource { @@ -57,9 +57,9 @@ public void testProgrammaticResourceBinding() .filter(r -> r.getPath().equals("/foo/bar")) .flatMap(r -> r.getAllMethods().stream()) .collect(toImmutableList()); - assertEquals(foundMethods.size(), 1); + assertThat(foundMethods.size()).isEqualTo(1); ResourceMethod foundMethod = foundMethods.get(0); - assertEquals(foundMethod.getInvocable().getHandlingMethod(), getResultMethod); - assertEquals(foundMethod.getInvocable().getHandler().getHandlerClass(), getClass()); + assertThat(foundMethod.getInvocable().getHandlingMethod()).isEqualTo(getResultMethod); + assertThat(foundMethod.getInvocable().getHandler().getHandlerClass()).isEqualTo(getClass()); } } diff --git a/jaxrs/src/test/java/io/airlift/jaxrs/testing/TestMockRequest.java b/jaxrs/src/test/java/io/airlift/jaxrs/testing/TestMockRequest.java index 681279e71bf..deda3e1268d 100644 --- a/jaxrs/src/test/java/io/airlift/jaxrs/testing/TestMockRequest.java +++ b/jaxrs/src/test/java/io/airlift/jaxrs/testing/TestMockRequest.java @@ -36,9 +36,7 @@ import static jakarta.ws.rs.core.MediaType.TEXT_PLAIN_TYPE; import static jakarta.ws.rs.core.MediaType.TEXT_XML_TYPE; import static java.util.Locale.US; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestMockRequest { @@ -69,13 +67,13 @@ private Object[][] getRequestBuilders() @Test(dataProvider = "requestBuilders") public void testMethod(ConditionalRequestBuilder request, String method, Variant variant) { - assertEquals(request.unconditionally().getMethod(), method); + assertThat(request.unconditionally().getMethod()).isEqualTo(method); } @Test(dataProvider = "requestBuilders") public void testSelectVariant(ConditionalRequestBuilder request, String method, Variant variant) { - assertEquals(request.unconditionally().selectVariant(VARIANTS), variant); + assertThat(request.unconditionally().selectVariant(VARIANTS)).isEqualTo(variant); } @Test(dataProvider = "requestBuilders") @@ -148,27 +146,27 @@ public void testIfUnmodifiedSince(ConditionalRequestBuilder requestBuilder, Stri private void assertPreconditionsMet(ResponseBuilder responseBuilder) { - assertNull(responseBuilder, "Expected null response builder"); + assertThat(responseBuilder).as("Expected null response builder").isNull(); } private void assertPreconditionsFailed(ResponseBuilder responseBuilder) { - assertNotNull(responseBuilder, "Expected a response builder"); + assertThat(responseBuilder).as("Expected a response builder").isNotNull(); Response response = responseBuilder.build(); - assertEquals(response.getStatus(), Status.PRECONDITION_FAILED.getStatusCode()); + assertThat(response.getStatus()).isEqualTo(Status.PRECONDITION_FAILED.getStatusCode()); } private void assertIfNoneMatchFailed(String method, ResponseBuilder responseBuilder) { - assertNotNull(responseBuilder, "Expected a response builder"); + assertThat(responseBuilder).as("Expected a response builder").isNotNull(); Response response = responseBuilder.build(); // not modified only applies to GET and HEAD; otherwise it is a precondition failed if ("GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method)) { - assertEquals(response.getStatus(), Status.NOT_MODIFIED.getStatusCode()); + assertThat(response.getStatus()).isEqualTo(Status.NOT_MODIFIED.getStatusCode()); } else { - assertEquals(response.getStatus(), Status.PRECONDITION_FAILED.getStatusCode()); + assertThat(response.getStatus()).isEqualTo(Status.PRECONDITION_FAILED.getStatusCode()); } } @@ -176,13 +174,13 @@ private void assertIfModifiedSinceFailed(String method, ResponseBuilder response { // if modified since only applies to GET and HEAD; otherwise it process request if (!("GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method))) { - assertNull(responseBuilder, "Did NOT expect a response builder"); + assertThat(responseBuilder).as("Did NOT expect a response builder").isNull(); } else { - assertNotNull(responseBuilder, "Expected a response builder"); + assertThat(responseBuilder).as("Expected a response builder").isNotNull(); Response response = responseBuilder.build(); - assertEquals(response.getStatus(), Status.NOT_MODIFIED.getStatusCode()); + assertThat(response.getStatus()).isEqualTo(Status.NOT_MODIFIED.getStatusCode()); } } } diff --git a/jmx-http-rpc/pom.xml b/jmx-http-rpc/pom.xml index 11fdd480c28..d59dfe4ccc4 100644 --- a/jmx-http-rpc/pom.xml +++ b/jmx-http-rpc/pom.xml @@ -75,6 +75,12 @@ test + + org.assertj + assertj-core + test + + org.testng testng diff --git a/jmx-http-rpc/src/test/java/io/airlift/jmx/http/rpc/TestMBeanServerResource.java b/jmx-http-rpc/src/test/java/io/airlift/jmx/http/rpc/TestMBeanServerResource.java index d4245f55ed3..d115d5f74d9 100644 --- a/jmx-http-rpc/src/test/java/io/airlift/jmx/http/rpc/TestMBeanServerResource.java +++ b/jmx-http-rpc/src/test/java/io/airlift/jmx/http/rpc/TestMBeanServerResource.java @@ -45,9 +45,8 @@ import java.lang.management.ManagementFactory; import java.util.UUID; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.weakref.jmx.ObjectNames.generatedNameOf; @Test(singleThreaded = true) @@ -105,95 +104,93 @@ public void teardown() public void testGetMBeanCount() throws Exception { - assertEquals(mbeanServerConnection.getMBeanCount(), platformMBeanServer.getMBeanCount()); + assertThat(mbeanServerConnection.getMBeanCount()).isEqualTo(platformMBeanServer.getMBeanCount()); } @Test public void testIsRegistered() throws Exception { - assertEquals(mbeanServerConnection.isRegistered(testMBeanName), true); - assertEquals(mbeanServerConnection.isRegistered(new ObjectName("fake", "fake", "fake")), false); + assertThat(mbeanServerConnection.isRegistered(testMBeanName)).isEqualTo(true); + assertThat(mbeanServerConnection.isRegistered(new ObjectName("fake", "fake", "fake"))).isEqualTo(false); } @Test public void testIsInstanceOf() throws Exception { - assertEquals(mbeanServerConnection.isInstanceOf(testMBeanName, TestMBean.class.getName()), true); - assertEquals(mbeanServerConnection.isInstanceOf(testMBeanName, Object.class.getName()), true); - assertEquals(mbeanServerConnection.isInstanceOf(testMBeanName, UUID.class.getName()), false); + assertThat(mbeanServerConnection.isInstanceOf(testMBeanName, TestMBean.class.getName())).isEqualTo(true); + assertThat(mbeanServerConnection.isInstanceOf(testMBeanName, Object.class.getName())).isEqualTo(true); + assertThat(mbeanServerConnection.isInstanceOf(testMBeanName, UUID.class.getName())).isEqualTo(false); } @Test public void testGetDefaultDomain() throws Exception { - assertEquals(mbeanServerConnection.getDefaultDomain(), platformMBeanServer.getDefaultDomain()); + assertThat(mbeanServerConnection.getDefaultDomain()).isEqualTo(platformMBeanServer.getDefaultDomain()); } @Test public void testGetDomains() throws Exception { - assertEquals(mbeanServerConnection.getDomains(), platformMBeanServer.getDomains()); + assertThat(mbeanServerConnection.getDomains()).isEqualTo(platformMBeanServer.getDomains()); } @Test public void testGetObjectInstance() throws Exception { - assertEquals(mbeanServerConnection.getObjectInstance(testMBeanName), platformMBeanServer.getObjectInstance(testMBeanName)); + assertThat(mbeanServerConnection.getObjectInstance(testMBeanName)).isEqualTo(platformMBeanServer.getObjectInstance(testMBeanName)); } @Test public void testGetMBeanInfo() throws Exception { - assertEquals(mbeanServerConnection.getMBeanInfo(testMBeanName), platformMBeanServer.getMBeanInfo(testMBeanName)); + assertThat(mbeanServerConnection.getMBeanInfo(testMBeanName)).isEqualTo(platformMBeanServer.getMBeanInfo(testMBeanName)); } @Test public void testGetQueryMBeanNames() throws Exception { - assertEquals(mbeanServerConnection.queryNames(testMBeanName, null), platformMBeanServer.queryNames(testMBeanName, null)); - assertEquals(mbeanServerConnection.queryNames(new ObjectName("*:*"), null), platformMBeanServer.queryNames(new ObjectName("*:*"), null)); + assertThat(mbeanServerConnection.queryNames(testMBeanName, null)).isEqualTo(platformMBeanServer.queryNames(testMBeanName, null)); + assertThat(mbeanServerConnection.queryNames(new ObjectName("*:*"), null)).isEqualTo(platformMBeanServer.queryNames(new ObjectName("*:*"), null)); } @Test public void testGetQueryMBeans() throws Exception { - assertEquals(mbeanServerConnection.queryMBeans(testMBeanName, null), platformMBeanServer.queryMBeans(testMBeanName, null)); - assertEquals(mbeanServerConnection.queryMBeans(new ObjectName("*:*"), null), platformMBeanServer.queryMBeans(new ObjectName("*:*"), null)); + assertThat(mbeanServerConnection.queryMBeans(testMBeanName, null)).isEqualTo(platformMBeanServer.queryMBeans(testMBeanName, null)); + assertThat(mbeanServerConnection.queryMBeans(new ObjectName("*:*"), null)).isEqualTo(platformMBeanServer.queryMBeans(new ObjectName("*:*"), null)); } @Test public void testGetAttribute() throws Exception { - assertEquals(mbeanServerConnection.getAttribute(testMBeanName, "Value"), null); + assertThat(mbeanServerConnection.getAttribute(testMBeanName, "Value")).isEqualTo(null); testMBean.setValue("FOO"); - assertEquals(mbeanServerConnection.getAttribute(testMBeanName, "Value"), "FOO"); + assertThat(mbeanServerConnection.getAttribute(testMBeanName, "Value")).isEqualTo("FOO"); - assertEquals(mbeanServerConnection.getAttribute(testMBeanName, "ObjectValue"), null); + assertThat(mbeanServerConnection.getAttribute(testMBeanName, "ObjectValue")).isEqualTo(null); testMBean.setObjectValue(UUID.randomUUID()); - assertEquals(mbeanServerConnection.getAttribute(testMBeanName, "ObjectValue"), testMBean.getObjectValue()); + assertThat(mbeanServerConnection.getAttribute(testMBeanName, "ObjectValue")).isEqualTo(testMBean.getObjectValue()); } @Test public void testGetAttributes() throws Exception { - assertEquals(mbeanServerConnection.getAttributes(testMBeanName, new String[] {"Value", "ObjectValue"}), - new AttributeList(ImmutableList.of(new Attribute("Value", null), new Attribute("ObjectValue", null)))); + assertThat(mbeanServerConnection.getAttributes(testMBeanName, new String[]{"Value", "ObjectValue"})).isEqualTo(new AttributeList(ImmutableList.of(new Attribute("Value", null), new Attribute("ObjectValue", null)))); testMBean.setValue("FOO"); testMBean.setObjectValue(UUID.randomUUID()); - assertEquals(mbeanServerConnection.getAttributes(testMBeanName, new String[] {"Value", "ObjectValue"}), - new AttributeList(ImmutableList.of(new Attribute("Value", "FOO"), new Attribute("ObjectValue", testMBean.getObjectValue())))); + assertThat(mbeanServerConnection.getAttributes(testMBeanName, new String[]{"Value", "ObjectValue"})).isEqualTo(new AttributeList(ImmutableList.of(new Attribute("Value", "FOO"), new Attribute("ObjectValue", testMBean.getObjectValue())))); } @Test @@ -201,15 +198,15 @@ public void testSetAttribute() throws Exception { mbeanServerConnection.setAttribute(testMBeanName, new Attribute("Value", "Foo")); - assertEquals(testMBean.getValue(), "Foo"); + assertThat(testMBean.getValue()).isEqualTo("Foo"); mbeanServerConnection.setAttribute(testMBeanName, new Attribute("Value", null)); - assertEquals(testMBean.getValue(), null); + assertThat(testMBean.getValue()).isEqualTo(null); UUID uuid = UUID.randomUUID(); mbeanServerConnection.setAttribute(testMBeanName, new Attribute("ObjectValue", uuid)); - assertEquals(testMBean.getObjectValue(), uuid); + assertThat(testMBean.getObjectValue()).isEqualTo(uuid); mbeanServerConnection.setAttribute(testMBeanName, new Attribute("ObjectValue", null)); - assertEquals(testMBean.getObjectValue(), null); + assertThat(testMBean.getObjectValue()).isEqualTo(null); } @Test @@ -218,24 +215,24 @@ public void testSetAttributes() { UUID uuid = UUID.randomUUID(); mbeanServerConnection.setAttributes(testMBeanName, new AttributeList(ImmutableList.of(new Attribute("Value", "Foo"), new Attribute("ObjectValue", uuid)))); - assertEquals(testMBean.getValue(), "Foo"); - assertEquals(testMBean.getObjectValue(), uuid); + assertThat(testMBean.getValue()).isEqualTo("Foo"); + assertThat(testMBean.getObjectValue()).isEqualTo(uuid); mbeanServerConnection.setAttributes(testMBeanName, new AttributeList(ImmutableList.of(new Attribute("Value", null), new Attribute("ObjectValue", null)))); - assertEquals(testMBean.getValue(), null); - assertEquals(testMBean.getObjectValue(), null); + assertThat(testMBean.getValue()).isEqualTo(null); + assertThat(testMBean.getObjectValue()).isEqualTo(null); } @Test public void testInvoke() throws Exception { - assertEquals(testMBean.noArgsMethodInvoked, false); + assertThat(testMBean.noArgsMethodInvoked).isEqualTo(false); mbeanServerConnection.invoke(testMBeanName, "noArgsMethod", null, null); - assertEquals(testMBean.noArgsMethodInvoked, true); + assertThat(testMBean.noArgsMethodInvoked).isEqualTo(true); UUID uuid = UUID.randomUUID(); - assertEquals(mbeanServerConnection.invoke(testMBeanName, "echo", new Object[] {uuid}, new String[] {Object.class.getName()}), uuid); + assertThat(mbeanServerConnection.invoke(testMBeanName, "echo", new Object[]{uuid}, new String[]{Object.class.getName()})).isEqualTo(uuid); } @Test @@ -247,8 +244,8 @@ public void testInvokeThrows() fail("Expected exception"); } catch (MBeanException e) { - assertTrue(e.getCause() instanceof Exception); - assertEquals(e.getCause().getMessage(), "exception-message"); + assertThat(e.getCause() instanceof Exception).isTrue(); + assertThat(e.getCause().getMessage()).isEqualTo("exception-message"); } } diff --git a/jmx-http/pom.xml b/jmx-http/pom.xml index 97c2391479a..4ee7d81b237 100644 --- a/jmx-http/pom.xml +++ b/jmx-http/pom.xml @@ -99,6 +99,12 @@ test + + org.assertj + assertj-core + test + + org.testng testng diff --git a/jmx-http/src/test/java/io/airlift/jmx/TestMBeanResource.java b/jmx-http/src/test/java/io/airlift/jmx/TestMBeanResource.java index 1c8ef59dca9..df0808ce36d 100644 --- a/jmx-http/src/test/java/io/airlift/jmx/TestMBeanResource.java +++ b/jmx-http/src/test/java/io/airlift/jmx/TestMBeanResource.java @@ -41,8 +41,7 @@ import static io.airlift.testing.Assertions.assertEqualsIgnoreOrder; import static java.lang.management.ManagementFactory.MEMORY_MXBEAN_NAME; import static java.lang.management.ManagementFactory.RUNTIME_MXBEAN_NAME; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestMBeanResource { @@ -99,7 +98,7 @@ public void testGetHtmlPage() prepareGet().setUri(uriFor("/v1/jmx")).build(), createStringResponseHandler()); - assertEquals(response.getStatusCode(), 200); + assertThat(response.getStatusCode()).isEqualTo(200); assertContentType(response, HTML_UTF_8); assertContains(response.getBody(), ""); } @@ -123,12 +122,12 @@ private void assertMBeansResponse(JsonNode mbeans) List names = new ArrayList<>(); for (JsonNode mbean : mbeans) { JsonNode name = mbean.get("objectName"); - assertTrue(name.isTextual()); + assertThat(name.isTextual()).isTrue(); names.add(name.asText()); } - assertTrue(names.contains(MEMORY_MXBEAN_NAME)); - assertTrue(names.contains(RUNTIME_MXBEAN_NAME)); + assertThat(names.contains(MEMORY_MXBEAN_NAME)).isTrue(); + assertThat(names.contains(RUNTIME_MXBEAN_NAME)).isTrue(); assertEqualsIgnoreOrder(names, getMBeanNames()); } @@ -142,8 +141,8 @@ public void testGetMBean(String mbeanName) JsonNode mbean = jsonRequest(uri); JsonNode name = mbean.get("objectName"); - assertTrue(name.isTextual()); - assertEquals(name.asText(), mbeanName); + assertThat(name.isTextual()).isTrue(); + assertThat(name.asText()).isEqualTo(mbeanName); } @Test(dataProvider = "mbeanNames") @@ -156,8 +155,8 @@ public void testGetMBeanJsonp(String mbeanName) JsonNode mbean = jsonpRequest(uri); JsonNode name = mbean.get("objectName"); - assertTrue(name.isTextual()); - assertEquals(name.asText(), mbeanName); + assertThat(name.isTextual()).isTrue(); + assertThat(name.asText()).isEqualTo(mbeanName); } private JsonNode jsonRequest(URI uri) @@ -166,7 +165,7 @@ private JsonNode jsonRequest(URI uri) Request request = prepareGet().setUri(uri).build(); StringResponse response = client.execute(request, createStringResponseHandler()); - assertEquals(response.getStatusCode(), 200, response.getBody()); + assertThat(response.getStatusCode()).as(response.getBody()).isEqualTo(200); assertContentType(response, JSON_UTF_8); return new ObjectMapperProvider().get().readTree(response.getBody()); @@ -181,12 +180,12 @@ private JsonNode jsonpRequest(URI uri) Request request = prepareGet().setUri(uri).build(); StringResponse response = client.execute(request, createStringResponseHandler()); - assertEquals(response.getStatusCode(), 200, response.getBody()); + assertThat(response.getStatusCode()).as(response.getBody()).isEqualTo(200); assertContentType(response, JSON_UTF_8); String jsonp = response.getBody().trim(); - assertTrue(jsonp.startsWith("test("), jsonp); - assertTrue(jsonp.endsWith(")"), jsonp); + assertThat(jsonp.startsWith("test(")).as(jsonp).isTrue(); + assertThat(jsonp.endsWith(")")).as(jsonp).isTrue(); jsonp = jsonp.substring(5, jsonp.length() - 1); return new ObjectMapperProvider().get().readTree(jsonp); @@ -209,6 +208,6 @@ private List getMBeanNames() private static void assertContentType(StringResponse response, MediaType type) { String contentType = response.getHeader(CONTENT_TYPE); - assertTrue(MediaType.parse(contentType).is(type.withoutParameters()), contentType); + assertThat(MediaType.parse(contentType).is(type.withoutParameters())).as(contentType).isTrue(); } } diff --git a/json/src/test/java/io/airlift/json/ImmutablePerson.java b/json/src/test/java/io/airlift/json/ImmutablePerson.java index b1ba0597560..73bd7b20b1d 100644 --- a/json/src/test/java/io/airlift/json/ImmutablePerson.java +++ b/json/src/test/java/io/airlift/json/ImmutablePerson.java @@ -25,7 +25,7 @@ import java.util.Objects; import static com.google.common.base.MoreObjects.toStringHelper; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class ImmutablePerson { @@ -38,10 +38,10 @@ public static void validatePersonJsonCodec(JsonCodec jsonCodec) ImmutablePerson expected = new ImmutablePerson("dain", true); String json = jsonCodec.toJson(expected); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); byte[] bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); } public static void validatePersonListJsonCodec(JsonCodec> jsonCodec) @@ -52,10 +52,10 @@ public static void validatePersonListJsonCodec(JsonCodec> new ImmutablePerson("mark", true)); String json = jsonCodec.toJson(expected); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); byte[] bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); } public static void validatePersonMapJsonCodec(JsonCodec> jsonCodec) @@ -67,10 +67,10 @@ public static void validatePersonMapJsonCodec(JsonCodec jsonCodec) Person expected = new Person().setName("dain").setRocks(true); String json = jsonCodec.toJson(expected); - assertFalse(json.contains("lastName")); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(json.contains("lastName")).isFalse(); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); byte[] bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); // create object with missing lastName expected.setLastName(Optional.empty()); json = jsonCodec.toJson(expected); - assertFalse(json.contains("lastName")); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(json.contains("lastName")).isFalse(); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); // create object with present lastName expected.setLastName(Optional.of("Awesome")); json = jsonCodec.toJson(expected); - assertTrue(json.contains("lastName")); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(json.contains("lastName")).isTrue(); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); } public static void validatePersonListJsonCodec(JsonCodec> jsonCodec) @@ -76,10 +74,10 @@ public static void validatePersonListJsonCodec(JsonCodec> jsonCodec new Person().setName("mark").setRocks(true)); String json = jsonCodec.toJson(expected); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); byte[] bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); } public static void validatePersonMapJsonCodec(JsonCodec> jsonCodec) @@ -91,10 +89,10 @@ public static void validatePersonMapJsonCodec(JsonCodec> jso .build(); String json = jsonCodec.toJson(expected); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); byte[] bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); } @JsonProperty diff --git a/json/src/test/java/io/airlift/json/TestJsonCodec.java b/json/src/test/java/io/airlift/json/TestJsonCodec.java index 59b98afc7e1..b15acd89fa0 100644 --- a/json/src/test/java/io/airlift/json/TestJsonCodec.java +++ b/json/src/test/java/io/airlift/json/TestJsonCodec.java @@ -32,11 +32,8 @@ import static io.airlift.json.JsonCodec.listJsonCodec; import static io.airlift.json.JsonCodec.mapJsonCodec; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; public class TestJsonCodec { @@ -97,7 +94,7 @@ public void testListNullValues() list.add(null); list.add("abc"); - assertEquals(jsonCodec.fromJson(jsonCodec.toJson(list)), list); + assertThat(jsonCodec.fromJson(jsonCodec.toJson(list))).isEqualTo(list); } @Test @@ -145,7 +142,7 @@ public void testMapNullValues() map.put("x", null); map.put("y", "abc"); - assertEquals(jsonCodec.fromJson(jsonCodec.toJson(map)), map); + assertThat(jsonCodec.fromJson(jsonCodec.toJson(map))).isEqualTo(map); } @Test @@ -161,7 +158,7 @@ public void testAsymmetricJsonCodec() { JsonCodec jsonCodec = jsonCodec(ImmutablePerson.class); ImmutablePerson immutablePerson = jsonCodec.fromJson("{ \"notWritable\": \"foo\" }"); - assertNull(immutablePerson.getNotWritable()); + assertThat(immutablePerson.getNotWritable()).isNull(); } @Test @@ -218,10 +215,10 @@ public void testToJsonWithLengthLimitSimple() JsonCodec jsonCodec = jsonCodec(ImmutablePerson.class); ImmutablePerson person = new ImmutablePerson(Strings.repeat("a", 1000), false); - assertFalse(jsonCodec.toJsonWithLengthLimit(person, 0).isPresent()); - assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1000).isPresent()); - assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1035).isPresent()); - assertTrue(jsonCodec.toJsonWithLengthLimit(person, 1036).isPresent()); + assertThat(jsonCodec.toJsonWithLengthLimit(person, 0).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(person, 1000).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(person, 1035).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(person, 1036).isPresent()).isTrue(); } @Test @@ -231,10 +228,10 @@ public void testToJsonExceedingDefaultStringLimit() ImmutablePerson person = new ImmutablePerson(Strings.repeat("a", DEFAULT_MAX_STRING_LEN + 1), false); String json = jsonCodec.toJson(person); - assertEquals(jsonCodec.fromJson(json), person); + assertThat(jsonCodec.fromJson(json)).isEqualTo(person); byte[] bytes = jsonCodec.toJsonBytes(person); - assertEquals(jsonCodec.fromJson(bytes), person); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(person); } @Test @@ -243,10 +240,10 @@ public void testToJsonWithLengthLimitNonAscii() JsonCodec jsonCodec = jsonCodec(ImmutablePerson.class); ImmutablePerson person = new ImmutablePerson(Strings.repeat("\u0158", 1000), false); - assertFalse(jsonCodec.toJsonWithLengthLimit(person, 0).isPresent()); - assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1000).isPresent()); - assertFalse(jsonCodec.toJsonWithLengthLimit(person, 1035).isPresent()); - assertTrue(jsonCodec.toJsonWithLengthLimit(person, 1036).isPresent()); + assertThat(jsonCodec.toJsonWithLengthLimit(person, 0).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(person, 1000).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(person, 1035).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(person, 1036).isPresent()).isTrue(); } @Test @@ -256,10 +253,10 @@ public void testToJsonWithLengthLimitComplex() ImmutablePerson person = new ImmutablePerson(Strings.repeat("a", 1000), false); List people = Collections.nCopies(10, person); - assertFalse(jsonCodec.toJsonWithLengthLimit(people, 0).isPresent()); - assertFalse(jsonCodec.toJsonWithLengthLimit(people, 5000).isPresent()); - assertFalse(jsonCodec.toJsonWithLengthLimit(people, 10381).isPresent()); - assertTrue(jsonCodec.toJsonWithLengthLimit(people, 10382).isPresent()); + assertThat(jsonCodec.toJsonWithLengthLimit(people, 0).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(people, 5000).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(people, 10381).isPresent()).isFalse(); + assertThat(jsonCodec.toJsonWithLengthLimit(people, 10382).isPresent()).isTrue(); } @Test @@ -268,7 +265,7 @@ public void testTrailingContent() JsonCodec codec = jsonCodec(ImmutablePerson.class); String json = "{\"name\":\"Me\",\"rocks\":true}"; - assertEquals(codec.fromJson(json).getName(), "Me"); + assertThat(codec.fromJson(json).getName()).isEqualTo("Me"); String jsonWithTrailingContent = json + " trailer"; assertThatThrownBy(() -> codec.fromJson(jsonWithTrailingContent)) @@ -324,9 +321,7 @@ public void testRecordSerialization() }\ """); - assertEquals( - JsonCodec.jsonCodec(LegacyRecordAdditionalGetter.class).toJson(new LegacyRecordAdditionalGetter("my value")), - """ + assertThat(JsonCodec.jsonCodec(LegacyRecordAdditionalGetter.class).toJson(new LegacyRecordAdditionalGetter("my value"))).isEqualTo(""" { "bar" : "there is no bar field in the record", "foo" : "not really a foo value", @@ -337,8 +332,8 @@ public void testRecordSerialization() private static void assertSerializationRoundTrip(JsonCodec codec, T object, String expected) { - assertEquals(codec.toJson(object), expected); - assertEquals(codec.fromJson(expected), object); + assertThat(codec.toJson(object)).isEqualTo(expected); + assertThat(codec.fromJson(expected)).isEqualTo(object); } public record MyRecord(String foo) {} diff --git a/json/src/test/java/io/airlift/json/TestJsonCodecBinder.java b/json/src/test/java/io/airlift/json/TestJsonCodecBinder.java index ca71d2e9b04..6ec2a35484c 100644 --- a/json/src/test/java/io/airlift/json/TestJsonCodecBinder.java +++ b/json/src/test/java/io/airlift/json/TestJsonCodecBinder.java @@ -23,7 +23,7 @@ import org.testng.annotations.Test; import static io.airlift.json.JsonCodecBinder.jsonCodecBinder; -import static org.testng.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestJsonCodecBinder { @@ -37,7 +37,7 @@ public void ignoresRepeatedBinding() binder.bind(Dummy.class).in(Scopes.SINGLETON); }); - assertNotNull(injector.getInstance(Dummy.class).getCodec()); + assertThat(injector.getInstance(Dummy.class).getCodec()).isNotNull(); } private static class Dummy diff --git a/json/src/test/java/io/airlift/json/TestJsonCodecFactory.java b/json/src/test/java/io/airlift/json/TestJsonCodecFactory.java index 3a328c60915..8ddc428e920 100644 --- a/json/src/test/java/io/airlift/json/TestJsonCodecFactory.java +++ b/json/src/test/java/io/airlift/json/TestJsonCodecFactory.java @@ -25,7 +25,7 @@ import java.util.Map; import static com.google.common.base.MoreObjects.toStringHelper; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestJsonCodecFactory { @@ -40,7 +40,7 @@ public void testJsonCodec() Person expected = new Person().setName("dain").setRocks(true); String json = jsonCodec.toJson(expected); Person actual = jsonCodec.fromJson(json); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } @Test @@ -79,7 +79,7 @@ private void validateListCodec(JsonCodec> jsonCodec) String json = jsonCodec.toJson(expected); List actual = jsonCodec.fromJson(json); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } @Test @@ -119,7 +119,7 @@ private void validateMapCodec(JsonCodec> jsonCodec) String json = jsonCodec.toJson(expected); Map actual = jsonCodec.fromJson(json); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } public static class Person diff --git a/json/src/test/java/io/airlift/json/TestJsonModule.java b/json/src/test/java/io/airlift/json/TestJsonModule.java index 2bb1c4d86de..796442b745e 100644 --- a/json/src/test/java/io/airlift/json/TestJsonModule.java +++ b/json/src/test/java/io/airlift/json/TestJsonModule.java @@ -45,8 +45,8 @@ import static com.google.common.base.MoreObjects.toStringHelper; import static io.airlift.json.JsonBinder.jsonBinder; import static java.util.Objects.requireNonNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.joda.time.DateTimeZone.UTC; -import static org.testng.Assert.assertEquals; public class TestJsonModule { @@ -88,10 +88,10 @@ public void testJsonCodecFactoryBinding() public void testSetup() throws Exception { - assertEquals(CAR, CAR); + assertThat(CAR).isEqualTo(CAR); String json = objectMapper.writeValueAsString(CAR); Car actual = objectMapper.readValue(json, Car.class); - assertEquals(actual, CAR); + assertThat(actual).isEqualTo(CAR); } @Test @@ -102,7 +102,7 @@ public void testFieldDetection() // notes is not annotated so should not be included // color is null so should not be included - assertEquals(actual.keySet(), ImmutableSet.of("make", "model", "year", "purchased", "nameList")); + assertThat(actual.keySet()).isEqualTo(ImmutableSet.of("make", "model", "year", "purchased", "nameList")); } @Test @@ -111,7 +111,7 @@ public void testDateTimeRendered() { Map actual = createCarMap(); - assertEquals(actual.get("purchased"), ISODateTimeFormat.dateTime().print(CAR.getPurchased())); + assertThat(actual.get("purchased")).isEqualTo(ISODateTimeFormat.dateTime().print(CAR.getPurchased())); } @Test @@ -123,7 +123,7 @@ public void testGuavaRoundTrip() String json = objectMapper.writeValueAsString(list); ImmutableList actual = objectMapper.readValue(json, new TypeReference>() {}); - assertEquals(actual, list); + assertThat(actual).isEqualTo(list); } @Test @@ -136,7 +136,7 @@ public void testIgnoreUnknownFields() data.put("unknown", "bogus"); // Jackson should deserialize the object correctly with the extra unknown data - assertEquals(objectMapper.readValue(objectMapper.writeValueAsString(data), Car.class), CAR); + assertThat(objectMapper.readValue(objectMapper.writeValueAsString(data), Car.class)).isEqualTo(CAR); } @Test @@ -145,8 +145,8 @@ public void testPropertyNamesFromParameterNames() { NoJsonPropertiesInJsonCreator value = new NoJsonPropertiesInJsonCreator("first value", "second value"); NoJsonPropertiesInJsonCreator mapped = objectMapper.readValue(objectMapper.writeValueAsString(value), NoJsonPropertiesInJsonCreator.class); - assertEquals(mapped.getFirst(), "first value"); - assertEquals(mapped.getSecond(), "second value"); + assertThat(mapped.getFirst()).isEqualTo("first value"); + assertThat(mapped.getSecond()).isEqualTo("second value"); } @Test @@ -155,7 +155,7 @@ public void testJsonValueAndStaticFactoryMethod() { JsonValueAndStaticFactoryMethod value = JsonValueAndStaticFactoryMethod.valueOf("some value"); JsonValueAndStaticFactoryMethod mapped = objectMapper.readValue(objectMapper.writeValueAsString(value), JsonValueAndStaticFactoryMethod.class); - assertEquals(mapped.getValue(), "some value"); + assertThat(mapped.getValue()).isEqualTo("some value"); } private Map createCarMap() diff --git a/json/src/test/java/io/airlift/json/Vehicle.java b/json/src/test/java/io/airlift/json/Vehicle.java index f0be7055dbf..631dbedf819 100644 --- a/json/src/test/java/io/airlift/json/Vehicle.java +++ b/json/src/test/java/io/airlift/json/Vehicle.java @@ -8,8 +8,7 @@ import java.util.List; import java.util.Map; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, @@ -25,20 +24,20 @@ static void validateVehicleJsonCodec(JsonCodec jsonCodec) Vehicle expected = new Car("bmw"); String json = jsonCodec.toJson(expected); - assertEquals(jsonCodec.fromJson(json), expected); - assertTrue(json.contains("\"@type\" : \"car\"")); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); + assertThat(json.contains("\"@type\" : \"car\"")).isTrue(); byte[] bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); expected = new Truck("volvo"); json = jsonCodec.toJson(expected); - assertEquals(jsonCodec.fromJson(json), expected); - assertTrue(json.contains("\"@type\" : \"truck\"")); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); + assertThat(json.contains("\"@type\" : \"truck\"")).isTrue(); bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); } static void validateVehicleListJsonCodec(JsonCodec> jsonCodec) @@ -48,10 +47,10 @@ static void validateVehicleListJsonCodec(JsonCodec> jsonCodec) new Truck("volvo")); String json = jsonCodec.toJson(expected); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); byte[] bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); } static void validateVehicleMapJsonCodec(JsonCodec> jsonCodec) @@ -62,9 +61,9 @@ static void validateVehicleMapJsonCodec(JsonCodec> jsonCode .build(); String json = jsonCodec.toJson(expected); - assertEquals(jsonCodec.fromJson(json), expected); + assertThat(jsonCodec.fromJson(json)).isEqualTo(expected); byte[] bytes = jsonCodec.toJsonBytes(expected); - assertEquals(jsonCodec.fromJson(bytes), expected); + assertThat(jsonCodec.fromJson(bytes)).isEqualTo(expected); } } diff --git a/json/src/test/java/io/airlift/json/isolated/TestJsonCodecBinder.java b/json/src/test/java/io/airlift/json/isolated/TestJsonCodecBinder.java index babe7951ba4..5da3a7a82a7 100644 --- a/json/src/test/java/io/airlift/json/isolated/TestJsonCodecBinder.java +++ b/json/src/test/java/io/airlift/json/isolated/TestJsonCodecBinder.java @@ -28,7 +28,7 @@ import java.util.Map; import static io.airlift.json.JsonCodecBinder.jsonCodecBinder; -import static org.testng.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestJsonCodecBinder { @@ -53,9 +53,9 @@ public void test() injector.injectMembers(this); - assertNotNull(personJsonCodec); - assertNotNull(personListJsonCodec); - assertNotNull(personMapJsonCodec); + assertThat(personJsonCodec).isNotNull(); + assertThat(personListJsonCodec).isNotNull(); + assertThat(personMapJsonCodec).isNotNull(); Person.validatePersonJsonCodec(personJsonCodec); Person.validatePersonListJsonCodec(personListJsonCodec); diff --git a/log-manager/src/test/java/io/airlift/log/TestJsonFormatter.java b/log-manager/src/test/java/io/airlift/log/TestJsonFormatter.java index aa078f31cf8..5e97b81a9bf 100644 --- a/log-manager/src/test/java/io/airlift/log/TestJsonFormatter.java +++ b/log-manager/src/test/java/io/airlift/log/TestJsonFormatter.java @@ -21,7 +21,6 @@ import static io.airlift.json.JsonCodec.mapJsonCodec; import static java.time.temporal.ChronoUnit.NANOS; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; public class TestJsonFormatter { @@ -44,18 +43,16 @@ public void testMinimalJsonErrorLogLine() assertThat(minimalJsonErrorLogLine).as("Log lines should end with newline").endsWith("\n"); - assertEquals( - jsonCodec(JsonRecord.class).fromJson(minimalJsonErrorLogLine), - new JsonRecord( - original.getTimestamp(), - Level.ERROR, - null, - null, - exception.getMessage(), - (Object[]) null, - null, - Context.root(), - ImmutableMap.of())); + assertThat(jsonCodec(JsonRecord.class).fromJson(minimalJsonErrorLogLine)).isEqualTo(new JsonRecord( + original.getTimestamp(), + Level.ERROR, + null, + null, + exception.getMessage(), + (Object[]) null, + null, + Context.root(), + ImmutableMap.of())); } @Test @@ -82,18 +79,16 @@ public void testRoundTrip() Context.root(), ImmutableMap.of()); - assertEquals( - jsonCodec(JsonRecord.class).fromJson(jsonCodec(JsonRecord.class).toJson(original)), - new JsonRecord( - original.getTimestamp(), - original.getLevel(), - original.getThread(), - original.getLoggerName(), - original.getMessage(), - List.of(), - null, - Context.root(), - ImmutableMap.of())); + assertThat(jsonCodec(JsonRecord.class).fromJson(jsonCodec(JsonRecord.class).toJson(original))).isEqualTo(new JsonRecord( + original.getTimestamp(), + original.getLevel(), + original.getThread(), + original.getLoggerName(), + original.getMessage(), + List.of(), + null, + Context.root(), + ImmutableMap.of())); } @Test @@ -111,16 +106,16 @@ public void testLogFormatting() assertThat(logMessage).as("Log lines should end with newline").endsWith("\n"); - assertEquals(jsonRecord.getTimestamp().truncatedTo(NANOS), record.getInstant().truncatedTo(NANOS), "Ensure timestamps between the original LogRecord and Json are equal to the nano"); + assertThat(jsonRecord.getTimestamp().truncatedTo(NANOS)).as("Ensure timestamps between the original LogRecord and Json are equal to the nano").isEqualTo(record.getInstant().truncatedTo(NANOS)); - assertEquals(jsonRecord.getThread(), Thread.currentThread().getName()); - assertEquals(jsonRecord.getLevel(), Level.fromJulLevel(record.getLevel())); - assertEquals(jsonRecord.getLoggerName(), record.getLoggerName()); - assertEquals(jsonRecord.getMessage(), record.getMessage()); + assertThat(jsonRecord.getThread()).isEqualTo(Thread.currentThread().getName()); + assertThat(jsonRecord.getLevel()).isEqualTo(Level.fromJulLevel(record.getLevel())); + assertThat(jsonRecord.getLoggerName()).isEqualTo(record.getLoggerName()); + assertThat(jsonRecord.getMessage()).isEqualTo(record.getMessage()); - assertEquals(jsonMap.get("throwableClass"), testException.getClass().getName()); - assertEquals(jsonMap.get("throwableMessage"), testException.getMessage()); - assertEquals(jsonMap.get("stackTrace"), getStackTraceAsString(testException)); + assertThat(jsonMap.get("throwableClass")).isEqualTo(testException.getClass().getName()); + assertThat(jsonMap.get("throwableMessage")).isEqualTo(testException.getMessage()); + assertThat(jsonMap.get("stackTrace")).isEqualTo(getStackTraceAsString(testException)); } @Test @@ -174,7 +169,7 @@ public void testLogAnnotations() Map jsonMap = mapJsonCodec(String.class, Object.class).fromJson(logMessage); JsonRecord jsonRecord = jsonCodec(JsonRecord.class).fromJson(logMessage); - assertEquals(jsonRecord.getMessage(), record.getMessage()); + assertThat(jsonRecord.getMessage()).isEqualTo(record.getMessage()); assertThat(jsonMap.get("annotations")).asInstanceOf(InstanceOfAssertFactories.map(String.class, String.class)).containsExactlyEntriesOf(logAnnotations); } } diff --git a/log-manager/src/test/java/io/airlift/log/TestLogFileName.java b/log-manager/src/test/java/io/airlift/log/TestLogFileName.java index beb51e5bafb..30446150d8a 100644 --- a/log-manager/src/test/java/io/airlift/log/TestLogFileName.java +++ b/log-manager/src/test/java/io/airlift/log/TestLogFileName.java @@ -25,9 +25,7 @@ import static com.google.common.collect.Comparators.isInOrder; import static com.google.common.collect.Comparators.isInStrictOrder; import static java.util.Comparator.naturalOrder; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestLogFileName { @@ -135,8 +133,8 @@ public void testGenerateNextLogFileName() { // note: no actual files are created here LogFileName logFileName = LogFileName.generateNextLogFileName(Paths.get(BASE_NAME), Optional.empty()); - assertEquals(logFileName.getIndex(), OptionalInt.of(0)); - assertEquals(logFileName.getLegacyIndex(), OptionalInt.empty()); + assertThat(logFileName.getIndex()).isEqualTo(OptionalInt.of(0)); + assertThat(logFileName.getLegacyIndex()).isEqualTo(OptionalInt.empty()); // verify the name round trips assertEqualOrdering(LogFileName.parseHistoryLogFileName(BASE_NAME, logFileName.getFileName()).orElseThrow(AssertionError::new), logFileName); @@ -151,22 +149,22 @@ private static void assertLogFile(String suffix, LocalDateTime dateTime, Optiona { Path path = Paths.get(BASE_NAME + "-" + suffix); Optional logFile = LogFileName.parseHistoryLogFileName(BASE_NAME, path.getFileName().toString()); - assertTrue(logFile.isPresent()); - assertEquals(logFile.get().getDateTime(), dateTime); - assertEquals(logFile.get().getIndex(), index); - assertEquals(logFile.get().getLegacyIndex(), legacyIndex); - assertEquals(logFile.get().getSlug(), Optional.empty()); - assertEquals(logFile.get().isCompressed(), compressed); + assertThat(logFile.isPresent()).isTrue(); + assertThat(logFile.get().getDateTime()).isEqualTo(dateTime); + assertThat(logFile.get().getIndex()).isEqualTo(index); + assertThat(logFile.get().getLegacyIndex()).isEqualTo(legacyIndex); + assertThat(logFile.get().getSlug()).isEqualTo(Optional.empty()); + assertThat(logFile.get().isCompressed()).isEqualTo(compressed); } private static void assertOrdering(LogFileName... logFileNames) { - assertTrue(isInStrictOrder(ImmutableList.copyOf(logFileNames), naturalOrder())); + assertThat(isInStrictOrder(ImmutableList.copyOf(logFileNames), naturalOrder())).isTrue(); } private static void assertEqualOrdering(LogFileName... logFileNames) { - assertTrue(isInOrder(ImmutableList.copyOf(logFileNames), naturalOrder())); - assertFalse(isInStrictOrder(ImmutableList.copyOf(logFileNames), naturalOrder())); + assertThat(isInOrder(ImmutableList.copyOf(logFileNames), naturalOrder())).isTrue(); + assertThat(isInStrictOrder(ImmutableList.copyOf(logFileNames), naturalOrder())).isFalse(); } } diff --git a/log-manager/src/test/java/io/airlift/log/TestLogHistoryManager.java b/log-manager/src/test/java/io/airlift/log/TestLogHistoryManager.java index db956360b24..87c56697dcb 100644 --- a/log-manager/src/test/java/io/airlift/log/TestLogHistoryManager.java +++ b/log-manager/src/test/java/io/airlift/log/TestLogHistoryManager.java @@ -29,7 +29,7 @@ import static io.airlift.units.DataSize.Unit.BYTE; import static io.airlift.units.DataSize.Unit.GIGABYTE; import static java.nio.file.StandardOpenOption.CREATE_NEW; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestLogHistoryManager { @@ -75,11 +75,11 @@ public void testInitialPrune() private static void assertLogFiles(LogHistoryManager logHistoryManager, List expected) { - assertEquals(logHistoryManager.getTotalSize(), expected.size() * FILE_SIZE); + assertThat(logHistoryManager.getTotalSize()).isEqualTo(expected.size() * FILE_SIZE); List files = logHistoryManager.getFiles().stream() .sorted() .collect(toImmutableList()); - assertEquals(files, expected); + assertThat(files).isEqualTo(expected); } @Test diff --git a/log-manager/src/test/java/io/airlift/log/TestLogging.java b/log-manager/src/test/java/io/airlift/log/TestLogging.java index c88fff5e59b..ab5e2624b61 100644 --- a/log-manager/src/test/java/io/airlift/log/TestLogging.java +++ b/log-manager/src/test/java/io/airlift/log/TestLogging.java @@ -26,8 +26,7 @@ import static com.google.common.io.MoreFiles.deleteRecursively; import static com.google.common.io.RecursiveDeleteOption.ALLOW_INSECURE; import static java.nio.file.Files.createTempDirectory; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public class TestLogging @@ -67,13 +66,13 @@ public void testRecoverTempFiles() Logging logging = Logging.initialize(); logging.configure(configuration); - assertTrue(logFile1.exists()); - assertTrue(logFile2.exists()); - assertFalse(tempLogFile1.exists()); - assertFalse(tempLogFile2.exists()); + assertThat(logFile1.exists()).isTrue(); + assertThat(logFile2.exists()).isTrue(); + assertThat(tempLogFile1.exists()).isFalse(); + assertThat(tempLogFile2.exists()).isFalse(); - assertTrue(new File(tempDir, "temp1.log").exists()); - assertTrue(new File(tempDir, "temp2.log").exists()); + assertThat(new File(tempDir, "temp1.log").exists()).isTrue(); + assertThat(new File(tempDir, "temp2.log").exists()).isTrue(); } @Test @@ -84,20 +83,20 @@ public void testPropagatesLevels() Logger logger = Logger.get("testPropagatesLevels"); logging.setLevel("testPropagatesLevels", Level.ERROR); - assertFalse(logger.isDebugEnabled()); - assertFalse(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); + assertThat(logger.isInfoEnabled()).isFalse(); logging.setLevel("testPropagatesLevels", Level.WARN); - assertFalse(logger.isDebugEnabled()); - assertFalse(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); + assertThat(logger.isInfoEnabled()).isFalse(); logging.setLevel("testPropagatesLevels", Level.INFO); - assertFalse(logger.isDebugEnabled()); - assertTrue(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); + assertThat(logger.isInfoEnabled()).isTrue(); logging.setLevel("testPropagatesLevels", Level.DEBUG); - assertTrue(logger.isDebugEnabled()); - assertTrue(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isTrue(); + assertThat(logger.isInfoEnabled()).isTrue(); } @Test @@ -108,20 +107,20 @@ public void testPropagatesLevelsHierarchical() Logger logger = Logger.get("testPropagatesLevelsHierarchical.child"); logging.setLevel("testPropagatesLevelsHierarchical", Level.ERROR); - assertFalse(logger.isDebugEnabled()); - assertFalse(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); + assertThat(logger.isInfoEnabled()).isFalse(); logging.setLevel("testPropagatesLevelsHierarchical", Level.WARN); - assertFalse(logger.isDebugEnabled()); - assertFalse(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); + assertThat(logger.isInfoEnabled()).isFalse(); logging.setLevel("testPropagatesLevelsHierarchical", Level.INFO); - assertFalse(logger.isDebugEnabled()); - assertTrue(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); + assertThat(logger.isInfoEnabled()).isTrue(); logging.setLevel("testPropagatesLevelsHierarchical", Level.DEBUG); - assertTrue(logger.isDebugEnabled()); - assertTrue(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isTrue(); + assertThat(logger.isInfoEnabled()).isTrue(); } @Test @@ -133,8 +132,8 @@ public void testChildLevelOverridesParent() logging.setLevel("testChildLevelOverridesParent", Level.DEBUG); logging.setLevel("testChildLevelOverridesParent.child", Level.ERROR); - assertFalse(logger.isDebugEnabled()); - assertFalse(logger.isInfoEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); + assertThat(logger.isInfoEnabled()).isFalse(); } @Test @@ -145,8 +144,8 @@ public void testClearLevel() Logger logger = Logger.get("testClearLevel"); logging.setLevel("testClearLevel", Level.DEBUG); - assertTrue(logger.isDebugEnabled()); + assertThat(logger.isDebugEnabled()).isTrue(); logging.clearLevel("testClearLevel"); - assertFalse(logger.isDebugEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); } } diff --git a/log-manager/src/test/java/io/airlift/log/TestLoggingMBean.java b/log-manager/src/test/java/io/airlift/log/TestLoggingMBean.java index 2b2f5d9d719..cdbd89bc112 100644 --- a/log-manager/src/test/java/io/airlift/log/TestLoggingMBean.java +++ b/log-manager/src/test/java/io/airlift/log/TestLoggingMBean.java @@ -19,10 +19,8 @@ import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; @Test(singleThreaded = true) public class TestLoggingMBean @@ -46,40 +44,40 @@ public void restoreRootLevel() @Test public void testGetAndSetRoot() { - assertEquals(logging.getRootLevel(), "INFO"); + assertThat(logging.getRootLevel()).isEqualTo("INFO"); logging.setRootLevel("WARN"); - assertEquals(logging.getRootLevel(), "WARN"); + assertThat(logging.getRootLevel()).isEqualTo("WARN"); logging.setRootLevel("INFO"); - assertEquals(logging.getRootLevel(), "INFO"); + assertThat(logging.getRootLevel()).isEqualTo("INFO"); } @Test public void testGetAndSetNonExisting() { - assertEquals(logging.getRootLevel(), "INFO"); + assertThat(logging.getRootLevel()).isEqualTo("INFO"); String name = "this.logger.does.not.exist.yet.Bogus"; - assertFalse(logging.getAllLevels().containsKey(name)); - assertEquals(logging.getLevel(name), "INFO"); + assertThat(logging.getAllLevels().containsKey(name)).isFalse(); + assertThat(logging.getLevel(name)).isEqualTo("INFO"); logging.setLevel(name, "WARN"); - assertEquals(logging.getLevel(name), "WARN"); - assertTrue(logging.getAllLevels().containsKey(name)); + assertThat(logging.getLevel(name)).isEqualTo("WARN"); + assertThat(logging.getAllLevels().containsKey(name)).isTrue(); - assertEquals(logging.getRootLevel(), "INFO"); + assertThat(logging.getRootLevel()).isEqualTo("INFO"); } @Test public void testSetInvalidLevel() { - assertEquals(logging.getRootLevel(), "INFO"); + assertThat(logging.getRootLevel()).isEqualTo("INFO"); try { logging.setRootLevel("FOO"); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } - assertEquals(logging.getRootLevel(), "INFO"); + assertThat(logging.getRootLevel()).isEqualTo("INFO"); } } diff --git a/log-manager/src/test/java/io/airlift/log/TestLoggingOutputStream.java b/log-manager/src/test/java/io/airlift/log/TestLoggingOutputStream.java index 6811675ba43..5e43bd9d267 100644 --- a/log-manager/src/test/java/io/airlift/log/TestLoggingOutputStream.java +++ b/log-manager/src/test/java/io/airlift/log/TestLoggingOutputStream.java @@ -23,10 +23,7 @@ import java.util.logging.Level; import java.util.logging.LogRecord; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestLoggingOutputStream { @@ -44,7 +41,7 @@ public void testStripTrailingNewline(String printed, String logged) stream.println(printed); assertLog(handler.takeRecord(), Level.INFO, logged); - assertTrue(handler.isEmpty()); + assertThat(handler.isEmpty()).isTrue(); } @DataProvider @@ -60,9 +57,9 @@ public static Object[][] testStripTrailingNewlineDataProvider() private void assertLog(LogRecord record, Level level, String message) { - assertEquals(record.getLevel(), level); - assertEquals(record.getMessage(), message); - assertNull(record.getThrown()); + assertThat(record.getLevel()).isEqualTo(level); + assertThat(record.getMessage()).isEqualTo(message); + assertThat(record.getThrown()).isNull(); } private static class MockHandler @@ -89,7 +86,7 @@ public void close() {} public LogRecord takeRecord() { - assertFalse(records.isEmpty(), "No messages logged"); + assertThat(records.isEmpty()).as("No messages logged").isFalse(); return records.remove(0); } diff --git a/log-manager/src/test/java/io/airlift/log/TestRollingFileMessageOutput.java b/log-manager/src/test/java/io/airlift/log/TestRollingFileMessageOutput.java index ec451ad1ebe..92850adc1b7 100644 --- a/log-manager/src/test/java/io/airlift/log/TestRollingFileMessageOutput.java +++ b/log-manager/src/test/java/io/airlift/log/TestRollingFileMessageOutput.java @@ -48,12 +48,8 @@ import static java.nio.file.StandardOpenOption.APPEND; import static java.nio.file.StandardOpenOption.CREATE; import static java.util.function.Predicate.not; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; @Test(timeOut = 5 * 60 * 1000) public class TestRollingFileMessageOutput @@ -71,32 +67,26 @@ public void testBasicLogging() BufferedHandler handler = createRollingFileHandler(masterFile.toString(), DataSize.of(1, MEGABYTE), DataSize.of(10, MEGABYTE), NONE, TEXT.createFormatter(TESTING_ANNOTATIONS), new ErrorManager()); assertLogDirectory(masterFile); - assertTrue(Files.exists(masterFile)); - assertTrue(Files.isSymbolicLink(masterFile)); + assertThat(Files.exists(masterFile)).isTrue(); + assertThat(Files.isSymbolicLink(masterFile)).isTrue(); handler.publish(new LogRecord(Level.SEVERE, "apple")); List lines = waitForExactLines(masterFile, 1); - assertEquals(lines.size(), 1); - assertEquals( - lines.stream() - .filter(line -> line.contains("environment=testing")) - .count(), - 1); - assertEquals( - lines.stream() - .filter(line -> line.contains("apple")) - .count(), - 1); + assertThat(lines.size()).isEqualTo(1); + assertThat(lines.stream() + .filter(line -> line.contains("environment=testing")) + .count()).isEqualTo(1); + assertThat(lines.stream() + .filter(line -> line.contains("apple")) + .count()).isEqualTo(1); handler.publish(new LogRecord(Level.SEVERE, "banana")); lines = waitForExactLines(masterFile, 2); - assertEquals(lines.size(), 2); - assertEquals( - Files.readAllLines(masterFile, UTF_8).stream() - .filter(line -> line.contains("banana")) - .count(), - 1); + assertThat(lines.size()).isEqualTo(2); + assertThat(Files.readAllLines(masterFile, UTF_8).stream() + .filter(line -> line.contains("banana")) + .count()).isEqualTo(1); assertLogDirectory(masterFile); handler.close(); @@ -120,13 +110,13 @@ public void testBrokenLink() BufferedHandler handler = createRollingFileHandler(masterFile.toString(), DataSize.of(1, MEGABYTE), DataSize.of(10, MEGABYTE), NONE, TEXT.createFormatter(TESTING_ANNOTATIONS), new ErrorManager()); assertLogDirectory(masterFile); - assertTrue(Files.exists(masterFile)); - assertTrue(Files.isSymbolicLink(masterFile)); + assertThat(Files.exists(masterFile)).isTrue(); + assertThat(Files.isSymbolicLink(masterFile)).isTrue(); handler.publish(new LogRecord(Level.SEVERE, "apple")); List lines = waitForExactLines(masterFile, 1); - assertEquals(lines.size(), 1); + assertThat(lines.size()).isEqualTo(1); assertLogDirectory(masterFile); handler.close(); @@ -272,8 +262,8 @@ public void testCompression() } int expectedCompressedSize = out.toByteArray().length; // to make testing easier, we assume that compressed file is greater than one message and less than 5 messages - assertTrue(expectedCompressedSize < message.length() * 5); - assertTrue(expectedCompressedSize > message.length()); + assertThat(expectedCompressedSize < message.length() * 5).isTrue(); + assertThat(expectedCompressedSize > message.length()).isTrue(); Path tempDir = Files.createTempDirectory("logging-test"); try { @@ -359,12 +349,10 @@ public void testClosedHandler() handler.publish(new LogRecord(Level.SEVERE, "cherry")); List lines = waitForExactLines(masterFile, 2); - assertEquals(lines.size(), 2); - assertEquals( - Files.readAllLines(masterFile, UTF_8).stream() - .filter(line -> line.contains("apple") || line.contains("banana")) - .count(), - 2); + assertThat(lines.size()).isEqualTo(2); + assertThat(Files.readAllLines(masterFile, UTF_8).stream() + .filter(line -> line.contains("apple") || line.contains("banana")) + .count()).isEqualTo(2); // these should not throw handler.flush(); @@ -390,12 +378,10 @@ public void testLoggingInExistingDirectory() handler.publish(new LogRecord(Level.SEVERE, "banana")); List lines = waitForExactLines(masterFile, 2); - assertEquals(lines.size(), 2); - assertEquals( - Files.readAllLines(masterFile, UTF_8).stream() - .filter(line -> line.contains("apple") || line.contains("banana")) - .count(), - 2); + assertThat(lines.size()).isEqualTo(2); + assertThat(Files.readAllLines(masterFile, UTF_8).stream() + .filter(line -> line.contains("apple") || line.contains("banana")) + .count()).isEqualTo(2); assertLogDirectory(masterFile); handler.close(); @@ -405,17 +391,15 @@ public void testLoggingInExistingDirectory() handler = createRollingFileHandler(masterFile.toString(), DataSize.of(1, MEGABYTE), DataSize.of(10, MEGABYTE), NONE, TEXT.createFormatter(TESTING_ANNOTATIONS), new ErrorManager()); assertLogDirectory(masterFile); - assertNotEquals(Files.readSymbolicLink(masterFile), firstLogFile); + assertThat(Files.readSymbolicLink(masterFile)).isNotEqualTo(firstLogFile); handler.publish(new LogRecord(Level.SEVERE, "cherry")); lines = waitForExactLines(masterFile, 1); - assertEquals(lines.size(), 1); - assertEquals( - lines.stream() - .filter(line -> line.contains("cherry")) - .count(), - 1); + assertThat(lines.size()).isEqualTo(1); + assertThat(lines.stream() + .filter(line -> line.contains("cherry")) + .count()).isEqualTo(1); assertLogDirectory(masterFile); handler.close(); @@ -440,34 +424,30 @@ public void testLoggingInExistingLegacyDirectory() Files.writeString(masterFile, new StaticFormatter().formatMessage(new LogRecord(Level.SEVERE, "apple")), CREATE, APPEND); Files.writeString(masterFile, new StaticFormatter().formatMessage(new LogRecord(Level.SEVERE, "banana")), CREATE, APPEND); - assertTrue(Files.isRegularFile(masterFile)); + assertThat(Files.isRegularFile(masterFile)).isTrue(); List lines = waitForExactLines(masterFile, 2); - assertEquals(lines.size(), 2); - assertEquals( - Files.readAllLines(masterFile, UTF_8).stream() - .filter(line -> line.contains("apple") || line.contains("banana")) - .count(), - 2); + assertThat(lines.size()).isEqualTo(2); + assertThat(Files.readAllLines(masterFile, UTF_8).stream() + .filter(line -> line.contains("apple") || line.contains("banana")) + .count()).isEqualTo(2); // open new handler BufferedHandler newHandler = createRollingFileHandler(masterFile.toString(), DataSize.of(1, MEGABYTE), DataSize.of(10, MEGABYTE), NONE, TEXT.createFormatter(TESTING_ANNOTATIONS), new ErrorManager()); assertLogDirectory(masterFile); - assertTrue(Files.isSymbolicLink(masterFile)); + assertThat(Files.isSymbolicLink(masterFile)).isTrue(); // should be tracking legacy file and new file - assertEquals(((RollingFileMessageOutput) newHandler.getMessageOutput()).getFiles().size(), 2); + assertThat(((RollingFileMessageOutput) newHandler.getMessageOutput()).getFiles().size()).isEqualTo(2); newHandler.publish(new LogRecord(Level.SEVERE, "cherry")); newHandler.publish(new LogRecord(Level.SEVERE, "date")); lines = waitForExactLines(masterFile, 2); - assertEquals(lines.size(), 2); - assertEquals( - lines.stream() - .filter(line -> line.contains("cherry") || line.contains("date")) - .count(), - 2); + assertThat(lines.size()).isEqualTo(2); + assertThat(lines.stream() + .filter(line -> line.contains("cherry") || line.contains("date")) + .count()).isEqualTo(2); assertLogDirectory(masterFile); newHandler.close(); @@ -513,21 +493,21 @@ private static BufferedHandler createRollingFileHandler( private static void assertLogDirectory(Path masterFile) throws Exception { - assertTrue(Files.isDirectory(masterFile.getParent())); - assertTrue(Files.isSymbolicLink(masterFile)); + assertThat(Files.isDirectory(masterFile.getParent())).isTrue(); + assertThat(Files.isSymbolicLink(masterFile)).isTrue(); Path symbolicLinkTarget = Files.readSymbolicLink(masterFile); - assertFalse(symbolicLinkTarget.isAbsolute()); - assertEquals(symbolicLinkTarget.getNameCount(), 1); - assertNull(symbolicLinkTarget.getParent()); + assertThat(symbolicLinkTarget.isAbsolute()).isFalse(); + assertThat(symbolicLinkTarget.getNameCount()).isEqualTo(1); + assertThat(symbolicLinkTarget.getParent()).isNull(); List logFiles = Files.list(masterFile.getParent()) .filter(not(masterFile::equals)) .collect(toImmutableList()); for (Path logFile : logFiles) { - assertFalse(Files.isSymbolicLink(logFile)); - assertTrue(Files.isRegularFile(logFile)); - assertTrue(parseHistoryLogFileName(masterFile.getFileName().toString(), logFile.getFileName().toString()).isPresent()); + assertThat(Files.isSymbolicLink(logFile)).isFalse(); + assertThat(Files.isRegularFile(logFile)).isTrue(); + assertThat(parseHistoryLogFileName(masterFile.getFileName().toString(), logFile.getFileName().toString()).isPresent()).isTrue(); } } @@ -535,18 +515,18 @@ private static void assertCompression(Path masterFile, BufferedHandler handler, throws Exception { Set compressedFileNames = waitForCompression((RollingFileMessageOutput) handler.getMessageOutput(), expectedFileCount); - assertEquals(compressedFileNames.size(), expectedFileCount - 1); + assertThat(compressedFileNames.size()).isEqualTo(expectedFileCount - 1); for (LogFileName compressedFileName : compressedFileNames) { Path compressedFile = masterFile.resolveSibling(compressedFileName.getFileName()); - assertEquals(Files.size(compressedFile), expectedCompressedSize); + assertThat(Files.size(compressedFile)).isEqualTo(expectedCompressedSize); List lines = new GzippedByteSource(asByteSource(compressedFile)) .asCharSource(UTF_8) .readLines(); - assertEquals(lines.size(), expectedLineCount); - assertTrue(lines.stream().allMatch(message.trim()::equals)); + assertThat(lines.size()).isEqualTo(expectedLineCount); + assertThat(lines.stream().allMatch(message.trim()::equals)).isTrue(); } } @@ -554,11 +534,11 @@ private static void assertLogSizes(Path masterFile, BufferedHandler handler, int throws Exception { Set files = waitForExactFiles((RollingFileMessageOutput) handler.getMessageOutput(), expectedFileCount); - assertEquals(files.size(), expectedFileCount); + assertThat(files.size()).isEqualTo(expectedFileCount); List lines = waitForExactLines(masterFile, expectedLines); - assertEquals(lines.size(), expectedLines); - assertEquals(Files.size(masterFile), (expectedLines) * lineSize); + assertThat(lines.size()).isEqualTo(expectedLines); + assertThat(Files.size(masterFile)).isEqualTo((expectedLines) * lineSize); } private static List waitForExactLines(Path masterFile, int exactCount) diff --git a/log-manager/src/test/java/io/airlift/log/TestSocketHandler.java b/log-manager/src/test/java/io/airlift/log/TestSocketHandler.java index d1265a11c59..0a29b024f81 100644 --- a/log-manager/src/test/java/io/airlift/log/TestSocketHandler.java +++ b/log-manager/src/test/java/io/airlift/log/TestSocketHandler.java @@ -20,8 +20,7 @@ import java.util.logging.LogRecord; import static io.airlift.log.Format.TEXT; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @Test(timeOut = 5 * 60 * 1000) public class TestSocketHandler @@ -49,8 +48,8 @@ public void testSocketLogging() String[] lines = received.split("\n"); for (int i = 0; i < lines.length; i++) { String[] parts = lines[i].split("\t"); - assertEquals(parts[1], io.airlift.log.Level.fromJulLevel(levels[i]).toString()); - assertEquals(parts[4], data[i]); + assertThat(parts[1]).isEqualTo(io.airlift.log.Level.fromJulLevel(levels[i]).toString()); + assertThat(parts[4]).isEqualTo(data[i]); } } } @@ -69,7 +68,7 @@ public void testBadListeningSocket() handler.flush(); handler.close(); - assertTrue(((SocketMessageOutput) handler.getMessageOutput()).getFailedConnections() > 0); + assertThat(((SocketMessageOutput) handler.getMessageOutput()).getFailedConnections() > 0).isTrue(); } private static BufferedHandler createSocketHandler(HostAndPort hostAndPort, Formatter formatter, ErrorManager errorManager) diff --git a/log/pom.xml b/log/pom.xml index 7889060a878..67341954912 100644 --- a/log/pom.xml +++ b/log/pom.xml @@ -29,6 +29,12 @@ test + + org.assertj + assertj-core + test + + org.testng testng diff --git a/log/src/test/java/io/airlift/log/TestLogger.java b/log/src/test/java/io/airlift/log/TestLogger.java index 9a87b5d40c3..e9a8f03c5bf 100644 --- a/log/src/test/java/io/airlift/log/TestLogger.java +++ b/log/src/test/java/io/airlift/log/TestLogger.java @@ -26,10 +26,7 @@ import java.util.logging.Level; import java.util.logging.LogRecord; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public class TestLogger @@ -55,23 +52,23 @@ public void setUp() @AfterMethod(alwaysRun = true) public void teardown() { - assertTrue(handler.isEmpty(), "Some log messages were not verified by test"); + assertThat(handler.isEmpty()).as("Some log messages were not verified by test").isTrue(); } @Test public void testIsDebugEnabled() { inner.setLevel(Level.FINE); - assertTrue(logger.isDebugEnabled()); + assertThat(logger.isDebugEnabled()).isTrue(); inner.setLevel(Level.INFO); - assertFalse(logger.isDebugEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); inner.setLevel(Level.WARNING); - assertFalse(logger.isDebugEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); inner.setLevel(Level.SEVERE); - assertFalse(logger.isDebugEnabled()); + assertThat(logger.isDebugEnabled()).isFalse(); } @Test @@ -134,7 +131,7 @@ public void testDebugShortCircuit() { inner.setLevel(Level.OFF); logger.debug("hello"); - assertTrue(handler.isEmpty()); + assertThat(handler.isEmpty()).isTrue(); } @Test @@ -142,7 +139,7 @@ public void testInfoShortCircuit() { inner.setLevel(Level.OFF); logger.info("hello"); - assertTrue(handler.isEmpty()); + assertThat(handler.isEmpty()).isTrue(); } @Test @@ -150,7 +147,7 @@ public void testWarnShortCircuit() { inner.setLevel(Level.OFF); logger.warn("hello"); - assertTrue(handler.isEmpty()); + assertThat(handler.isEmpty()).isTrue(); } @Test @@ -162,7 +159,7 @@ public void testWarnWithThrowableShortCircuit() Throwable e = new Throwable(); logger.warn(e, "hello"); - assertTrue(handler.isEmpty()); + assertThat(handler.isEmpty()).isTrue(); } @Test @@ -170,7 +167,7 @@ public void testErrorShortCircuit() { inner.setLevel(Level.OFF); logger.error("hello"); - assertTrue(handler.isEmpty()); + assertThat(handler.isEmpty()).isTrue(); } @Test @@ -182,7 +179,7 @@ public void testErrorWithThrowableShortCircuit() Throwable e = new Throwable(); logger.error(e, "hello"); - assertTrue(handler.isEmpty()); + assertThat(handler.isEmpty()).isTrue(); } @Test @@ -194,7 +191,7 @@ public void testErrorWithThrowableNoMessageShortCircuit() Throwable e = new Throwable(); logger.error(e); - assertTrue(handler.isEmpty()); + assertThat(handler.isEmpty()).isTrue(); } @Test @@ -268,25 +265,25 @@ public void testInsufficientArgsLogsOriginalExceptionForError() private void assertLog(Level level, String message, Throwable exception) { LogRecord record = handler.takeRecord(); - assertEquals(record.getLevel(), level); - assertEquals(record.getMessage(), message); - assertEquals(record.getThrown(), exception); + assertThat(record.getLevel()).isEqualTo(level); + assertThat(record.getMessage()).isEqualTo(message); + assertThat(record.getThrown()).isEqualTo(exception); } private void assertLog(Level level, String message) { LogRecord record = handler.takeRecord(); - assertEquals(record.getLevel(), level); - assertEquals(record.getMessage(), message); - assertNull(record.getThrown()); + assertThat(record.getLevel()).isEqualTo(level); + assertThat(record.getMessage()).isEqualTo(message); + assertThat(record.getThrown()).isNull(); } private void assertLogLike(Level level, List substrings, Class exceptionClass) { LogRecord record = handler.takeRecord(); - assertEquals(record.getLevel(), level); - assertTrue(stringContains(record.getMessage(), substrings)); - assertTrue(exceptionClass.isAssignableFrom(record.getThrown().getClass())); + assertThat(record.getLevel()).isEqualTo(level); + assertThat(stringContains(record.getMessage(), substrings)).isTrue(); + assertThat(exceptionClass.isAssignableFrom(record.getThrown().getClass())).isTrue(); } private boolean stringContains(String value, List substrings) @@ -329,7 +326,7 @@ public void close() public LogRecord takeRecord() { - assertTrue(!records.isEmpty(), "No messages logged"); + assertThat(!records.isEmpty()).as("No messages logged").isTrue(); return records.remove(0); } diff --git a/node/pom.xml b/node/pom.xml index b598a7d83df..316322fa687 100644 --- a/node/pom.xml +++ b/node/pom.xml @@ -48,6 +48,12 @@ test + + org.assertj + assertj-core + test + + org.testng testng diff --git a/node/src/test/java/io/airlift/node/TestAddressSource.java b/node/src/test/java/io/airlift/node/TestAddressSource.java index fb0543a9b4f..5b1d6f22f6e 100644 --- a/node/src/test/java/io/airlift/node/TestAddressSource.java +++ b/node/src/test/java/io/airlift/node/TestAddressSource.java @@ -20,7 +20,7 @@ import static io.airlift.node.AddressToHostname.encodeAddressAsHostname; import static io.airlift.node.AddressToHostname.tryDecodeHostnameToAddress; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestAddressSource { @@ -36,7 +36,7 @@ public void testIpEncoding() private static void verifyEncoding(String addressString, String encodedHostname) { - assertEquals(encodeAddressAsHostname(InetAddresses.forString(addressString)), encodedHostname); - assertEquals(tryDecodeHostnameToAddress(encodedHostname), Optional.of(InetAddresses.forString(addressString))); + assertThat(encodeAddressAsHostname(InetAddresses.forString(addressString))).isEqualTo(encodedHostname); + assertThat(tryDecodeHostnameToAddress(encodedHostname)).isEqualTo(Optional.of(InetAddresses.forString(addressString))); } } diff --git a/node/src/test/java/io/airlift/node/TestNodeInfo.java b/node/src/test/java/io/airlift/node/TestNodeInfo.java index 3ca2979cd7d..e7bdc4e7d6f 100644 --- a/node/src/test/java/io/airlift/node/TestNodeInfo.java +++ b/node/src/test/java/io/airlift/node/TestNodeInfo.java @@ -27,8 +27,7 @@ import static io.airlift.node.NodeConfig.AddressSource.IP; import static io.airlift.testing.Assertions.assertGreaterThanOrEqual; import static io.airlift.testing.Assertions.assertNotEquals; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestNodeInfo { @@ -49,32 +48,32 @@ public void testBasicNodeInfo() String externalAddress = "external"; NodeInfo nodeInfo = new NodeInfo(ENVIRONMENT, POOL, nodeId, internalIp, bindIp, externalAddress, location, binarySpec, configSpec, IP, null); - assertEquals(nodeInfo.getEnvironment(), ENVIRONMENT); - assertEquals(nodeInfo.getPool(), POOL); - assertEquals(nodeInfo.getNodeId(), nodeId); - assertEquals(nodeInfo.getLocation(), location); - assertEquals(nodeInfo.getBinarySpec(), binarySpec); - assertEquals(nodeInfo.getConfigSpec(), configSpec); - assertNotNull(nodeInfo.getInstanceId()); + assertThat(nodeInfo.getEnvironment()).isEqualTo(ENVIRONMENT); + assertThat(nodeInfo.getPool()).isEqualTo(POOL); + assertThat(nodeInfo.getNodeId()).isEqualTo(nodeId); + assertThat(nodeInfo.getLocation()).isEqualTo(location); + assertThat(nodeInfo.getBinarySpec()).isEqualTo(binarySpec); + assertThat(nodeInfo.getConfigSpec()).isEqualTo(configSpec); + assertThat(nodeInfo.getInstanceId()).isNotNull(); assertNotEquals(nodeInfo.getNodeId(), nodeInfo.getInstanceId()); - assertEquals(nodeInfo.getInternalAddress(), internalIp); - assertEquals(nodeInfo.getExternalAddress(), externalAddress); - assertEquals(nodeInfo.getBindIp(), bindIp); + assertThat(nodeInfo.getInternalAddress()).isEqualTo(internalIp); + assertThat(nodeInfo.getExternalAddress()).isEqualTo(externalAddress); + assertThat(nodeInfo.getBindIp()).isEqualTo(bindIp); assertGreaterThanOrEqual(nodeInfo.getStartTime(), testStartTime); - assertEquals(nodeInfo.getAnnotations().size(), 0); + assertThat(nodeInfo.getAnnotations().size()).isEqualTo(0); // make sure toString doesn't throw an exception - assertNotNull(nodeInfo.toString()); + assertThat(nodeInfo.toString()).isNotNull(); } @Test public void testDefaultAddresses() { NodeInfo nodeInfo = new NodeInfo(ENVIRONMENT, POOL, "nodeInfo", "10.0.0.22", null, null, null, null, null, IP, null); - assertEquals(nodeInfo.getExternalAddress(), "10.0.0.22"); - assertEquals(nodeInfo.getBindIp(), InetAddresses.forString("0.0.0.0")); + assertThat(nodeInfo.getExternalAddress()).isEqualTo("10.0.0.22"); + assertThat(nodeInfo.getBindIp()).isEqualTo(InetAddresses.forString("0.0.0.0")); } @Test @@ -82,9 +81,9 @@ public void testIpDiscovery() throws UnknownHostException { NodeInfo nodeInfo = new NodeInfo(ENVIRONMENT, POOL, "nodeInfo", null, null, null, null, null, null, IP, null); - assertNotNull(nodeInfo.getInternalAddress()); - assertEquals(nodeInfo.getBindIp(), InetAddresses.forString("0.0.0.0")); - assertEquals(nodeInfo.getExternalAddress(), nodeInfo.getInternalAddress()); + assertThat(nodeInfo.getInternalAddress()).isNotNull(); + assertThat(nodeInfo.getBindIp()).isEqualTo(InetAddresses.forString("0.0.0.0")); + assertThat(nodeInfo.getExternalAddress()).isEqualTo(nodeInfo.getInternalAddress()); } @Test @@ -92,9 +91,9 @@ public void testHostnameDiscovery() throws UnknownHostException { NodeInfo nodeInfo = new NodeInfo(ENVIRONMENT, POOL, "nodeInfo", null, null, null, null, null, null, HOSTNAME, null); - assertNotNull(nodeInfo.getInternalAddress()); - assertEquals(nodeInfo.getBindIp(), InetAddresses.forString("0.0.0.0")); - assertEquals(nodeInfo.getExternalAddress(), InetAddress.getLocalHost().getHostName()); + assertThat(nodeInfo.getInternalAddress()).isNotNull(); + assertThat(nodeInfo.getBindIp()).isEqualTo(InetAddresses.forString("0.0.0.0")); + assertThat(nodeInfo.getExternalAddress()).isEqualTo(InetAddress.getLocalHost().getHostName()); } @Test @@ -102,9 +101,9 @@ public void testFqdnDiscovery() throws UnknownHostException { NodeInfo nodeInfo = new NodeInfo(ENVIRONMENT, POOL, "nodeInfo", null, null, null, null, null, null, FQDN, null); - assertNotNull(nodeInfo.getInternalAddress()); - assertEquals(nodeInfo.getBindIp(), InetAddresses.forString("0.0.0.0")); - assertEquals(nodeInfo.getExternalAddress(), InetAddress.getLocalHost().getCanonicalHostName()); + assertThat(nodeInfo.getInternalAddress()).isNotNull(); + assertThat(nodeInfo.getBindIp()).isEqualTo(InetAddresses.forString("0.0.0.0")); + assertThat(nodeInfo.getExternalAddress()).isEqualTo(InetAddress.getLocalHost().getCanonicalHostName()); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "nodeId .*") diff --git a/node/src/test/java/io/airlift/node/TestNodeModule.java b/node/src/test/java/io/airlift/node/TestNodeModule.java index 7c0a0684575..8b9e1a9f61a 100644 --- a/node/src/test/java/io/airlift/node/TestNodeModule.java +++ b/node/src/test/java/io/airlift/node/TestNodeModule.java @@ -32,11 +32,7 @@ import static com.google.common.io.Resources.getResource; import static io.airlift.testing.Assertions.assertGreaterThanOrEqual; import static io.airlift.testing.Assertions.assertNotEquals; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestNodeModule { @@ -49,26 +45,26 @@ public void testDefaultConfig() ConfigurationFactory configFactory = new ConfigurationFactory(ImmutableMap.of("node.environment", "environment")); Injector injector = Guice.createInjector(new NodeModule(), new ConfigurationModule(configFactory)); NodeInfo nodeInfo = injector.getInstance(NodeInfo.class); - assertNotNull(nodeInfo); - assertEquals(nodeInfo.getEnvironment(), "environment"); - assertEquals(nodeInfo.getPool(), "general"); - assertNotNull(nodeInfo.getNodeId()); - assertNotNull(nodeInfo.getLocation()); - assertNull(nodeInfo.getBinarySpec()); - assertNull(nodeInfo.getConfigSpec()); - assertNotNull(nodeInfo.getInstanceId()); + assertThat(nodeInfo).isNotNull(); + assertThat(nodeInfo.getEnvironment()).isEqualTo("environment"); + assertThat(nodeInfo.getPool()).isEqualTo("general"); + assertThat(nodeInfo.getNodeId()).isNotNull(); + assertThat(nodeInfo.getLocation()).isNotNull(); + assertThat(nodeInfo.getBinarySpec()).isNull(); + assertThat(nodeInfo.getConfigSpec()).isNull(); + assertThat(nodeInfo.getInstanceId()).isNotNull(); assertNotEquals(nodeInfo.getNodeId(), nodeInfo.getInstanceId()); - assertNotNull(nodeInfo.getInternalAddress()); - assertFalse(InetAddress.getByName(nodeInfo.getInternalAddress()).isAnyLocalAddress()); - assertNotNull(nodeInfo.getBindIp()); - assertTrue(nodeInfo.getBindIp().isAnyLocalAddress()); + assertThat(nodeInfo.getInternalAddress()).isNotNull(); + assertThat(InetAddress.getByName(nodeInfo.getInternalAddress()).isAnyLocalAddress()).isFalse(); + assertThat(nodeInfo.getBindIp()).isNotNull(); + assertThat(nodeInfo.getBindIp().isAnyLocalAddress()).isTrue(); assertGreaterThanOrEqual(nodeInfo.getStartTime(), testStartTime); - assertEquals(nodeInfo.getAnnotations().size(), 0); + assertThat(nodeInfo.getAnnotations().size()).isEqualTo(0); // make sure toString doesn't throw an exception - assertNotNull(nodeInfo.toString()); + assertThat(nodeInfo.toString()).isNotNull(); } @Test @@ -99,23 +95,23 @@ public void testFullConfig() Injector injector = Guice.createInjector(new NodeModule(), new ConfigurationModule(configFactory)); NodeInfo nodeInfo = injector.getInstance(NodeInfo.class); - assertNotNull(nodeInfo); - assertEquals(nodeInfo.getEnvironment(), environment); - assertEquals(nodeInfo.getPool(), pool); - assertEquals(nodeInfo.getNodeId(), nodeId); - assertEquals(nodeInfo.getLocation(), location); - assertEquals(nodeInfo.getBinarySpec(), binarySpec); - assertEquals(nodeInfo.getConfigSpec(), configSpec); - assertNotNull(nodeInfo.getInstanceId()); + assertThat(nodeInfo).isNotNull(); + assertThat(nodeInfo.getEnvironment()).isEqualTo(environment); + assertThat(nodeInfo.getPool()).isEqualTo(pool); + assertThat(nodeInfo.getNodeId()).isEqualTo(nodeId); + assertThat(nodeInfo.getLocation()).isEqualTo(location); + assertThat(nodeInfo.getBinarySpec()).isEqualTo(binarySpec); + assertThat(nodeInfo.getConfigSpec()).isEqualTo(configSpec); + assertThat(nodeInfo.getInstanceId()).isNotNull(); assertNotEquals(nodeInfo.getNodeId(), nodeInfo.getInstanceId()); - assertEquals(nodeInfo.getInternalAddress(), publicAddress); - assertEquals(nodeInfo.getBindIp(), InetAddresses.forString("0.0.0.0")); + assertThat(nodeInfo.getInternalAddress()).isEqualTo(publicAddress); + assertThat(nodeInfo.getBindIp()).isEqualTo(InetAddresses.forString("0.0.0.0")); assertGreaterThanOrEqual(nodeInfo.getStartTime(), testStartTime); - assertEquals(nodeInfo.getAnnotations(), Map.of("team", "a", "region", "b")); + assertThat(nodeInfo.getAnnotations()).isEqualTo(Map.of("team", "a", "region", "b")); // make sure toString doesn't throw an exception - assertNotNull(nodeInfo.toString()); + assertThat(nodeInfo.toString()).isNotNull(); } } diff --git a/node/src/test/java/io/airlift/node/testing/TestTestingNodeModule.java b/node/src/test/java/io/airlift/node/testing/TestTestingNodeModule.java index 4b8a5428043..28d6c91761b 100644 --- a/node/src/test/java/io/airlift/node/testing/TestTestingNodeModule.java +++ b/node/src/test/java/io/airlift/node/testing/TestTestingNodeModule.java @@ -11,10 +11,7 @@ import static io.airlift.testing.Assertions.assertGreaterThanOrEqual; import static io.airlift.testing.Assertions.assertNotEquals; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestTestingNodeModule { @@ -27,25 +24,25 @@ public void testTestingNode() Injector injector = Guice.createInjector(new TestingNodeModule()); NodeInfo nodeInfo = injector.getInstance(NodeInfo.class); - assertNotNull(nodeInfo); - assertTrue(nodeInfo.getEnvironment().matches("test\\d+")); - assertEquals(nodeInfo.getPool(), "general"); - assertNotNull(nodeInfo.getNodeId()); - assertNotNull(nodeInfo.getLocation()); - assertNull(nodeInfo.getBinarySpec()); - assertNull(nodeInfo.getConfigSpec()); - assertNotNull(nodeInfo.getInstanceId()); + assertThat(nodeInfo).isNotNull(); + assertThat(nodeInfo.getEnvironment().matches("test\\d+")).isTrue(); + assertThat(nodeInfo.getPool()).isEqualTo("general"); + assertThat(nodeInfo.getNodeId()).isNotNull(); + assertThat(nodeInfo.getLocation()).isNotNull(); + assertThat(nodeInfo.getBinarySpec()).isNull(); + assertThat(nodeInfo.getConfigSpec()).isNull(); + assertThat(nodeInfo.getInstanceId()).isNotNull(); assertNotEquals(nodeInfo.getNodeId(), nodeInfo.getInstanceId()); - assertEquals(nodeInfo.getInternalAddress(), "127.0.0.1"); - assertEquals(nodeInfo.getBindIp(), InetAddress.getByName(nodeInfo.getInternalAddress())); - assertEquals(nodeInfo.getExternalAddress(), "127.0.0.1"); + assertThat(nodeInfo.getInternalAddress()).isEqualTo("127.0.0.1"); + assertThat(nodeInfo.getBindIp()).isEqualTo(InetAddress.getByName(nodeInfo.getInternalAddress())); + assertThat(nodeInfo.getExternalAddress()).isEqualTo("127.0.0.1"); assertGreaterThanOrEqual(nodeInfo.getStartTime(), testStartTime); // make sure toString doesn't throw an exception - assertNotNull(nodeInfo.toString()); + assertThat(nodeInfo.toString()).isNotNull(); } @Test @@ -54,8 +51,8 @@ public void testTestingNodeExplicitEnvironment() Injector injector = Guice.createInjector(new TestingNodeModule("foo")); NodeInfo nodeInfo = injector.getInstance(NodeInfo.class); - assertNotNull(nodeInfo); - assertEquals(nodeInfo.getEnvironment(), "foo"); + assertThat(nodeInfo).isNotNull(); + assertThat(nodeInfo.getEnvironment()).isEqualTo("foo"); } @Test @@ -64,8 +61,8 @@ public void testTestingNodePresentEnvironment() Injector injector = Guice.createInjector(new TestingNodeModule(Optional.of("foo"))); NodeInfo nodeInfo = injector.getInstance(NodeInfo.class); - assertNotNull(nodeInfo); - assertEquals(nodeInfo.getEnvironment(), "foo"); + assertThat(nodeInfo).isNotNull(); + assertThat(nodeInfo.getEnvironment()).isEqualTo("foo"); } @Test @@ -74,7 +71,7 @@ public void testTestingNodeAbsentEnvironment() Injector injector = Guice.createInjector(new TestingNodeModule(Optional.empty())); NodeInfo nodeInfo = injector.getInstance(NodeInfo.class); - assertNotNull(nodeInfo); - assertTrue(nodeInfo.getEnvironment().matches("test\\d+")); + assertThat(nodeInfo).isNotNull(); + assertThat(nodeInfo.getEnvironment().matches("test\\d+")).isTrue(); } } diff --git a/openmetrics/pom.xml b/openmetrics/pom.xml index 636bbe0f0d1..5f88ee4eb7a 100644 --- a/openmetrics/pom.xml +++ b/openmetrics/pom.xml @@ -67,6 +67,12 @@ test + + org.assertj + assertj-core + test + + org.testng testng diff --git a/openmetrics/src/test/java/io/airlift/openmetrics/TestMetricExpositions.java b/openmetrics/src/test/java/io/airlift/openmetrics/TestMetricExpositions.java index d908be1f5c5..7fed4dad1d0 100644 --- a/openmetrics/src/test/java/io/airlift/openmetrics/TestMetricExpositions.java +++ b/openmetrics/src/test/java/io/airlift/openmetrics/TestMetricExpositions.java @@ -23,7 +23,7 @@ import java.math.BigInteger; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestMetricExpositions { @@ -38,8 +38,8 @@ public void testCounterExposition() Counter counter = new Counter("metric_name", 0, ImmutableMap.of(), "metric_help"); BigCounter bigCounter = new BigCounter("metric_name", BigInteger.ZERO, ImmutableMap.of(), "metric_help"); - assertEquals(counter.getMetricExposition(), bigCounter.getMetricExposition()); - assertEquals(counter.getMetricExposition(), expected); + assertThat(counter.getMetricExposition()).isEqualTo(bigCounter.getMetricExposition()); + assertThat(counter.getMetricExposition()).isEqualTo(expected); } @Test @@ -53,8 +53,8 @@ public void testCounterExpositionLabels() Counter counter = new Counter("metric_name", 0, ImmutableMap.of("type", "cavendish"), "metric_help"); BigCounter bigCounter = new BigCounter("metric_name", BigInteger.ZERO, ImmutableMap.of("type", "cavendish"), "metric_help"); - assertEquals(counter.getMetricExposition(), bigCounter.getMetricExposition()); - assertEquals(counter.getMetricExposition(), expected); + assertThat(counter.getMetricExposition()).isEqualTo(bigCounter.getMetricExposition()); + assertThat(counter.getMetricExposition()).isEqualTo(expected); } @Test @@ -66,7 +66,7 @@ public void testGaugeExposition() metric_name 0.0 """; - assertEquals(new Gauge("metric_name", 0.0, ImmutableMap.of(), "metric_help").getMetricExposition(), expected); + assertThat(new Gauge("metric_name", 0.0, ImmutableMap.of(), "metric_help").getMetricExposition()).isEqualTo(expected); } @Test @@ -78,7 +78,7 @@ public void testGaugeExpositionLabels() metric_name{type="cavendish"} 0.0 """; - assertEquals(new Gauge("metric_name", 0.0, ImmutableMap.of("type", "cavendish"), "metric_help").getMetricExposition(), expected); + assertThat(new Gauge("metric_name", 0.0, ImmutableMap.of("type", "cavendish"), "metric_help").getMetricExposition()).isEqualTo(expected); } @Test @@ -90,7 +90,7 @@ public void testInfoExposition() metric_name banana """; - assertEquals(new Info("metric_name", "banana", ImmutableMap.of(), "metric_help").getMetricExposition(), expected); + assertThat(new Info("metric_name", "banana", ImmutableMap.of(), "metric_help").getMetricExposition()).isEqualTo(expected); } @Test @@ -102,7 +102,7 @@ public void testInfoExpositionLabels() metric_name{type="cavendish"} banana """; - assertEquals(new Info("metric_name", "banana", ImmutableMap.of("type", "cavendish"), "metric_help").getMetricExposition(), expected); + assertThat(new Info("metric_name", "banana", ImmutableMap.of("type", "cavendish"), "metric_help").getMetricExposition()).isEqualTo(expected); } @Test @@ -117,7 +117,7 @@ public void testSummaryExposition() metric_name{quantile="0.5"} 0.25 """; - assertEquals(new Summary("metric_name", 10L, 2.0, 3.0, ImmutableMap.of(0.5, 0.25), ImmutableMap.of(), "metric_help").getMetricExposition(), expected); + assertThat(new Summary("metric_name", 10L, 2.0, 3.0, ImmutableMap.of(0.5, 0.25), ImmutableMap.of(), "metric_help").getMetricExposition()).isEqualTo(expected); } @Test @@ -132,6 +132,6 @@ public void testSummaryExpositionLabels() metric_name{fruit="apple",quantile="0.5"} 0.25 """; - assertEquals(new Summary("metric_name", 10L, 2.0, 3.0, ImmutableMap.of(0.5, 0.25), ImmutableMap.of("fruit", "apple"), "metric_help").getMetricExposition(), expected); + assertThat(new Summary("metric_name", 10L, 2.0, 3.0, ImmutableMap.of(0.5, 0.25), ImmutableMap.of("fruit", "apple"), "metric_help").getMetricExposition()).isEqualTo(expected); } } diff --git a/sample-server/src/test/java/io/airlift/sample/TestPersonRepresentation.java b/sample-server/src/test/java/io/airlift/sample/TestPersonRepresentation.java index 323e3e8701a..ecd395c961c 100644 --- a/sample-server/src/test/java/io/airlift/sample/TestPersonRepresentation.java +++ b/sample-server/src/test/java/io/airlift/sample/TestPersonRepresentation.java @@ -21,7 +21,7 @@ import static io.airlift.json.JsonCodec.jsonCodec; import static java.nio.charset.StandardCharsets.UTF_8; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestPersonRepresentation { @@ -35,7 +35,7 @@ public void testJsonRoundTrip() PersonRepresentation expected = new PersonRepresentation("alice@example.com", "Alice", null); String json = codec.toJson(expected); PersonRepresentation actual = codec.fromJson(json); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } @Test @@ -47,6 +47,6 @@ public void testJsonDecode() String json = Resources.toString(Resources.getResource("single.json"), UTF_8); PersonRepresentation actual = codec.fromJson(json); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } } diff --git a/sample-server/src/test/java/io/airlift/sample/TestPersonResource.java b/sample-server/src/test/java/io/airlift/sample/TestPersonResource.java index 45631bdca83..3b895b84889 100644 --- a/sample-server/src/test/java/io/airlift/sample/TestPersonResource.java +++ b/sample-server/src/test/java/io/airlift/sample/TestPersonResource.java @@ -27,8 +27,7 @@ import static io.airlift.sample.PersonEvent.personAdded; import static io.airlift.sample.PersonEvent.personRemoved; import static io.airlift.sample.PersonEvent.personUpdated; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public class TestPersonResource @@ -49,7 +48,7 @@ public void setup() public void testNotFound() { Response response = resource.get("foo", MockUriInfo.from(URI.create("http://localhost/v1/person/1"))); - assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); + assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); } @Test @@ -58,9 +57,9 @@ public void testGet() store.put("foo", new Person("foo@example.com", "Mr Foo")); Response response = resource.get("foo", MockUriInfo.from(URI.create("http://localhost/v1/person/1"))); - assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); - assertEquals(response.getEntity(), new PersonRepresentation("foo@example.com", "Mr Foo", URI.create("http://localhost/v1/person/1"))); - assertNull(response.getMetadata().get("Content-Type")); // content type is set by JAX-RS based on @Produces + assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); + assertThat(response.getEntity()).isEqualTo(new PersonRepresentation("foo@example.com", "Mr Foo", URI.create("http://localhost/v1/person/1"))); + assertThat(response.getMetadata().get("Content-Type")).isNull(); // content type is set by JAX-RS based on @Produces } @Test(expectedExceptions = NullPointerException.class) @@ -74,13 +73,13 @@ public void testAdd() { Response response = resource.put("foo", new PersonRepresentation("foo@example.com", "Mr Foo", null)); - assertEquals(response.getStatus(), Response.Status.CREATED.getStatusCode()); - assertNull(response.getEntity()); - assertNull(response.getMetadata().get("Content-Type")); // content type is set by JAX-RS based on @Produces + assertThat(response.getStatus()).isEqualTo(Response.Status.CREATED.getStatusCode()); + assertThat(response.getEntity()).isNull(); + assertThat(response.getMetadata().get("Content-Type")).isNull(); // content type is set by JAX-RS based on @Produces - assertEquals(store.get("foo"), new Person("foo@example.com", "Mr Foo")); + assertThat(store.get("foo")).isEqualTo(new Person("foo@example.com", "Mr Foo")); - assertEquals(eventClient.getEvents(), ImmutableList.of( + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of( personAdded("foo", new Person("foo@example.com", "Mr Foo")))); } @@ -103,13 +102,13 @@ public void testReplace() Response response = resource.put("foo", new PersonRepresentation("bar@example.com", "Mr Bar", null)); - assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode()); - assertNull(response.getEntity()); - assertNull(response.getMetadata().get("Content-Type")); // content type is set by JAX-RS based on @Produces + assertThat(response.getStatus()).isEqualTo(Response.Status.NO_CONTENT.getStatusCode()); + assertThat(response.getEntity()).isNull(); + assertThat(response.getMetadata().get("Content-Type")).isNull(); // content type is set by JAX-RS based on @Produces - assertEquals(store.get("foo"), new Person("bar@example.com", "Mr Bar")); + assertThat(store.get("foo")).isEqualTo(new Person("bar@example.com", "Mr Bar")); - assertEquals(eventClient.getEvents(), ImmutableList.of( + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of( personAdded("foo", new Person("foo@example.com", "Mr Foo")), personUpdated("foo", new Person("bar@example.com", "Mr Bar")))); } @@ -120,12 +119,12 @@ public void testDelete() store.put("foo", new Person("foo@example.com", "Mr Foo")); Response response = resource.delete("foo"); - assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode()); - assertNull(response.getEntity()); + assertThat(response.getStatus()).isEqualTo(Response.Status.NO_CONTENT.getStatusCode()); + assertThat(response.getEntity()).isNull(); - assertNull(store.get("foo")); + assertThat(store.get("foo")).isNull(); - assertEquals(eventClient.getEvents(), ImmutableList.of( + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of( personAdded("foo", new Person("foo@example.com", "Mr Foo")), personRemoved("foo", new Person("foo@example.com", "Mr Foo")))); } @@ -134,8 +133,8 @@ public void testDelete() public void testDeleteMissing() { Response response = resource.delete("foo"); - assertEquals(response.getStatus(), Response.Status.NOT_FOUND.getStatusCode()); - assertNull(response.getEntity()); + assertThat(response.getStatus()).isEqualTo(Response.Status.NOT_FOUND.getStatusCode()); + assertThat(response.getEntity()).isNull(); } @Test(expectedExceptions = NullPointerException.class) diff --git a/sample-server/src/test/java/io/airlift/sample/TestPersonStore.java b/sample-server/src/test/java/io/airlift/sample/TestPersonStore.java index f577214ed4d..3340bed035d 100644 --- a/sample-server/src/test/java/io/airlift/sample/TestPersonStore.java +++ b/sample-server/src/test/java/io/airlift/sample/TestPersonStore.java @@ -26,9 +26,7 @@ import static io.airlift.sample.PersonEvent.personRemoved; import static io.airlift.sample.PersonEvent.personUpdated; import static java.util.Arrays.asList; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestPersonStore { @@ -36,7 +34,7 @@ public class TestPersonStore public void testStartsEmpty() { PersonStore store = new PersonStore(new StoreConfig(), new InMemoryEventClient()); - assertTrue(store.getAll().isEmpty()); + assertThat(store.getAll().isEmpty()).isTrue(); } @Test @@ -49,7 +47,7 @@ public void testTtl() PersonStore store = new PersonStore(config, new InMemoryEventClient()); store.put("foo", new Person("foo@example.com", "Mr Foo")); Thread.sleep(2); - assertNull(store.get("foo")); + assertThat(store.get("foo")).isNull(); } @Test @@ -59,10 +57,10 @@ public void testPut() PersonStore store = new PersonStore(new StoreConfig(), eventClient); store.put("foo", new Person("foo@example.com", "Mr Foo")); - assertEquals(new Person("foo@example.com", "Mr Foo"), store.get("foo")); - assertEquals(store.getAll().size(), 1); + assertThat(new Person("foo@example.com", "Mr Foo")).isEqualTo(store.get("foo")); + assertThat(store.getAll().size()).isEqualTo(1); - assertEquals(eventClient.getEvents(), ImmutableList.of(personAdded("foo", new Person("foo@example.com", "Mr Foo")))); + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of(personAdded("foo", new Person("foo@example.com", "Mr Foo")))); } @Test @@ -73,10 +71,10 @@ public void testIdempotentPut() store.put("foo", new Person("foo@example.com", "Mr Foo")); store.put("foo", new Person("foo@example.com", "Mr Bar")); - assertEquals(new Person("foo@example.com", "Mr Bar"), store.get("foo")); - assertEquals(store.getAll().size(), 1); + assertThat(new Person("foo@example.com", "Mr Bar")).isEqualTo(store.get("foo")); + assertThat(store.getAll().size()).isEqualTo(1); - assertEquals(eventClient.getEvents(), ImmutableList.of( + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of( personAdded("foo", new Person("foo@example.com", "Mr Foo")), personUpdated("foo", new Person("foo@example.com", "Mr Bar")))); } @@ -89,10 +87,10 @@ public void testDelete() store.put("foo", new Person("foo@example.com", "Mr Foo")); store.delete("foo"); - assertNull(store.get("foo")); - assertTrue(store.getAll().isEmpty()); + assertThat(store.get("foo")).isNull(); + assertThat(store.getAll().isEmpty()).isTrue(); - assertEquals(eventClient.getEvents(), ImmutableList.of( + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of( personAdded("foo", new Person("foo@example.com", "Mr Foo")), personRemoved("foo", new Person("foo@example.com", "Mr Foo")))); } @@ -105,14 +103,14 @@ public void testIdempotentDelete() store.put("foo", new Person("foo@example.com", "Mr Foo")); store.delete("foo"); - assertTrue(store.getAll().isEmpty()); - assertNull(store.get("foo")); + assertThat(store.getAll().isEmpty()).isTrue(); + assertThat(store.get("foo")).isNull(); store.delete("foo"); - assertTrue(store.getAll().isEmpty()); - assertNull(store.get("foo")); + assertThat(store.getAll().isEmpty()).isTrue(); + assertThat(store.get("foo")).isNull(); - assertEquals(eventClient.getEvents(), ImmutableList.of( + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of( personAdded("foo", new Person("foo@example.com", "Mr Foo")), personRemoved("foo", new Person("foo@example.com", "Mr Foo")))); } @@ -125,7 +123,7 @@ public void testGetAll() store.put("foo", new Person("foo@example.com", "Mr Foo")); store.put("bar", new Person("bar@example.com", "Mr Bar")); - assertEquals(store.getAll().size(), 2); - assertEquals(store.getAll(), asList(new Person("foo@example.com", "Mr Foo"), new Person("bar@example.com", "Mr Bar"))); + assertThat(store.getAll().size()).isEqualTo(2); + assertThat(store.getAll()).isEqualTo(asList(new Person("foo@example.com", "Mr Foo"), new Person("bar@example.com", "Mr Bar"))); } } diff --git a/sample-server/src/test/java/io/airlift/sample/TestPersonsResource.java b/sample-server/src/test/java/io/airlift/sample/TestPersonsResource.java index 1e19228600f..5d7d5afcaa7 100644 --- a/sample-server/src/test/java/io/airlift/sample/TestPersonsResource.java +++ b/sample-server/src/test/java/io/airlift/sample/TestPersonsResource.java @@ -25,7 +25,7 @@ import static com.google.common.collect.Lists.newArrayList; import static io.airlift.testing.Assertions.assertInstanceOf; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public class TestPersonsResource @@ -44,9 +44,9 @@ public void setup() public void testEmpty() { Response response = resource.listAll(); - assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); assertInstanceOf(response.getEntity(), Collection.class); - assertEquals((Collection) response.getEntity(), new ArrayList<>()); + assertThat((Collection) response.getEntity()).isEqualTo(new ArrayList<>()); } @Test @@ -56,9 +56,9 @@ public void testListAll() store.put("bar", new Person("bar@example.com", "Mr Bar")); Response response = resource.listAll(); - assertEquals(response.getStatus(), Response.Status.OK.getStatusCode()); + assertThat(response.getStatus()).isEqualTo(Response.Status.OK.getStatusCode()); assertInstanceOf(response.getEntity(), Collection.class); - assertEquals((Collection) response.getEntity(), newArrayList( + assertThat((Collection) response.getEntity()).isEqualTo(newArrayList( new PersonRepresentation("foo@example.com", "Mr Foo", null), new PersonRepresentation("bar@example.com", "Mr Bar", null))); } diff --git a/sample-server/src/test/java/io/airlift/sample/TestServer.java b/sample-server/src/test/java/io/airlift/sample/TestServer.java index d9bd847a46b..1c89bce0a0e 100644 --- a/sample-server/src/test/java/io/airlift/sample/TestServer.java +++ b/sample-server/src/test/java/io/airlift/sample/TestServer.java @@ -64,8 +64,6 @@ import static java.net.HttpURLConnection.HTTP_OK; import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNull; @Test(singleThreaded = true) public class TestServer @@ -124,7 +122,7 @@ public void testEmpty() prepareGet().setUri(uriFor("/v1/person")).build(), createJsonResponseHandler(listCodec)); - assertEquals(response, ImmutableList.of()); + assertThat(response).isEqualTo(ImmutableList.of()); } @Test @@ -158,7 +156,7 @@ public void testGetSingle() prepareGet().setUri(requestUri).build(), createJsonResponseHandler(mapCodec)); - assertEquals(actual, expected); + assertThat(actual).isEqualTo(expected); } @Test @@ -175,11 +173,11 @@ public void testPut() .build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HTTP_CREATED); + assertThat(response.getStatusCode()).isEqualTo(HTTP_CREATED); - assertEquals(store.get("foo"), new Person("foo@example.com", "Mr Foo")); + assertThat(store.get("foo")).isEqualTo(new Person("foo@example.com", "Mr Foo")); - assertEquals(eventClient.getEvents(), ImmutableList.of( + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of( personAdded("foo", new Person("foo@example.com", "Mr Foo")))); } @@ -195,11 +193,11 @@ public void testDelete() .build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HTTP_NO_CONTENT); + assertThat(response.getStatusCode()).isEqualTo(HTTP_NO_CONTENT); - assertNull(store.get("foo")); + assertThat(store.get("foo")).isNull(); - assertEquals(eventClient.getEvents(), ImmutableList.of( + assertThat(eventClient.getEvents()).isEqualTo(ImmutableList.of( personAdded("foo", new Person("foo@example.com", "Mr Foo")), personRemoved("foo", new Person("foo@example.com", "Mr Foo")))); } @@ -214,7 +212,7 @@ public void testDeleteMissing() .build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HTTP_NOT_FOUND); + assertThat(response.getStatusCode()).isEqualTo(HTTP_NOT_FOUND); } @Test @@ -231,9 +229,9 @@ public void testPostNotAllowed() .build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), HTTP_BAD_METHOD); + assertThat(response.getStatusCode()).isEqualTo(HTTP_BAD_METHOD); - assertNull(store.get("foo")); + assertThat(store.get("foo")).isNull(); } @Test diff --git a/security-jwks/src/test/java/io/airlift/security/jwks/TestJwksDecoder.java b/security-jwks/src/test/java/io/airlift/security/jwks/TestJwksDecoder.java index 795a5b3eb83..c573578f769 100644 --- a/security-jwks/src/test/java/io/airlift/security/jwks/TestJwksDecoder.java +++ b/security-jwks/src/test/java/io/airlift/security/jwks/TestJwksDecoder.java @@ -36,8 +36,8 @@ import static io.airlift.security.jwks.JwksDecoder.decodeKeys; import static io.airlift.testing.Assertions.assertInstanceOf; import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertSame; public class TestJwksDecoder @@ -67,7 +67,7 @@ public void testReadRsaKeys() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 2); + assertThat(keys.size()).isEqualTo(2); assertInstanceOf(keys.get("example-rsa"), JwkRsaPublicKey.class); assertInstanceOf(keys.get("example-ec"), JwkEcPublicKey.class); } @@ -95,7 +95,7 @@ public void testNoKeyId() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 0); + assertThat(keys.size()).isEqualTo(0); } @Test @@ -113,7 +113,7 @@ public void testRsaNoModulus() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 0); + assertThat(keys.size()).isEqualTo(0); } @Test @@ -131,7 +131,7 @@ public void testRsaNoExponent() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 0); + assertThat(keys.size()).isEqualTo(0); } @Test @@ -150,7 +150,7 @@ public void testRsaInvalidModulus() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 0); + assertThat(keys.size()).isEqualTo(0); } @Test @@ -169,7 +169,7 @@ public void testRsaInvalidExponent() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 0); + assertThat(keys.size()).isEqualTo(0); } @Test @@ -180,11 +180,11 @@ public void testJwtRsa() Map keys = decodeKeys(jwksJson); RSAPublicKey publicKey = (RSAPublicKey) keys.get("test-rsa"); - assertNotNull(publicKey); + assertThat(publicKey).isNotNull(); RSAPublicKey expectedPublicKey = (RSAPublicKey) PemReader.loadPublicKey(new File(Resources.getResource("jwks/jwk-rsa-public.pem").getPath())); - assertEquals(publicKey.getPublicExponent(), expectedPublicKey.getPublicExponent()); - assertEquals(publicKey.getModulus(), expectedPublicKey.getModulus()); + assertThat(publicKey.getPublicExponent()).isEqualTo(expectedPublicKey.getPublicExponent()); + assertThat(publicKey.getModulus()).isEqualTo(expectedPublicKey.getModulus()); PrivateKey privateKey = PemReader.loadPrivateKey(new File(Resources.getResource("jwks/jwk-rsa-private.pem").getPath()), Optional.empty()); String jwt = Jwts.builder() @@ -204,7 +204,7 @@ public void testJwtRsa() .build() .parseSignedClaims(jwt); - assertEquals(claimsJws.getPayload().getSubject(), "test-user"); + assertThat(claimsJws.getPayload().getSubject()).isEqualTo("test-user"); } @Test @@ -222,7 +222,7 @@ public void testEcKey() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 1); + assertThat(keys.size()).isEqualTo(1); assertInstanceOf(keys.get("test-ec"), JwkEcPublicKey.class); } @@ -241,7 +241,7 @@ public void testEcInvalidCurve() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 0); + assertThat(keys.size()).isEqualTo(0); } @Test @@ -259,7 +259,7 @@ public void testEcInvalidX() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 0); + assertThat(keys.size()).isEqualTo(0); } @Test @@ -277,7 +277,7 @@ public void testEcInvalidY() " }\n" + " ]\n" + "}"); - assertEquals(keys.size(), 0); + assertThat(keys.size()).isEqualTo(0); } @Test @@ -296,16 +296,16 @@ private static void assertJwtEc(String keyName, SignatureAlgorithm signatureAlgo Map keys = decodeKeys(jwksJson); ECPublicKey publicKey = (ECPublicKey) keys.get(keyName); - assertNotNull(publicKey); + assertThat(publicKey).isNotNull(); assertSame(publicKey.getParams(), expectedSpec); ECPublicKey expectedPublicKey = (ECPublicKey) PemReader.loadPublicKey(new File(Resources.getResource("jwks/" + keyName + "-public.pem").getPath())); - assertEquals(publicKey.getW(), expectedPublicKey.getW()); - assertEquals(publicKey.getParams().getCurve(), expectedPublicKey.getParams().getCurve()); - assertEquals(publicKey.getParams().getGenerator(), expectedPublicKey.getParams().getGenerator()); - assertEquals(publicKey.getParams().getOrder(), expectedPublicKey.getParams().getOrder()); - assertEquals(publicKey.getParams().getCofactor(), expectedPublicKey.getParams().getCofactor()); + assertThat(publicKey.getW()).isEqualTo(expectedPublicKey.getW()); + assertThat(publicKey.getParams().getCurve()).isEqualTo(expectedPublicKey.getParams().getCurve()); + assertThat(publicKey.getParams().getGenerator()).isEqualTo(expectedPublicKey.getParams().getGenerator()); + assertThat(publicKey.getParams().getOrder()).isEqualTo(expectedPublicKey.getParams().getOrder()); + assertThat(publicKey.getParams().getCofactor()).isEqualTo(expectedPublicKey.getParams().getCofactor()); PrivateKey privateKey = PemReader.loadPrivateKey(new File(Resources.getResource("jwks/" + keyName + "-private.pem").getPath()), Optional.empty()); String jwt = Jwts.builder() @@ -327,6 +327,6 @@ private static void assertJwtEc(String keyName, SignatureAlgorithm signatureAlgo .build() .parseSignedClaims(jwt); - assertEquals(claimsJws.getPayload().getSubject(), "test-user"); + assertThat(claimsJws.getPayload().getSubject()).isEqualTo("test-user"); } } diff --git a/security-jwks/src/test/java/io/airlift/security/jwks/TestJwksService.java b/security-jwks/src/test/java/io/airlift/security/jwks/TestJwksService.java index 052f41d4a47..72daeeef3b1 100644 --- a/security-jwks/src/test/java/io/airlift/security/jwks/TestJwksService.java +++ b/security-jwks/src/test/java/io/airlift/security/jwks/TestJwksService.java @@ -30,9 +30,8 @@ import static io.airlift.http.client.testing.TestingResponse.mockResponse; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; public class TestJwksService { @@ -191,15 +190,15 @@ public void testBadResponse() private static void assertEmptyKeys(JwksService service) { - assertEquals(service.getKeys().size(), 0); + assertThat(service.getKeys().size()).isEqualTo(0); } private static void assertTestKeys(JwksService service) { Map keys = service.getKeys(); - assertEquals(keys.size(), 3); - assertTrue(keys.containsKey("test-rsa")); - assertTrue(keys.containsKey("test-ec")); - assertTrue(keys.containsKey("test-certificate-chain")); + assertThat(keys.size()).isEqualTo(3); + assertThat(keys.containsKey("test-rsa")).isTrue(); + assertThat(keys.containsKey("test-ec")).isTrue(); + assertThat(keys.containsKey("test-certificate-chain")).isTrue(); } } diff --git a/security/src/test/java/io/airlift/security/cert/TestCertificateBuilder.java b/security/src/test/java/io/airlift/security/cert/TestCertificateBuilder.java index 599748398fe..1ec539820b2 100644 --- a/security/src/test/java/io/airlift/security/cert/TestCertificateBuilder.java +++ b/security/src/test/java/io/airlift/security/cert/TestCertificateBuilder.java @@ -30,7 +30,7 @@ import static io.airlift.security.cert.CertificateBuilder.certificateBuilder; import static java.time.ZoneOffset.UTC; import static java.time.temporal.ChronoUnit.YEARS; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestCertificateBuilder { @@ -55,12 +55,12 @@ public void test() .setSubject(subject) .buildSelfSigned(); - assertEquals(certificate.getSerialNumber(), BigInteger.valueOf(12345)); - assertEquals(certificate.getIssuerX500Principal(), issuer); - assertEquals(certificate.getNotBefore().toInstant(), notBefore.atStartOfDay().toInstant(UTC)); - assertEquals(certificate.getNotAfter().toInstant(), notAfter.atTime(23, 59, 59).toInstant(UTC)); - assertEquals(certificate.getSubjectX500Principal(), subject); - assertEquals(certificate.getPublicKey(), keyPair.getPublic()); + assertThat(certificate.getSerialNumber()).isEqualTo(BigInteger.valueOf(12345)); + assertThat(certificate.getIssuerX500Principal()).isEqualTo(issuer); + assertThat(certificate.getNotBefore().toInstant()).isEqualTo(notBefore.atStartOfDay().toInstant(UTC)); + assertThat(certificate.getNotAfter().toInstant()).isEqualTo(notAfter.atTime(23, 59, 59).toInstant(UTC)); + assertThat(certificate.getSubjectX500Principal()).isEqualTo(subject); + assertThat(certificate.getPublicKey()).isEqualTo(keyPair.getPublic()); // verify certificate trusts itself KeyStore keyStore = KeyStore.getInstance("JKS"); diff --git a/security/src/test/java/io/airlift/security/csr/TestCertificationRequest.java b/security/src/test/java/io/airlift/security/csr/TestCertificationRequest.java index 341b4b7530a..72105387092 100644 --- a/security/src/test/java/io/airlift/security/csr/TestCertificationRequest.java +++ b/security/src/test/java/io/airlift/security/csr/TestCertificationRequest.java @@ -29,7 +29,7 @@ import static com.google.common.io.BaseEncoding.base16; import static io.airlift.security.csr.SignatureAlgorithmIdentifier.findSignatureAlgorithmIdentifier; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestCertificationRequest { @@ -49,19 +49,17 @@ public void test() byte[] signature = certificationRequestInfo.sign(signatureAlgorithmIdentifier, keyPair.getPrivate()); CertificationRequest certificationRequest = new CertificationRequest(certificationRequestInfo, signatureAlgorithmIdentifier, signature); - assertEquals(certificationRequest.getCertificationRequestInfo(), certificationRequestInfo); - assertEquals(certificationRequest.getSignatureAlgorithmIdentifier(), signatureAlgorithmIdentifier); - assertEquals(base16().encode(certificationRequest.getSignature()), base16().encode(signature)); - assertEquals(certificationRequest, certificationRequest); - assertEquals(certificationRequest.hashCode(), certificationRequest.hashCode()); + assertThat(certificationRequest.getCertificationRequestInfo()).isEqualTo(certificationRequestInfo); + assertThat(certificationRequest.getSignatureAlgorithmIdentifier()).isEqualTo(signatureAlgorithmIdentifier); + assertThat(base16().encode(certificationRequest.getSignature())).isEqualTo(base16().encode(signature)); + assertThat(certificationRequest).isEqualTo(certificationRequest); + assertThat(certificationRequest.hashCode()).isEqualTo(certificationRequest.hashCode()); PKCS10CertificationRequest expectedCertificationRequest = new PKCS10CertificationRequest(new org.bouncycastle.asn1.pkcs.CertificationRequest( new org.bouncycastle.asn1.pkcs.CertificationRequestInfo(new X500Name(name), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()), new DERSet()), new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA"), new DERBitString(signature))); - assertEquals( - base16().encode(certificationRequest.getEncoded()), - base16().encode(expectedCertificationRequest.getEncoded())); + assertThat(base16().encode(certificationRequest.getEncoded())).isEqualTo(base16().encode(expectedCertificationRequest.getEncoded())); } } diff --git a/security/src/test/java/io/airlift/security/csr/TestCertificationRequestInfo.java b/security/src/test/java/io/airlift/security/csr/TestCertificationRequestInfo.java index a704bcd17a7..6fa860d3642 100644 --- a/security/src/test/java/io/airlift/security/csr/TestCertificationRequestInfo.java +++ b/security/src/test/java/io/airlift/security/csr/TestCertificationRequestInfo.java @@ -27,8 +27,7 @@ import static com.google.common.io.BaseEncoding.base16; import static io.airlift.security.csr.SignatureAlgorithmIdentifier.findSignatureAlgorithmIdentifier; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestCertificationRequestInfo { @@ -44,22 +43,20 @@ public void test() KeyPair keyPair = generator.generateKeyPair(); CertificationRequestInfo actualInfo = new CertificationRequestInfo(new X500Principal(name), keyPair.getPublic()); - assertEquals(actualInfo.getPublicKey(), keyPair.getPublic()); - assertEquals(actualInfo.getSubject().getName(), name); - assertEquals(actualInfo, actualInfo); - assertEquals(actualInfo.hashCode(), actualInfo.hashCode()); + assertThat(actualInfo.getPublicKey()).isEqualTo(keyPair.getPublic()); + assertThat(actualInfo.getSubject().getName()).isEqualTo(name); + assertThat(actualInfo).isEqualTo(actualInfo); + assertThat(actualInfo.hashCode()).isEqualTo(actualInfo.hashCode()); org.bouncycastle.asn1.pkcs.CertificationRequestInfo expectedInfo = new org.bouncycastle.asn1.pkcs.CertificationRequestInfo(new X500Name(name), SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()), new DERSet()); - assertEquals( - base16().encode(actualInfo.getEncoded()), - base16().encode(expectedInfo.getEncoded("DER"))); + assertThat(base16().encode(actualInfo.getEncoded())).isEqualTo(base16().encode(expectedInfo.getEncoded("DER"))); SignatureAlgorithmIdentifier signatureAlgorithmIdentifier = findSignatureAlgorithmIdentifier("SHA256withECDSA"); byte[] actualSignature = actualInfo.sign(signatureAlgorithmIdentifier, keyPair.getPrivate()); Signature signature = Signature.getInstance(signatureAlgorithmIdentifier.getName()); signature.initVerify(keyPair.getPublic()); signature.update(actualInfo.getEncoded()); - assertTrue(signature.verify(actualSignature)); + assertThat(signature.verify(actualSignature)).isTrue(); } } diff --git a/security/src/test/java/io/airlift/security/csr/TestSignatureAlgorithmIdentifier.java b/security/src/test/java/io/airlift/security/csr/TestSignatureAlgorithmIdentifier.java index 15a7f718827..7a2ce9fadef 100644 --- a/security/src/test/java/io/airlift/security/csr/TestSignatureAlgorithmIdentifier.java +++ b/security/src/test/java/io/airlift/security/csr/TestSignatureAlgorithmIdentifier.java @@ -21,7 +21,6 @@ import static com.google.common.io.BaseEncoding.base16; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; public class TestSignatureAlgorithmIdentifier { @@ -32,7 +31,7 @@ public void test() int verifiedCount = 0; for (Entry entry : SignatureAlgorithmIdentifier.getAllSignatureAlgorithmIdentifiers().entrySet()) { SignatureAlgorithmIdentifier signatureAlgorithmIdentifier = entry.getValue(); - assertEquals(signatureAlgorithmIdentifier.getName(), entry.getKey()); + assertThat(signatureAlgorithmIdentifier.getName()).isEqualTo(entry.getKey()); AlgorithmIdentifier algorithmIdentifier; try { @@ -42,14 +41,10 @@ public void test() // Bouncy is missing some algorithms the JVM supports continue; } - assertEquals( - signatureAlgorithmIdentifier.getOid(), - algorithmIdentifier.getAlgorithm().getId()); - assertEquals( - base16().encode(signatureAlgorithmIdentifier.getEncoded()), - base16().encode(algorithmIdentifier.getAlgorithm().getEncoded("DER"))); - assertEquals(algorithmIdentifier, algorithmIdentifier); - assertEquals(algorithmIdentifier.hashCode(), algorithmIdentifier.hashCode()); + assertThat(signatureAlgorithmIdentifier.getOid()).isEqualTo(algorithmIdentifier.getAlgorithm().getId()); + assertThat(base16().encode(signatureAlgorithmIdentifier.getEncoded())).isEqualTo(base16().encode(algorithmIdentifier.getAlgorithm().getEncoded("DER"))); + assertThat(algorithmIdentifier).isEqualTo(algorithmIdentifier); + assertThat(algorithmIdentifier.hashCode()).isEqualTo(algorithmIdentifier.hashCode()); verifiedCount++; } assertThat(verifiedCount).as("Algorithm identifiers verified").isGreaterThanOrEqualTo(10); diff --git a/security/src/test/java/io/airlift/security/pem/TestPemReader.java b/security/src/test/java/io/airlift/security/pem/TestPemReader.java index 458bef11e72..6a7000f74c3 100644 --- a/security/src/test/java/io/airlift/security/pem/TestPemReader.java +++ b/security/src/test/java/io/airlift/security/pem/TestPemReader.java @@ -51,9 +51,7 @@ import static io.airlift.security.pem.PemWriter.writePrivateKey; import static io.airlift.security.pem.PemWriter.writePublicKey; import static java.nio.charset.StandardCharsets.US_ASCII; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestPemReader { @@ -93,14 +91,14 @@ private static void testLoadKeyStore(String certFile, String keyFile, Optional aliases = Collections.list(keyStore.aliases()); - assertEquals(aliases.size(), 1); + assertThat(aliases.size()).isEqualTo(1); Certificate certificate = keyStore.getCertificate(aliases.get(0)); - assertNotNull(certificate); + assertThat(certificate).isNotNull(); - assertTrue(certificate instanceof X509Certificate); + assertThat(certificate instanceof X509Certificate).isTrue(); X509Certificate x509Certificate = (X509Certificate) certificate; assertX509Certificate(x509Certificate, expectedName); @@ -193,14 +191,14 @@ private static void assertX509Certificate(X509Certificate x509Certificate, Strin throws InvalidNameException { LdapName ldapName = new LdapName(x509Certificate.getSubjectX500Principal().getName()); - assertEquals(ldapName.toString(), expectedName); + assertThat(ldapName.toString()).isEqualTo(expectedName); } private static byte[] loadPrivateKeyData(String keyFile) throws IOException, KeyStoreException { File file = getResourceFile(keyFile); - assertTrue(isPem(file)); + assertThat(isPem(file)).isTrue(); String privateKey = asCharSource(file, US_ASCII).read(); Matcher matcher = PRIVATE_KEY_PATTERN.matcher(privateKey); if (!matcher.find()) { @@ -214,7 +212,7 @@ private static byte[] loadPublicKeyData(String keyFile) throws IOException, KeyStoreException { File file = getResourceFile(keyFile); - assertTrue(isPem(file)); + assertThat(isPem(file)).isTrue(); String privateKey = asCharSource(file, US_ASCII).read(); Matcher matcher = PUBLIC_KEY_PATTERN.matcher(privateKey); if (!matcher.find()) { diff --git a/skeleton-server/pom.xml b/skeleton-server/pom.xml index 976157787eb..6a203850160 100644 --- a/skeleton-server/pom.xml +++ b/skeleton-server/pom.xml @@ -126,6 +126,12 @@ test + + org.assertj + assertj-core + test + + org.testng diff --git a/skeleton-server/src/test/java/io/airlift/skeleton/TestServer.java b/skeleton-server/src/test/java/io/airlift/skeleton/TestServer.java index e88e0a1b23f..bba86c6568f 100644 --- a/skeleton-server/src/test/java/io/airlift/skeleton/TestServer.java +++ b/skeleton-server/src/test/java/io/airlift/skeleton/TestServer.java @@ -22,7 +22,7 @@ import static io.airlift.http.client.Request.Builder.prepareGet; import static io.airlift.http.client.StatusResponseHandler.createStatusResponseHandler; import static jakarta.ws.rs.core.Response.Status.OK; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; @Test(singleThreaded = true) public class TestServer @@ -70,7 +70,7 @@ public void testNothing() prepareGet().setUri(uriFor("/v1/jmx/mbean")).build(), createStatusResponseHandler()); - assertEquals(response.getStatusCode(), OK.getStatusCode()); + assertThat(response.getStatusCode()).isEqualTo(OK.getStatusCode()); } private URI uriFor(String path) diff --git a/stats/src/test/java/io/airlift/stats/TestCpuTimer.java b/stats/src/test/java/io/airlift/stats/TestCpuTimer.java index 9142af74139..413b3460ca9 100644 --- a/stats/src/test/java/io/airlift/stats/TestCpuTimer.java +++ b/stats/src/test/java/io/airlift/stats/TestCpuTimer.java @@ -5,10 +5,8 @@ import static io.airlift.units.Duration.succinctDuration; import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; public class TestCpuTimer { @@ -16,32 +14,32 @@ public class TestCpuTimer public void testCpuTimerWithUserTimeEnabled() { CpuTimer timer = new CpuTimer(); - assertTrue(timer.elapsedTime().hasUser()); - assertTrue(timer.startNewInterval().hasUser()); - assertTrue(timer.elapsedIntervalTime().hasUser()); - assertTrue(timer.elapsedTime().add(new CpuTimer.CpuDuration()).hasUser()); - assertTrue(timer.elapsedTime().subtract(new CpuTimer.CpuDuration()).hasUser()); + assertThat(timer.elapsedTime().hasUser()).isTrue(); + assertThat(timer.startNewInterval().hasUser()).isTrue(); + assertThat(timer.elapsedIntervalTime().hasUser()).isTrue(); + assertThat(timer.elapsedTime().add(new CpuTimer.CpuDuration()).hasUser()).isTrue(); + assertThat(timer.elapsedTime().subtract(new CpuTimer.CpuDuration()).hasUser()).isTrue(); } @Test public void testCpuTimerWithoutUserTimeEnabled() { CpuTimer timer = new CpuTimer(false); - assertFalse(timer.elapsedTime().hasUser()); - assertFalse(timer.startNewInterval().hasUser()); - assertFalse(timer.elapsedIntervalTime().hasUser()); + assertThat(timer.elapsedTime().hasUser()).isFalse(); + assertThat(timer.startNewInterval().hasUser()).isFalse(); + assertThat(timer.elapsedIntervalTime().hasUser()).isFalse(); CpuTimer.CpuDuration withUser = new CpuTimer.CpuDuration(); CpuTimer.CpuDuration withoutUser = timer.elapsedTime(); - assertTrue(withUser.hasUser()); - assertFalse(withoutUser.hasUser()); + assertThat(withUser.hasUser()).isTrue(); + assertThat(withoutUser.hasUser()).isFalse(); - assertFalse(withUser.add(withoutUser).hasUser()); - assertFalse(withoutUser.add(withUser).hasUser()); + assertThat(withUser.add(withoutUser).hasUser()).isFalse(); + assertThat(withoutUser.add(withUser).hasUser()).isFalse(); - assertFalse(withUser.subtract(withoutUser).hasUser()); - assertFalse(withoutUser.subtract(withUser).hasUser()); + assertThat(withUser.subtract(withoutUser).hasUser()).isFalse(); + assertThat(withoutUser.subtract(withUser).hasUser()).isFalse(); } @Test @@ -58,6 +56,6 @@ public void testCustomTicker() TestingTicker ticker = new TestingTicker(); CpuTimer timer = new CpuTimer(ticker, true); ticker.increment(1, SECONDS); - assertEquals(timer.elapsedTime().getWall(), succinctDuration(1, SECONDS)); + assertThat(timer.elapsedTime().getWall()).isEqualTo(succinctDuration(1, SECONDS)); } } diff --git a/stats/src/test/java/io/airlift/stats/TestDecayCounter.java b/stats/src/test/java/io/airlift/stats/TestDecayCounter.java index 9d13b5ba4f4..8bb9560af1b 100644 --- a/stats/src/test/java/io/airlift/stats/TestDecayCounter.java +++ b/stats/src/test/java/io/airlift/stats/TestDecayCounter.java @@ -5,8 +5,7 @@ import java.util.concurrent.TimeUnit; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestDecayCounter { @@ -19,7 +18,7 @@ public void testCountDecays() counter.add(1); ticker.increment(1, TimeUnit.MINUTES); - assertTrue(Math.abs(counter.getCount() - 1 / Math.E) < 1e-9); + assertThat(Math.abs(counter.getCount() - 1 / Math.E) < 1e-9).isTrue(); } @Test @@ -33,7 +32,7 @@ public void testAddAfterRescale() counter.add(2); double expected = 2 + 1 / Math.E; - assertTrue(Math.abs(counter.getCount() - expected) < 1e-9); + assertThat(Math.abs(counter.getCount() - expected) < 1e-9).isTrue(); } @Test @@ -46,7 +45,7 @@ public void testDuplicate() ticker.increment(1, TimeUnit.MINUTES); DecayCounter copy = counter.duplicate(); - assertEquals(copy.getCount(), counter.getCount()); - assertEquals(copy.getAlpha(), counter.getAlpha()); + assertThat(copy.getCount()).isEqualTo(counter.getCount()); + assertThat(copy.getAlpha()).isEqualTo(counter.getAlpha()); } } diff --git a/stats/src/test/java/io/airlift/stats/TestDecayTDigest.java b/stats/src/test/java/io/airlift/stats/TestDecayTDigest.java index 18881b2c8ea..c776fec89f1 100644 --- a/stats/src/test/java/io/airlift/stats/TestDecayTDigest.java +++ b/stats/src/test/java/io/airlift/stats/TestDecayTDigest.java @@ -9,7 +9,6 @@ import static io.airlift.stats.DecayTDigest.RESCALE_THRESHOLD_SECONDS; import static io.airlift.stats.DecayTDigest.ZERO_WEIGHT_THRESHOLD; import static org.assertj.core.api.Assertions.assertThat; -import static org.testng.Assert.assertEquals; public class TestDecayTDigest { @@ -22,13 +21,13 @@ public void testRescaleMinMax() digest.add(5); digest.add(1); - assertEquals(digest.getMin(), 1.0); - assertEquals(digest.getMax(), 5.0); + assertThat(digest.getMin()).isEqualTo(1.0); + assertThat(digest.getMax()).isEqualTo(5.0); ticker.increment(51, TimeUnit.SECONDS); - assertEquals(digest.getMin(), 1.0); - assertEquals(digest.getMax(), 5.0); + assertThat(digest.getMin()).isEqualTo(1.0); + assertThat(digest.getMax()).isEqualTo(5.0); } @Test @@ -44,7 +43,7 @@ public void testDecayBelowThreshold() // incrementing time by this amount should cause the weight of the existing value to become "zero" ticker.increment((long) Math.ceil(Math.log(1 / ZERO_WEIGHT_THRESHOLD) / decayFactor), TimeUnit.SECONDS); - assertEquals(digest.getCount(), 0.0); + assertThat(digest.getCount()).isEqualTo(0.0); } @Test diff --git a/stats/src/test/java/io/airlift/stats/TestDistribution.java b/stats/src/test/java/io/airlift/stats/TestDistribution.java index bc3e2450773..55d9044d6f0 100644 --- a/stats/src/test/java/io/airlift/stats/TestDistribution.java +++ b/stats/src/test/java/io/airlift/stats/TestDistribution.java @@ -2,7 +2,7 @@ import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestDistribution { @@ -12,13 +12,13 @@ public void testReset() Distribution distribution = new Distribution(0.1); distribution.add(10); - assertEquals(distribution.getCount(), 1D); - assertEquals(distribution.getAvg(), 10D); + assertThat(distribution.getCount()).isEqualTo(1D); + assertThat(distribution.getAvg()).isEqualTo(10D); distribution.reset(); - assertEquals(distribution.getCount(), 0D); - assertEquals(distribution.getAvg(), Double.NaN); + assertThat(distribution.getCount()).isEqualTo(0D); + assertThat(distribution.getAvg()).isEqualTo(Double.NaN); } @Test @@ -30,7 +30,7 @@ public void testDuplicate() Distribution copy = distribution.duplicate(); - assertEquals(copy.getCount(), distribution.getCount()); - assertEquals(copy.getTotal(), distribution.getTotal()); + assertThat(copy.getCount()).isEqualTo(distribution.getCount()); + assertThat(copy.getTotal()).isEqualTo(distribution.getTotal()); } } diff --git a/stats/src/test/java/io/airlift/stats/TestJmxGcMonitor.java b/stats/src/test/java/io/airlift/stats/TestJmxGcMonitor.java index e7bebb287fe..5227ac59d56 100644 --- a/stats/src/test/java/io/airlift/stats/TestJmxGcMonitor.java +++ b/stats/src/test/java/io/airlift/stats/TestJmxGcMonitor.java @@ -5,7 +5,7 @@ import static io.airlift.testing.Assertions.assertGreaterThanOrEqual; import static java.util.concurrent.TimeUnit.NANOSECONDS; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestJmxGcMonitor { @@ -14,8 +14,8 @@ public void test() throws Exception { JmxGcMonitor gcMonitor = new JmxGcMonitor(); - assertEquals(gcMonitor.getMajorGcCount(), 0); - assertEquals(gcMonitor.getMajorGcTime(), new Duration(0, NANOSECONDS)); + assertThat(gcMonitor.getMajorGcCount()).isEqualTo(0); + assertThat(gcMonitor.getMajorGcTime()).isEqualTo(new Duration(0, NANOSECONDS)); try { gcMonitor.start(); assertGreaterThanOrEqual(gcMonitor.getMajorGcCount(), (long) 0); diff --git a/stats/src/test/java/io/airlift/stats/TestQuantileDigest.java b/stats/src/test/java/io/airlift/stats/TestQuantileDigest.java index b56bddb55db..7ae6c77b04f 100644 --- a/stats/src/test/java/io/airlift/stats/TestQuantileDigest.java +++ b/stats/src/test/java/io/airlift/stats/TestQuantileDigest.java @@ -18,9 +18,7 @@ import static com.google.common.collect.ImmutableList.toImmutableList; import static java.lang.String.format; import static java.util.Arrays.asList; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestQuantileDigest { @@ -33,10 +31,10 @@ public void testSingleAdd() digest.validate(); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); - assertEquals(digest.getCount(), (double) 1); - assertEquals(digest.getNodeCount(), 1); + assertThat(digest.getCount()).isEqualTo((double) 1); + assertThat(digest.getNodeCount()).isEqualTo(1); } @Test @@ -45,7 +43,7 @@ public void testNegativeValues() QuantileDigest digest = new QuantileDigest(1); addAll(digest, asList(-1, -2, -3, -4, -5, 0, 1, 2, 3, 4, 5)); - assertEquals(digest.getCount(), (double) 11); + assertThat(digest.getCount()).isEqualTo((double) 11); } @Test @@ -58,10 +56,10 @@ public void testRepeatedValue() digest.validate(); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); - assertEquals(digest.getCount(), (double) 2); - assertEquals(digest.getNodeCount(), 1); + assertThat(digest.getCount()).isEqualTo((double) 2); + assertThat(digest.getNodeCount()).isEqualTo(1); } @Test @@ -74,9 +72,9 @@ public void testTwoDistinctValues() digest.validate(); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); - assertEquals(digest.getCount(), (double) 2); - assertEquals(digest.getNodeCount(), 3); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); + assertThat(digest.getCount()).isEqualTo((double) 2); + assertThat(digest.getNodeCount()).isEqualTo(3); } @Test @@ -87,7 +85,7 @@ public void testTreeBuilding() List values = asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7); addAll(digest, values); - assertEquals(digest.getCount(), (double) values.size()); + assertThat(digest.getCount()).isEqualTo((double) values.size()); } @Test @@ -98,7 +96,7 @@ public void testTreeBuildingReverse() List values = asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7); addAll(digest, Lists.reverse(values)); - assertEquals(digest.getCount(), (double) values.size()); + assertThat(digest.getCount()).isEqualTo((double) values.size()); } @Test @@ -113,9 +111,9 @@ public void testBasicCompression() digest.compress(); digest.validate(); - assertEquals(digest.getCount(), (double) values.size()); - assertEquals(digest.getNodeCount(), 7); - assertEquals(digest.getConfidenceFactor(), 0.2); + assertThat(digest.getCount()).isEqualTo((double) values.size()); + assertThat(digest.getNodeCount()).isEqualTo(7); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.2); } @Test @@ -140,19 +138,19 @@ public void testQuantile() addAll(digest, asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); - assertEquals(digest.getQuantile(0.0), 0); - assertEquals(digest.getQuantile(0.1), 1); - assertEquals(digest.getQuantile(0.2), 2); - assertEquals(digest.getQuantile(0.3), 3); - assertEquals(digest.getQuantile(0.4), 4); - assertEquals(digest.getQuantile(0.5), 5); - assertEquals(digest.getQuantile(0.6), 6); - assertEquals(digest.getQuantile(0.7), 7); - assertEquals(digest.getQuantile(0.8), 8); - assertEquals(digest.getQuantile(0.9), 9); - assertEquals(digest.getQuantile(1), 9); + assertThat(digest.getQuantile(0.0)).isEqualTo(0); + assertThat(digest.getQuantile(0.1)).isEqualTo(1); + assertThat(digest.getQuantile(0.2)).isEqualTo(2); + assertThat(digest.getQuantile(0.3)).isEqualTo(3); + assertThat(digest.getQuantile(0.4)).isEqualTo(4); + assertThat(digest.getQuantile(0.5)).isEqualTo(5); + assertThat(digest.getQuantile(0.6)).isEqualTo(6); + assertThat(digest.getQuantile(0.7)).isEqualTo(7); + assertThat(digest.getQuantile(0.8)).isEqualTo(8); + assertThat(digest.getQuantile(0.9)).isEqualTo(9); + assertThat(digest.getQuantile(1)).isEqualTo(9); } @Test @@ -162,17 +160,15 @@ public void testQuantileLowerBound() addRange(digest, 1, 100); - assertEquals(digest.getQuantileLowerBound(0.0), 1); + assertThat(digest.getQuantileLowerBound(0.0)).isEqualTo(1); for (int i = 1; i <= 10; i++) { - assertTrue(digest.getQuantileLowerBound(i / 10.0) <= i * 10); + assertThat(digest.getQuantileLowerBound(i / 10.0) <= i * 10).isTrue(); if (i > 5) { - assertTrue(digest.getQuantileLowerBound(i / 10.0) >= (i - 5) * 10); + assertThat(digest.getQuantileLowerBound(i / 10.0) >= (i - 5) * 10).isTrue(); } } - assertEquals( - digest.getQuantilesLowerBound(ImmutableList.of(0.0, 0.1, 0.2)), - ImmutableList.of(digest.getQuantileLowerBound(0.0), digest.getQuantileLowerBound(0.1), digest.getQuantileLowerBound(0.2))); + assertThat(digest.getQuantilesLowerBound(ImmutableList.of(0.0, 0.1, 0.2))).isEqualTo(ImmutableList.of(digest.getQuantileLowerBound(0.0), digest.getQuantileLowerBound(0.1), digest.getQuantileLowerBound(0.2))); } @Test @@ -182,17 +178,15 @@ public void testQuantileUpperBound() addRange(digest, 1, 100); - assertEquals(digest.getQuantileUpperBound(1.0), 99); + assertThat(digest.getQuantileUpperBound(1.0)).isEqualTo(99); for (int i = 0; i < 10; i++) { - assertTrue(digest.getQuantileUpperBound(i / 10.0) >= i * 10); + assertThat(digest.getQuantileUpperBound(i / 10.0) >= i * 10).isTrue(); if (i < 5) { - assertTrue(digest.getQuantileUpperBound(i / 10.0) <= (i + 5) * 10); + assertThat(digest.getQuantileUpperBound(i / 10.0) <= (i + 5) * 10).isTrue(); } } - assertEquals( - digest.getQuantilesUpperBound(ImmutableList.of(0.8, 0.9, 1.0)), - ImmutableList.of(digest.getQuantileUpperBound(0.8), digest.getQuantileUpperBound(0.9), digest.getQuantileUpperBound(1.0))); + assertThat(digest.getQuantilesUpperBound(ImmutableList.of(0.8, 0.9, 1.0))).isEqualTo(ImmutableList.of(digest.getQuantileUpperBound(0.8), digest.getQuantileUpperBound(0.9), digest.getQuantileUpperBound(1.0))); } @Test @@ -207,19 +201,19 @@ public void testWeightedValues() digest.validate(); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); - assertEquals(digest.getQuantile(0.0), 0); - assertEquals(digest.getQuantile(0.1), 0); - assertEquals(digest.getQuantile(0.2), 0); - assertEquals(digest.getQuantile(0.3), 2); - assertEquals(digest.getQuantile(0.4), 4); - assertEquals(digest.getQuantile(0.5), 4); - assertEquals(digest.getQuantile(0.6), 4); - assertEquals(digest.getQuantile(0.7), 4); - assertEquals(digest.getQuantile(0.8), 4); - assertEquals(digest.getQuantile(0.9), 5); - assertEquals(digest.getQuantile(1), 5); + assertThat(digest.getQuantile(0.0)).isEqualTo(0); + assertThat(digest.getQuantile(0.1)).isEqualTo(0); + assertThat(digest.getQuantile(0.2)).isEqualTo(0); + assertThat(digest.getQuantile(0.3)).isEqualTo(2); + assertThat(digest.getQuantile(0.4)).isEqualTo(4); + assertThat(digest.getQuantile(0.5)).isEqualTo(4); + assertThat(digest.getQuantile(0.6)).isEqualTo(4); + assertThat(digest.getQuantile(0.7)).isEqualTo(4); + assertThat(digest.getQuantile(0.8)).isEqualTo(4); + assertThat(digest.getQuantile(0.9)).isEqualTo(5); + assertThat(digest.getQuantile(1)).isEqualTo(5); } @Test @@ -231,10 +225,9 @@ public void testBatchQuantileQuery() addAll(digest, asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); - assertEquals(digest.getQuantiles(asList(0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)), - asList(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 9L)); + assertThat(digest.getQuantiles(asList(0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0))).isEqualTo(asList(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 9L)); } @Test @@ -246,31 +239,28 @@ public void testHistogramQuery() addAll(digest, asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); - - assertEquals(digest.getHistogram(asList(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L)), - asList(new QuantileDigest.Bucket(0, Double.NaN), - new QuantileDigest.Bucket(1, 0), - new QuantileDigest.Bucket(1, 1), - new QuantileDigest.Bucket(1, 2), - new QuantileDigest.Bucket(1, 3), - new QuantileDigest.Bucket(1, 4), - new QuantileDigest.Bucket(1, 5), - new QuantileDigest.Bucket(1, 6), - new QuantileDigest.Bucket(1, 7), - new QuantileDigest.Bucket(1, 8), - new QuantileDigest.Bucket(1, 9))); - - assertEquals(digest.getHistogram(asList(7L, 10L)), - asList(new QuantileDigest.Bucket(7, 3), - new QuantileDigest.Bucket(3, 8))); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); + + assertThat(digest.getHistogram(asList(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L))).isEqualTo(asList(new QuantileDigest.Bucket(0, Double.NaN), + new QuantileDigest.Bucket(1, 0), + new QuantileDigest.Bucket(1, 1), + new QuantileDigest.Bucket(1, 2), + new QuantileDigest.Bucket(1, 3), + new QuantileDigest.Bucket(1, 4), + new QuantileDigest.Bucket(1, 5), + new QuantileDigest.Bucket(1, 6), + new QuantileDigest.Bucket(1, 7), + new QuantileDigest.Bucket(1, 8), + new QuantileDigest.Bucket(1, 9))); + + assertThat(digest.getHistogram(asList(7L, 10L))).isEqualTo(asList(new QuantileDigest.Bucket(7, 3), + new QuantileDigest.Bucket(3, 8))); // test some edge conditions - assertEquals(digest.getHistogram(asList(0L)), asList(new QuantileDigest.Bucket(0, Double.NaN))); - assertEquals(digest.getHistogram(asList(9L)), asList(new QuantileDigest.Bucket(9, 4))); - assertEquals(digest.getHistogram(asList(10L)), asList(new QuantileDigest.Bucket(10, 4.5))); - assertEquals(digest.getHistogram(asList(Long.MAX_VALUE)), - asList(new QuantileDigest.Bucket(10, 4.5))); + assertThat(digest.getHistogram(asList(0L))).isEqualTo(asList(new QuantileDigest.Bucket(0, Double.NaN))); + assertThat(digest.getHistogram(asList(9L))).isEqualTo(asList(new QuantileDigest.Bucket(9, 4))); + assertThat(digest.getHistogram(asList(10L))).isEqualTo(asList(new QuantileDigest.Bucket(10, 4.5))); + assertThat(digest.getHistogram(asList(Long.MAX_VALUE))).isEqualTo(asList(new QuantileDigest.Bucket(10, 4.5))); } @Test @@ -283,7 +273,7 @@ public void testHistogramOfDoublesQuery() .boxed() .forEach(digest::add); - assertEquals(digest.getConfidenceFactor(), 0.0); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); List bucketUpperBounds = LongStream.range(-10, 10) .map(TestQuantileDigest::doubleToSortableLong) @@ -306,26 +296,18 @@ public void testHistogramOfDoublesQuery() .map(i -> new QuantileDigest.Bucket(1, i - 1)) .collect(Collectors.toList()); expected.add(0, new QuantileDigest.Bucket(0, Double.NaN)); - assertEquals(digest.getHistogram(bucketUpperBounds, middleFunction), - expected); + assertThat(digest.getHistogram(bucketUpperBounds, middleFunction)).isEqualTo(expected); - assertEquals(digest.getHistogram(asList(doubleToSortableLong(7), doubleToSortableLong(10)), middleFunction), - asList(new QuantileDigest.Bucket(17, -2.0), - new QuantileDigest.Bucket(3, 8))); + assertThat(digest.getHistogram(asList(doubleToSortableLong(7), doubleToSortableLong(10)), middleFunction)).isEqualTo(asList(new QuantileDigest.Bucket(17, -2.0), + new QuantileDigest.Bucket(3, 8))); // edge cases - assertEquals(digest.getHistogram(asList(doubleToSortableLong(-1 * Double.MAX_VALUE)), middleFunction), - asList(new QuantileDigest.Bucket(0, Double.NaN))); - assertEquals(digest.getHistogram(asList(doubleToSortableLong(-1 * Double.MAX_VALUE), doubleToSortableLong(-1 * Double.MAX_VALUE + 1)), middleFunction), - asList(new QuantileDigest.Bucket(0, Double.NaN), new QuantileDigest.Bucket(0, Double.NaN))); - assertEquals(digest.getHistogram(asList(doubleToSortableLong(0)), middleFunction), - asList(new QuantileDigest.Bucket(10.0, -5.5))); - assertEquals(digest.getHistogram(asList(doubleToSortableLong(9)), middleFunction), - asList(new QuantileDigest.Bucket(19, -1.0))); - assertEquals(digest.getHistogram(asList(doubleToSortableLong(10)), middleFunction), - asList(new QuantileDigest.Bucket(20, -0.5))); - assertEquals(digest.getHistogram(asList(doubleToSortableLong(Double.MAX_VALUE)), middleFunction), - asList(new QuantileDigest.Bucket(20, -0.5))); + assertThat(digest.getHistogram(asList(doubleToSortableLong(-1 * Double.MAX_VALUE)), middleFunction)).isEqualTo(asList(new QuantileDigest.Bucket(0, Double.NaN))); + assertThat(digest.getHistogram(asList(doubleToSortableLong(-1 * Double.MAX_VALUE), doubleToSortableLong(-1 * Double.MAX_VALUE + 1)), middleFunction)).isEqualTo(asList(new QuantileDigest.Bucket(0, Double.NaN), new QuantileDigest.Bucket(0, Double.NaN))); + assertThat(digest.getHistogram(asList(doubleToSortableLong(0)), middleFunction)).isEqualTo(asList(new QuantileDigest.Bucket(10.0, -5.5))); + assertThat(digest.getHistogram(asList(doubleToSortableLong(9)), middleFunction)).isEqualTo(asList(new QuantileDigest.Bucket(19, -1.0))); + assertThat(digest.getHistogram(asList(doubleToSortableLong(10)), middleFunction)).isEqualTo(asList(new QuantileDigest.Bucket(20, -0.5))); + assertThat(digest.getHistogram(asList(doubleToSortableLong(Double.MAX_VALUE)), middleFunction)).isEqualTo(asList(new QuantileDigest.Bucket(20, -0.5))); } @Test @@ -338,7 +320,7 @@ public void testHistogramQueryAfterCompression() addRange(digest, 0, total); // compression should've run at this error rate and count - assertTrue(digest.getConfidenceFactor() > 0.0); + assertThat(digest.getConfidenceFactor() > 0.0).isTrue(); double actualMaxError = digest.getConfidenceFactor(); @@ -346,7 +328,7 @@ public void testHistogramQueryAfterCompression() QuantileDigest.Bucket bucket = digest.getHistogram(asList(value)).get(0); // estimated count should have an absolute error smaller than 2 * maxError * N - assertTrue(Math.abs(bucket.getCount() - value) < 2 * actualMaxError * total); + assertThat(Math.abs(bucket.getCount() - value) < 2 * actualMaxError * total).isTrue(); } } @@ -361,8 +343,8 @@ public void testQuantileQueryError() addRange(digest, 0, count); // compression should've run at this error rate and count - assertTrue(digest.getConfidenceFactor() > 0); - assertTrue(digest.getConfidenceFactor() < maxError); + assertThat(digest.getConfidenceFactor() > 0).isTrue(); + assertThat(digest.getConfidenceFactor() < maxError).isTrue(); for (int value = 0; value < count; ++value) { double quantile = value * 1.0 / count; @@ -372,7 +354,7 @@ public void testQuantileQueryError() // we've inserted a list of ordered numbers starting at 0 double error = Math.abs(estimatedValue - quantile * count) * 1.0 / count; - assertTrue(error < maxError); + assertThat(error < maxError).isTrue(); } } @@ -386,7 +368,7 @@ public void testDecayedQuantiles() addAll(digest, asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); ticker.increment(60, TimeUnit.SECONDS); addAll(digest, asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)); @@ -394,7 +376,7 @@ public void testDecayedQuantiles() // Considering that the first 10 values now have a weight of 0.5 per the alpha factor, they only contributed a count // of 5 to rank computations. Therefore, the 50th percentile is equivalent to a weighted rank of (5 + 10) / 2 = 7.5, // which corresponds to value 12 - assertEquals(digest.getQuantile(0.5), 12); + assertThat(digest.getQuantile(0.5)).isEqualTo(12); } @Test @@ -407,12 +389,12 @@ public void testDecayedCounts() addAll(digest, asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)); // should have no compressions with so few values and the allowed error - assertEquals(digest.getConfidenceFactor(), 0.0); + assertThat(digest.getConfidenceFactor()).isEqualTo(0.0); ticker.increment(60, TimeUnit.SECONDS); addAll(digest, asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)); - assertEquals(digest.getCount(), 15.0); + assertThat(digest.getCount()).isEqualTo(15.0); } @Test @@ -429,7 +411,7 @@ public void testDecayedCountsWithClockIncrementSmallerThanRescaleThreshold() ticker.increment(targetAgeInSeconds, TimeUnit.SECONDS); addAll(digest, asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19)); - assertEquals(digest.getCount(), 15.0); + assertThat(digest.getCount()).isEqualTo(15.0); } @Test @@ -442,8 +424,8 @@ public void testMinMax() int to = 700; addRange(digest, from, to + 1); - assertEquals(digest.getMin(), from); - assertEquals(digest.getMax(), to); + assertThat(digest.getMin()).isEqualTo(from); + assertThat(digest.getMax()).isEqualTo(to); } @Test @@ -465,8 +447,8 @@ public void testMinMaxWithDecay() digest.validate(); - assertEquals(digest.getMin(), from); - assertEquals(digest.getMax(), to); + assertThat(digest.getMin()).isEqualTo(from); + assertThat(digest.getMax()).isEqualTo(to); } @Test @@ -488,7 +470,7 @@ public void testRescaleWithDecayKeepsCompactTree() ticker.increment(targetAgeInSeconds, TimeUnit.SECONDS); } - assertEquals(digest.getNodeCount(), 1); + assertThat(digest.getNodeCount()).isEqualTo(1); } @Test @@ -498,7 +480,7 @@ public void testEquivalenceEmpty() QuantileDigest a = new QuantileDigest(0.01); QuantileDigest b = new QuantileDigest(0.01); - assertTrue(a.equivalent(b)); + assertThat(a.equivalent(b)).isTrue(); } @Test @@ -511,7 +493,7 @@ public void testEquivalenceSingle() a.add(1); b.add(1); - assertTrue(a.equivalent(b)); + assertThat(a.equivalent(b)).isTrue(); } @Test @@ -524,7 +506,7 @@ public void testEquivalenceSingleDifferent() a.add(1); b.add(2); - assertFalse(a.equivalent(b)); + assertThat(a.equivalent(b)).isFalse(); } @Test @@ -537,7 +519,7 @@ public void testEquivalenceComplex() addAll(a, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7)); addAll(b, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7)); - assertTrue(a.equivalent(b)); + assertThat(a.equivalent(b)).isTrue(); } @Test @@ -550,7 +532,7 @@ public void testEquivalenceComplexDifferent() addAll(a, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7)); addAll(b, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8)); - assertFalse(a.equivalent(b)); + assertThat(a.equivalent(b)).isFalse(); } @Test @@ -566,13 +548,13 @@ public void testMergeEmpty() a.validate(); b.validate(); - assertTrue(b.equivalent(pristineB)); + assertThat(b.equivalent(pristineB)).isTrue(); - assertEquals(a.getCount(), 0.0); - assertEquals(a.getNodeCount(), 0); + assertThat(a.getCount()).isEqualTo(0.0); + assertThat(a.getNodeCount()).isEqualTo(0); - assertEquals(b.getCount(), 0.0); - assertEquals(b.getNodeCount(), 0); + assertThat(b.getCount()).isEqualTo(0.0); + assertThat(b.getNodeCount()).isEqualTo(0); } @Test @@ -591,13 +573,13 @@ public void testMergeIntoEmpty() a.validate(); b.validate(); - assertTrue(b.equivalent(pristineB)); + assertThat(b.equivalent(pristineB)).isTrue(); - assertEquals(a.getCount(), 1.0); - assertEquals(a.getNodeCount(), 1); + assertThat(a.getCount()).isEqualTo(1.0); + assertThat(a.getNodeCount()).isEqualTo(1); - assertEquals(b.getCount(), 1.0); - assertEquals(b.getNodeCount(), 1); + assertThat(b.getCount()).isEqualTo(1.0); + assertThat(b.getNodeCount()).isEqualTo(1); } @Test @@ -614,13 +596,13 @@ public void testMergeWithEmpty() a.validate(); b.validate(); - assertTrue(b.equivalent(pristineB)); + assertThat(b.equivalent(pristineB)).isTrue(); - assertEquals(a.getCount(), 1.0); - assertEquals(a.getNodeCount(), 1); + assertThat(a.getCount()).isEqualTo(1.0); + assertThat(a.getNodeCount()).isEqualTo(1); - assertEquals(b.getCount(), 0.0); - assertEquals(b.getNodeCount(), 0); + assertThat(b.getCount()).isEqualTo(0.0); + assertThat(b.getNodeCount()).isEqualTo(0); } @Test @@ -637,8 +619,8 @@ public void testMergeSample() a.validate(); - assertEquals(a.getCount(), 3.0); - assertEquals(a.getNodeCount(), 5); + assertThat(a.getCount()).isEqualTo(3.0); + assertThat(a.getNodeCount()).isEqualTo(5); } @Test @@ -656,13 +638,13 @@ public void testMergeSeparateBranches() a.merge(b); - assertTrue(b.equivalent(pristineB)); + assertThat(b.equivalent(pristineB)).isTrue(); - assertEquals(a.getCount(), 2.0); - assertEquals(a.getNodeCount(), 3); + assertThat(a.getCount()).isEqualTo(2.0); + assertThat(a.getNodeCount()).isEqualTo(3); - assertEquals(b.getCount(), 1.0); - assertEquals(b.getNodeCount(), 1); + assertThat(b.getCount()).isEqualTo(1.0); + assertThat(b.getNodeCount()).isEqualTo(1); } @Test @@ -686,10 +668,10 @@ public void testMergeWithLowerLevel() a.merge(b); - assertTrue(b.equivalent(pristineB)); + assertThat(b.equivalent(pristineB)).isTrue(); - assertEquals(a.getCount(), 14.0); - assertEquals(b.getCount(), 13.0); + assertThat(a.getCount()).isEqualTo(14.0); + assertThat(b.getCount()).isEqualTo(13.0); } @Test @@ -709,13 +691,13 @@ public void testMergeWithHigherLevel() a.merge(b); - assertTrue(b.equivalent(pristineB)); + assertThat(b.equivalent(pristineB)).isTrue(); - assertEquals(a.getCount(), 15.0); - assertEquals(a.getNodeCount(), 7); + assertThat(a.getCount()).isEqualTo(15.0); + assertThat(a.getNodeCount()).isEqualTo(7); - assertEquals(b.getCount(), 2.0); - assertEquals(b.getNodeCount(), 3); + assertThat(b.getCount()).isEqualTo(2.0); + assertThat(b.getNodeCount()).isEqualTo(3); } // test merging two digests that have a node at the highest level to make sure @@ -736,10 +718,10 @@ public void testMergeMaxLevel() a.validate(); b.validate(); - assertTrue(b.equivalent(pristineB)); + assertThat(b.equivalent(pristineB)).isTrue(); - assertEquals(a.getCount(), 4.0); - assertEquals(a.getNodeCount(), 7); + assertThat(a.getCount()).isEqualTo(4.0); + assertThat(a.getNodeCount()).isEqualTo(7); } @Test @@ -756,13 +738,13 @@ public void testMergeSameLevel() a.merge(b); - assertTrue(b.equivalent(pristineB)); + assertThat(b.equivalent(pristineB)).isTrue(); - assertEquals(a.getCount(), 2.0); - assertEquals(a.getNodeCount(), 1); + assertThat(a.getCount()).isEqualTo(2.0); + assertThat(a.getNodeCount()).isEqualTo(1); - assertEquals(b.getCount(), 1.0); - assertEquals(b.getNodeCount(), 1); + assertThat(b.getCount()).isEqualTo(1.0); + assertThat(b.getNodeCount()).isEqualTo(1); } @Test @@ -772,7 +754,7 @@ public void testSerializationEmpty() QuantileDigest digest = new QuantileDigest(0.01); QuantileDigest deserialized = deserialize(digest.serialize()); - assertTrue(digest.equivalent(deserialized)); + assertThat(digest.equivalent(deserialized)).isTrue(); } @Test @@ -782,7 +764,7 @@ public void testSerializationSingle() QuantileDigest digest = new QuantileDigest(0.01); digest.add(1); - assertTrue(digest.equivalent(deserialize(digest.serialize()))); + assertThat(digest.equivalent(deserialize(digest.serialize()))).isTrue(); } @Test @@ -792,11 +774,11 @@ public void testSerializationComplex() QuantileDigest digest = new QuantileDigest(1); addAll(digest, asList(0, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7)); - assertTrue(digest.equivalent(deserialize(digest.serialize()))); + assertThat(digest.equivalent(deserialize(digest.serialize()))).isTrue(); digest.compress(); - assertTrue(digest.equivalent(deserialize(digest.serialize()))); + assertThat(digest.equivalent(deserialize(digest.serialize()))).isTrue(); } @Test @@ -807,11 +789,11 @@ public void testSerializationWithExtremeEndsOfLong() digest.add(Long.MIN_VALUE); digest.add(Long.MAX_VALUE); - assertTrue(digest.equivalent(deserialize(digest.serialize()))); + assertThat(digest.equivalent(deserialize(digest.serialize()))).isTrue(); digest.compress(); - assertTrue(digest.equivalent(deserialize(digest.serialize()))); + assertThat(digest.equivalent(deserialize(digest.serialize()))).isTrue(); } @Test(invocationCount = 1000) @@ -827,7 +809,7 @@ public void testSerializationRandom() addAll(digest, values); - assertTrue(digest.equivalent(deserialize(digest.serialize())), format("Serialization roundtrip failed for input: %s", values)); + assertThat(digest.equivalent(deserialize(digest.serialize()))).as(format("Serialization roundtrip failed for input: %s", values)).isTrue(); } private QuantileDigest deserialize(Slice serialized) diff --git a/stats/src/test/java/io/airlift/stats/TestTDigest.java b/stats/src/test/java/io/airlift/stats/TestTDigest.java index 25a724ec163..7eb4ccd0f69 100644 --- a/stats/src/test/java/io/airlift/stats/TestTDigest.java +++ b/stats/src/test/java/io/airlift/stats/TestTDigest.java @@ -29,9 +29,9 @@ import static com.google.common.collect.ImmutableList.toImmutableList; import static java.util.Arrays.asList; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; public class TestTDigest { @@ -39,13 +39,13 @@ public class TestTDigest public void testEmpty() { TDigest digest = new TDigest(); - assertTrue(Double.isNaN(digest.valueAt(0.5))); - assertTrue(Double.isNaN(digest.getMin())); - assertTrue(Double.isNaN(digest.getMax())); + assertThat(Double.isNaN(digest.valueAt(0.5))).isTrue(); + assertThat(Double.isNaN(digest.getMin())).isTrue(); + assertThat(Double.isNaN(digest.getMax())).isTrue(); double[] quantiles = new double[] {0.1, 0.2, 0.5, 0.9}; double[] expected = new double[] {Double.NaN, Double.NaN, Double.NaN, Double.NaN}; - assertEquals(digest.valuesAt(quantiles), expected); - assertEquals(digest.valuesAt(Doubles.asList(quantiles)), Doubles.asList(expected)); + assertThat(digest.valuesAt(quantiles)).isEqualTo(expected); + assertThat(digest.valuesAt(Doubles.asList(quantiles))).isEqualTo(Doubles.asList(expected)); } @Test @@ -59,7 +59,7 @@ public void testMonotonicity() double previous = -1; for (double quantile = 0; quantile <= 1; quantile += 1e-5) { double value = digest.valueAt(quantile); - assertTrue(value >= previous); + assertThat(value >= previous).isTrue(); previous = value; } } @@ -73,11 +73,11 @@ public void testBigJump() } digest.add(1_000_000); - assertEquals(digest.valueAt(0.89999999), 18.0); - assertEquals(digest.valueAt(0.9), 19.0); - assertEquals(digest.valueAt(0.949999999), 19.0); - assertEquals(digest.valueAt(0.95), 1_000_000.0); - assertEquals(digest.valuesAt(0.89999999, 0.9, 0.949999999, 0.95), new double[] {18.0, 19.0, 19.0, 1_000_000.0}); + assertThat(digest.valueAt(0.89999999)).isEqualTo(18.0); + assertThat(digest.valueAt(0.9)).isEqualTo(19.0); + assertThat(digest.valueAt(0.949999999)).isEqualTo(19.0); + assertThat(digest.valueAt(0.95)).isEqualTo(1_000_000.0); + assertThat(digest.valuesAt(0.89999999, 0.9, 0.949999999, 0.95)).isEqualTo(new double[] {18.0, 19.0, 19.0, 1_000_000.0}); } @Test @@ -89,9 +89,9 @@ public void testBigJumpWithMerge() } digest.add(1_000_000); - assertEquals(digest.valueAt(0.998), 999.0); - assertEquals(digest.valueAt(0.999), 1_000_000.0); - assertEquals(digest.valuesAt(0.998, 0.999), new double[] {999.0, 1_000_000.0}); + assertThat(digest.valueAt(0.998)).isEqualTo(999.0); + assertThat(digest.valueAt(0.999)).isEqualTo(1_000_000.0); + assertThat(digest.valuesAt(0.998, 0.999)).isEqualTo(new double[] {999.0, 1_000_000.0}); } @Test @@ -100,16 +100,16 @@ public void testSmallCountQuantile() TDigest digest = new TDigest(200); addAll(digest, Lists.newArrayList(15, 20, 32, 60)); - assertEquals(digest.valueAt(0.4), 20, 1e-10); - assertEquals(digest.valueAt(0.25), 20, 1e-10); - assertEquals(digest.valueAt(0.25 - 1e-10), 15, 1e-10); - assertEquals(digest.valueAt(0.5 - 1e-10), 20, 1e-10); - assertEquals(digest.valueAt(0.5), 32, 1e-10); + assertThat(digest.valueAt(0.4)).isCloseTo(20, within(1e-10)); + assertThat(digest.valueAt(0.25)).isCloseTo(20, within(1e-10)); + assertThat(digest.valueAt(0.25 - 1e-10)).isCloseTo(15, within(1e-10)); + assertThat(digest.valueAt(0.5 - 1e-10)).isCloseTo(20, within(1e-10)); + assertThat(digest.valueAt(0.5)).isCloseTo(32, within(1e-10)); double[] quantiles = new double[] {0.25 - 1e-10, 0.25, 0.4, 0.5 - 1e-10, 0.5}; double[] values = digest.valuesAt(quantiles); for (int i = 0; i < quantiles.length; i++) { - assertEquals(values[i], digest.valueAt(quantiles[i])); + assertThat(values[i]).isEqualTo(digest.valueAt(quantiles[i])); } } @@ -134,8 +134,8 @@ public void testSingletonQuantiles() .map(digest::valueAt) .collect(toImmutableList()); List valuesAtQuantilesMultiple = digest.valuesAt(quantiles); - assertEquals(expectedValues, valuesAtQuantilesSingle); - assertEquals(expectedValues, valuesAtQuantilesMultiple); + assertThat(expectedValues).isEqualTo(valuesAtQuantilesSingle); + assertThat(expectedValues).isEqualTo(valuesAtQuantilesMultiple); } @Test @@ -145,10 +145,10 @@ public void testSingleValue() double value = ThreadLocalRandom.current().nextDouble() * 1000; digest.add(value); - assertEquals(digest.valueAt(0), value, 0.001f); - assertEquals(digest.valueAt(0.5), value, 0.001f); - assertEquals(digest.valueAt(1), value, 0.001f); - assertEquals(digest.valuesAt(0d, 0.5d, 1d), new double[] {digest.valueAt(0), digest.valueAt(0.5), digest.valueAt(1)}); + assertThat(digest.valueAt(0)).isCloseTo(value, within(0.001)); + assertThat(digest.valueAt(0.5)).isCloseTo(value, within(0.001)); + assertThat(digest.valueAt(1)).isCloseTo(value, within(0.001)); + assertThat(digest.valuesAt(0d, 0.5d, 1d)).isEqualTo(new double[] {digest.valueAt(0), digest.valueAt(0.5), digest.valueAt(1)}); } @Test @@ -158,11 +158,11 @@ public void testWeight() digest.add(1, 80); digest.add(2, 20); - assertEquals(digest.valueAt(0), 1.0); - assertEquals(digest.valueAt(0.3), 1.0); - assertEquals(digest.valueAt(0.9), 2.0); - assertEquals(digest.valueAt(1), 2.0); - assertEquals(digest.valuesAt(0d, 0.3d, 0.9d, 1d), new double[] {1.0, 1.0, 2.0, 2.0}); + assertThat(digest.valueAt(0)).isEqualTo(1.0); + assertThat(digest.valueAt(0.3)).isEqualTo(1.0); + assertThat(digest.valueAt(0.9)).isEqualTo(2.0); + assertThat(digest.valueAt(1)).isEqualTo(2.0); + assertThat(digest.valuesAt(0d, 0.3d, 0.9d, 1d)).isEqualTo(new double[] {1.0, 1.0, 2.0, 2.0}); } @Test @@ -174,7 +174,7 @@ public void testFirstInnerAndLastCentroid() digest.add(3); digest.add(4); - assertEquals(digest.valuesAt(0d, 0.6d, 1d), new double[] {1.0, 3.0, 4.0}); + assertThat(digest.valuesAt(0d, 0.6d, 1d)).isEqualTo(new double[] {1.0, 3.0, 4.0}); } @Test @@ -187,8 +187,8 @@ public void testSerializationEmpty() // ensure the internal arrays are initialized properly deserialized.add(10); - assertEquals(deserialized.getCount(), 1.0); - assertEquals(deserialized.valueAt(0.5), 10.0); + assertThat(deserialized.getCount()).isEqualTo(1.0); + assertThat(deserialized.valueAt(0.5)).isEqualTo(10.0); } @Test @@ -200,8 +200,8 @@ public void testSerializationSingle() TDigest deserialized = TDigest.deserialize(digest.serialize()); assertSimilar(deserialized, digest); - assertEquals(deserialized.valueAt(0), digest.valueAt(0)); - assertEquals(deserialized.valueAt(1), digest.valueAt(1)); + assertThat(deserialized.valueAt(0)).isEqualTo(digest.valueAt(0)); + assertThat(deserialized.valueAt(1)).isEqualTo(digest.valueAt(1)); } @Test @@ -215,7 +215,7 @@ public void testSerializationComplex() assertSimilar(deserialized, digest); for (double quantile = 0; quantile <= 1; quantile += 0.1) { - assertEquals(deserialized.valueAt(quantile), digest.valueAt(quantile)); + assertThat(deserialized.valueAt(quantile)).isEqualTo(digest.valueAt(quantile)); } } @@ -236,7 +236,7 @@ public void testSerializationRandom() assertSimilar(deserialized, digest); for (double quantile = 0; quantile <= 1; quantile += 0.1) { - assertEquals(deserialized.valueAt(quantile), digest.valueAt(quantile)); + assertThat(deserialized.valueAt(quantile)).isEqualTo(digest.valueAt(quantile)); } } @@ -261,7 +261,7 @@ public void testCopy() assertSimilar(copy, digest); for (double quantile = 0; quantile <= 1; quantile += 0.1) { - assertEquals(copy.valueAt(quantile), digest.valueAt(quantile)); + assertThat(copy.valueAt(quantile)).isEqualTo(digest.valueAt(quantile)); } } @@ -274,8 +274,8 @@ public void testCopyEmpty() // ensure the internal arrays are initialized properly copy.add(10); - assertEquals(copy.getCount(), 1.0); - assertEquals(copy.valueAt(0.5), 10.0); + assertThat(copy.getCount()).isEqualTo(1.0); + assertThat(copy.valueAt(0.5)).isEqualTo(10.0); } @Test @@ -290,13 +290,13 @@ public void testMerge() TDigest merged = TDigest.copyOf(first); merged.mergeWith(second); - assertEquals(merged.getMin(), 1.0); - assertEquals(merged.getMax(), 8.0); - assertEquals(merged.getCount(), 10.0); + assertThat(merged.getMin()).isEqualTo(1.0); + assertThat(merged.getMax()).isEqualTo(8.0); + assertThat(merged.getCount()).isEqualTo(10.0); - assertEquals(merged.valueAt(0), 1.0); - assertEquals(merged.valueAt(0.5), 5.0); - assertEquals(merged.valueAt(1), 8.0); + assertThat(merged.valueAt(0)).isEqualTo(1.0); + assertThat(merged.valueAt(0.5)).isEqualTo(5.0); + assertThat(merged.valueAt(1)).isEqualTo(8.0); } @Test @@ -310,7 +310,7 @@ public void testUnmergeable() // validate the assumption int centroids = digest.getCentroidCount(); digest.forceMerge(); - assertEquals(digest.getCentroidCount(), centroids, "Assumption that digest is not mergeable no longer holds"); + assertThat(digest.getCentroidCount()).as("Assumption that digest is not mergeable no longer holds").isEqualTo(centroids); for (int i = 0; i < 1000; i++) { // add some values somewhere in the middle of the distribution @@ -324,12 +324,12 @@ public void testTwoValueTDigest() TDigest digest = new TDigest(); digest.add(10, 99999.999999999); digest.add(10, 99999.999999999); - assertEquals(10.0, digest.valueAt(0.75)); + assertThat(10.0).isEqualTo(digest.valueAt(0.75)); digest = new TDigest(); digest.add(10, 99999.999999999); digest.add(20, 99999.999999999); - assertEquals(20.0, digest.valueAt(0.75)); + assertThat(20.0).isEqualTo(digest.valueAt(0.75)); } @Test @@ -338,9 +338,9 @@ public void testValuesAtSimpleCases() TDigest digest = new TDigest(); // empty quantiles list - assertEquals(ImmutableList.of(), digest.valuesAt(ImmutableList.of())); - assertEquals(new double[0], digest.valuesAt()); - assertEquals(new double[0], digest.valuesAt(new double[0])); + assertThat(ImmutableList.of()).isEqualTo(digest.valuesAt(ImmutableList.of())); + assertThat(new double[0]).isEqualTo(digest.valuesAt()); + assertThat(new double[0]).isEqualTo(digest.valuesAt(new double[0])); // quantiles not sorted assertThrows(IllegalArgumentException.class, () -> digest.valuesAt(ImmutableList.of(0.9, 0.1))); @@ -349,11 +349,11 @@ public void testValuesAtSimpleCases() assertThrows(IllegalArgumentException.class, () -> digest.valuesAt(ImmutableList.of(-0.9, 0.9))); // empty digest - assertEquals(ImmutableList.of(Double.NaN, Double.NaN), digest.valuesAt(ImmutableList.of(0.5, 0.75))); + assertThat(ImmutableList.of(Double.NaN, Double.NaN)).isEqualTo(digest.valuesAt(ImmutableList.of(0.5, 0.75))); // single centroid digest.add(10); - assertEquals(ImmutableList.of(10.0, 10.0, 10.0, 10.0), digest.valuesAt(ImmutableList.of(0.0, 0.5, 0.75, 1.0))); + assertThat(ImmutableList.of(10.0, 10.0, 10.0, 10.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.0, 0.5, 0.75, 1.0))); } @Test @@ -362,28 +362,28 @@ public void testValuesAt() TDigest digest = new TDigest(); addAll(digest, ImmutableList.of(10, 20, 30, 40)); // quantiles at centroid borders - assertEquals(ImmutableList.of(10.0, 20.0, 30.0, 40.0, 40.0), digest.valuesAt(ImmutableList.of(0.0, 0.25, 0.5, 0.75, 1.0))); + assertThat(ImmutableList.of(10.0, 20.0, 30.0, 40.0, 40.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.0, 0.25, 0.5, 0.75, 1.0))); // quantiles inside centroids - assertEquals(ImmutableList.of(10.0, 10.0, 20.0, 20.0, 30.0, 30.0, 40.0, 40.0), digest.valuesAt(ImmutableList.of(0.001, 0.249, 0.251, 0.499, 0.501, 0.749, 0.751, 0.999))); + assertThat(ImmutableList.of(10.0, 10.0, 20.0, 20.0, 30.0, 30.0, 40.0, 40.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.001, 0.249, 0.251, 0.499, 0.501, 0.749, 0.751, 0.999))); digest = new TDigest(); digest.add(10, 2); digest.add(20, 2); // min value and value at offset 1 - assertEquals(ImmutableList.of(10.0, 10.0), digest.valuesAt(ImmutableList.of(0.1, 0.25))); + assertThat(ImmutableList.of(10.0, 10.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.1, 0.25))); // short-circuit to last centroid - assertEquals(ImmutableList.of(20.0, 20.0), digest.valuesAt(ImmutableList.of(0.9, 1.0))); - assertEquals(ImmutableList.of(20.0, 20.0), digest.valuesAt(ImmutableList.of(0.75, 1.0))); + assertThat(ImmutableList.of(20.0, 20.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.9, 1.0))); + assertThat(ImmutableList.of(20.0, 20.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.75, 1.0))); // pass through the structure until last centroid - assertEquals(ImmutableList.of(15.0, 20.0), digest.valuesAt(ImmutableList.of(0.5, 1.0))); + assertThat(ImmutableList.of(15.0, 20.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.5, 1.0))); digest = new TDigest(); digest.add(10, 4); digest.add(20, 4); // min value and value at offset 1 - assertEquals(ImmutableList.of(10.0, 10.0), digest.valuesAt(ImmutableList.of(0.1, 0.125))); + assertThat(ImmutableList.of(10.0, 10.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.1, 0.125))); // short-circuit to last centroid - assertEquals(ImmutableList.of(20.0, 20.0, 20.0), digest.valuesAt(ImmutableList.of(0.75, 0.875, 1.0))); + assertThat(ImmutableList.of(20.0, 20.0, 20.0)).isEqualTo(digest.valuesAt(ImmutableList.of(0.75, 0.875, 1.0))); digest = new TDigest(); digest.add(10, 4); @@ -392,7 +392,7 @@ public void testValuesAt() digest.add(40, 2); digest.add(50, 2); // single-element vs multi-element clusters - assertEquals(ImmutableList.of(19.5, 20.0, 20.0, 30.0, 30.0, 30.999999999999996, 44.5, 45.50000000000001), digest.valuesAt(ImmutableList.of(0.39, 0.41, 0.49, 0.51, 0.59, 0.61, 0.79, 0.81))); + assertThat(ImmutableList.of(19.5, 20.0, 20.0, 30.0, 30.0, 30.999999999999996, 44.5, 45.50000000000001)).isEqualTo(digest.valuesAt(ImmutableList.of(0.39, 0.41, 0.49, 0.51, 0.59, 0.61, 0.79, 0.81))); } private void addAll(TDigest digest, List values) @@ -404,9 +404,9 @@ private void addAll(TDigest digest, List values) private void assertSimilar(TDigest actual, TDigest expected) { - assertEquals(actual.getMin(), expected.getMin()); - assertEquals(actual.getMax(), expected.getMax()); - assertEquals(actual.getCount(), expected.getCount()); + assertThat(actual.getMin()).isEqualTo(expected.getMin()); + assertThat(actual.getMax()).isEqualTo(expected.getMax()); + assertThat(actual.getCount()).isEqualTo(expected.getCount()); } private static double interpolate(double x, double x0, double y0, double x1, double y1) diff --git a/stats/src/test/java/io/airlift/stats/TestTestingGcMonitor.java b/stats/src/test/java/io/airlift/stats/TestTestingGcMonitor.java index d116c89802d..3065bfed673 100644 --- a/stats/src/test/java/io/airlift/stats/TestTestingGcMonitor.java +++ b/stats/src/test/java/io/airlift/stats/TestTestingGcMonitor.java @@ -5,7 +5,7 @@ import org.testng.annotations.Test; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestTestingGcMonitor { @@ -15,17 +15,17 @@ public void test() { TestingGcMonitor gcMonitor = new TestingGcMonitor(); - assertEquals(gcMonitor.getMajorGcCount(), 0); - assertEquals(gcMonitor.getMajorGcTime(), new Duration(0, SECONDS)); + assertThat(gcMonitor.getMajorGcCount()).isEqualTo(0); + assertThat(gcMonitor.getMajorGcTime()).isEqualTo(new Duration(0, SECONDS)); gcMonitor.recordMajorGc(new Duration(3, SECONDS)); - assertEquals(gcMonitor.getMajorGcCount(), 1); - assertEquals(gcMonitor.getMajorGcTime(), new Duration(3, SECONDS)); + assertThat(gcMonitor.getMajorGcCount()).isEqualTo(1); + assertThat(gcMonitor.getMajorGcTime()).isEqualTo(new Duration(3, SECONDS)); gcMonitor.recordMajorGc(new Duration(7, SECONDS)); - assertEquals(gcMonitor.getMajorGcCount(), 2); - assertEquals(gcMonitor.getMajorGcTime(), new Duration(10, SECONDS)); + assertThat(gcMonitor.getMajorGcCount()).isEqualTo(2); + assertThat(gcMonitor.getMajorGcTime()).isEqualTo(new Duration(10, SECONDS)); } } diff --git a/stats/src/test/java/io/airlift/stats/TestTimeStat.java b/stats/src/test/java/io/airlift/stats/TestTimeStat.java index 3b49efb099a..22b79c787ef 100644 --- a/stats/src/test/java/io/airlift/stats/TestTimeStat.java +++ b/stats/src/test/java/io/airlift/stats/TestTimeStat.java @@ -27,11 +27,10 @@ import static com.google.common.math.DoubleMath.fuzzyEquals; import static java.lang.Math.min; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.within; import static org.testng.Assert.assertThrows; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; @Test(singleThreaded = true) public class TestTimeStat @@ -60,11 +59,11 @@ public void testBasic() Collections.sort(values); TimeDistribution allTime = stat.getAllTime(); - assertEquals(allTime.getCount(), (double) values.size()); - assertTrue(fuzzyEquals(allTime.getMax(), values.get(values.size() - 1) * 0.001, 0.000_000_000_1)); - assertEquals(allTime.getMin(), values.get(0) * 0.001); - assertEquals(allTime.getAvg(), values.stream().mapToDouble(x -> x).average().getAsDouble() * 0.001, 0.001); - assertEquals(allTime.getUnit(), TimeUnit.SECONDS); + assertThat(allTime.getCount()).isEqualTo((double) values.size()); + assertThat(fuzzyEquals(allTime.getMax(), values.get(values.size() - 1) * 0.001, 0.000_000_000_1)).isTrue(); + assertThat(allTime.getMin()).isEqualTo(values.get(0) * 0.001); + assertThat(allTime.getAvg()).isCloseTo(values.stream().mapToDouble(x -> x).average().getAsDouble() * 0.001, within(0.001)); + assertThat(allTime.getUnit()).isEqualTo(TimeUnit.SECONDS); assertPercentile("tp50", allTime.getP50(), values, 0.50); assertPercentile("tp75", allTime.getP75(), values, 0.75); @@ -84,9 +83,9 @@ public void testAddIllegalDoubles() assertThrows(IllegalArgumentException.class, () -> stat.add(1.0d / 0.0d, TimeUnit.MILLISECONDS)); stat.add(0.0, TimeUnit.MILLISECONDS); // 0.0 is valid - assertEquals(stat.getAllTime().getCount(), 1.0); - assertEquals(stat.getAllTime().getMin(), 0.0); - assertEquals(stat.getAllTime().getMax(), 0.0); + assertThat(stat.getAllTime().getCount()).isEqualTo(1.0); + assertThat(stat.getAllTime().getMin()).isEqualTo(0.0); + assertThat(stat.getAllTime().getMax()).isEqualTo(0.0); } @Test @@ -97,27 +96,27 @@ public void testReset() stat.add(value, TimeUnit.MILLISECONDS); } - assertEquals(stat.getAllTime().getCount(), (double) VALUES); - assertEquals(stat.getOneMinute().getCount(), (double) VALUES); - assertEquals(stat.getFiveMinutes().getCount(), (double) VALUES); - assertEquals(stat.getFifteenMinutes().getCount(), (double) VALUES); + assertThat(stat.getAllTime().getCount()).isEqualTo((double) VALUES); + assertThat(stat.getOneMinute().getCount()).isEqualTo((double) VALUES); + assertThat(stat.getFiveMinutes().getCount()).isEqualTo((double) VALUES); + assertThat(stat.getFifteenMinutes().getCount()).isEqualTo((double) VALUES); - assertNotEquals(stat.getAllTime().getAvg(), Double.NaN); - assertNotEquals(stat.getOneMinute().getAvg(), Double.NaN); - assertNotEquals(stat.getFiveMinutes().getAvg(), Double.NaN); - assertNotEquals(stat.getFifteenMinutes().getAvg(), Double.NaN); + assertThat(stat.getAllTime().getAvg()).isNotEqualTo(Double.NaN); + assertThat(stat.getOneMinute().getAvg()).isNotEqualTo(Double.NaN); + assertThat(stat.getFiveMinutes().getAvg()).isNotEqualTo(Double.NaN); + assertThat(stat.getFifteenMinutes().getAvg()).isNotEqualTo(Double.NaN); stat.reset(); - assertEquals(stat.getAllTime().getCount(), 0D); - assertEquals(stat.getOneMinute().getCount(), 0D); - assertEquals(stat.getFiveMinutes().getCount(), 0D); - assertEquals(stat.getFifteenMinutes().getCount(), 0D); + assertThat(stat.getAllTime().getCount()).isEqualTo(0D); + assertThat(stat.getOneMinute().getCount()).isEqualTo(0D); + assertThat(stat.getFiveMinutes().getCount()).isEqualTo(0D); + assertThat(stat.getFifteenMinutes().getCount()).isEqualTo(0D); - assertEquals(stat.getAllTime().getAvg(), Double.NaN); - assertEquals(stat.getOneMinute().getAvg(), Double.NaN); - assertEquals(stat.getFiveMinutes().getAvg(), Double.NaN); - assertEquals(stat.getFifteenMinutes().getAvg(), Double.NaN); + assertThat(stat.getAllTime().getAvg()).isEqualTo(Double.NaN); + assertThat(stat.getOneMinute().getAvg()).isEqualTo(Double.NaN); + assertThat(stat.getFiveMinutes().getAvg()).isEqualTo(Double.NaN); + assertThat(stat.getFifteenMinutes().getAvg()).isEqualTo(Double.NaN); } @Test @@ -125,13 +124,13 @@ public void testEmpty() { TimeStat stat = new TimeStat(); TimeDistribution allTime = stat.getAllTime(); - assertEquals(allTime.getMin(), Double.NaN); - assertEquals(allTime.getMax(), Double.NaN); - assertEquals(allTime.getP50(), Double.NaN); - assertEquals(allTime.getP75(), Double.NaN); - assertEquals(allTime.getP90(), Double.NaN); - assertEquals(allTime.getP99(), Double.NaN); - assertEquals(allTime.getAvg(), Double.NaN); + assertThat(allTime.getMin()).isEqualTo(Double.NaN); + assertThat(allTime.getMax()).isEqualTo(Double.NaN); + assertThat(allTime.getP50()).isEqualTo(Double.NaN); + assertThat(allTime.getP75()).isEqualTo(Double.NaN); + assertThat(allTime.getP90()).isEqualTo(Double.NaN); + assertThat(allTime.getP99()).isEqualTo(Double.NaN); + assertThat(allTime.getAvg()).isEqualTo(Double.NaN); } @Test @@ -152,13 +151,13 @@ public void time() fail("Exception should have been thrown"); } catch (Exception e) { - assertEquals(e.getMessage(), "thrown by time"); + assertThat(e.getMessage()).isEqualTo("thrown by time"); } TimeDistribution allTime = stat.getAllTime(); - assertEquals(allTime.getCount(), 2.0); - assertEquals(allTime.getMin(), 0.010); - assertEquals(allTime.getMax(), 0.020); + assertThat(allTime.getCount()).isEqualTo(2.0); + assertThat(allTime.getMin()).isEqualTo(0.010); + assertThat(allTime.getMax()).isEqualTo(0.020); } @Test @@ -171,9 +170,9 @@ public void timeTry() } TimeDistribution allTime = stat.getAllTime(); - assertEquals(allTime.getCount(), 1.0); - assertEquals(allTime.getMin(), 0.010); - assertEquals(allTime.getMax(), 0.010); + assertThat(allTime.getCount()).isEqualTo(1.0); + assertThat(allTime.getMin()).isEqualTo(0.010); + assertThat(allTime.getMax()).isEqualTo(0.010); } @Test @@ -183,8 +182,8 @@ public void testUnit() stat.add(1, TimeUnit.SECONDS); TimeDistribution allTime = stat.getAllTime(); - assertEquals(allTime.getMin(), 1000.0); - assertEquals(allTime.getMax(), 1000.0); + assertThat(allTime.getMin()).isEqualTo(1000.0); + assertThat(allTime.getMax()).isEqualTo(1000.0); } @Test @@ -195,9 +194,9 @@ public void testAddNanos() stat.addNanos(1L); TimeDistribution allTime = stat.getAllTime(); - assertEquals(allTime.getMin(), 1.0); - assertEquals(allTime.getMax(), 1000000.0); - assertEquals(allTime.getCount(), 2.0); + assertThat(allTime.getMin()).isEqualTo(1.0); + assertThat(allTime.getMax()).isEqualTo(1000000.0); + assertThat(allTime.getCount()).isEqualTo(2.0); assertThrows(IllegalArgumentException.class, () -> stat.addNanos(-1)); } diff --git a/stats/src/test/java/io/airlift/stats/TimedStatTest.java b/stats/src/test/java/io/airlift/stats/TimedStatTest.java index fd3f2902771..a5011200881 100644 --- a/stats/src/test/java/io/airlift/stats/TimedStatTest.java +++ b/stats/src/test/java/io/airlift/stats/TimedStatTest.java @@ -27,9 +27,8 @@ import static io.airlift.testing.Assertions.assertGreaterThanOrEqual; import static java.lang.Math.min; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; @SuppressWarnings("deprecation") public class TimedStatTest @@ -50,10 +49,10 @@ public void testBasic() } Collections.sort(values); - assertEquals(stat.getCount(), values.size()); - assertEquals(stat.getMax(), values.get(values.size() - 1)); - assertEquals(stat.getMin(), values.get(0)); - assertEquals(stat.getMean(), (values.get(0) + values.get(values.size() - 1)) / 2.0); + assertThat(stat.getCount()).isEqualTo(values.size()); + assertThat(stat.getMax()).isEqualTo(values.get(values.size() - 1)); + assertThat(stat.getMin()).isEqualTo(values.get(0)); + assertThat(stat.getMean()).isEqualTo((values.get(0) + values.get(values.size() - 1)) / 2.0); assertPercentile("tp50", stat.getTP50(), values, 0.50); assertPercentile("tp90", stat.getTP90(), values, 0.90); @@ -68,14 +67,14 @@ public void testBasic() public void testEmpty() { TimedStat stat = new TimedStat(); - assertTrue(Double.isNaN(stat.getMin())); - assertTrue(Double.isNaN(stat.getMax())); - assertTrue(Double.isNaN(stat.getTP50())); - assertTrue(Double.isNaN(stat.getTP90())); - assertTrue(Double.isNaN(stat.getTP99())); - assertTrue(Double.isNaN(stat.getTP999())); - assertTrue(Double.isNaN(stat.getPercentile(0.80))); - assertTrue(Double.isNaN(stat.getPercentile(0.20))); + assertThat(Double.isNaN(stat.getMin())).isTrue(); + assertThat(Double.isNaN(stat.getMax())).isTrue(); + assertThat(Double.isNaN(stat.getTP50())).isTrue(); + assertThat(Double.isNaN(stat.getTP90())).isTrue(); + assertThat(Double.isNaN(stat.getTP99())).isTrue(); + assertThat(Double.isNaN(stat.getTP999())).isTrue(); + assertThat(Double.isNaN(stat.getPercentile(0.80))).isTrue(); + assertThat(Double.isNaN(stat.getPercentile(0.20))).isTrue(); } @Test @@ -88,8 +87,8 @@ public void time() return null; }); - assertEquals(stat.getCount(), 1); - assertEquals(stat.getMin(), stat.getMax()); + assertThat(stat.getCount()).isEqualTo(1); + assertThat(stat.getMin()).isEqualTo(stat.getMax()); assertGreaterThanOrEqual(stat.getMax(), 10.0); } diff --git a/stats/src/test/java/io/airlift/stats/cardinality/TestDenseHll.java b/stats/src/test/java/io/airlift/stats/cardinality/TestDenseHll.java index fb1dfa783e5..6efb90bf621 100644 --- a/stats/src/test/java/io/airlift/stats/cardinality/TestDenseHll.java +++ b/stats/src/test/java/io/airlift/stats/cardinality/TestDenseHll.java @@ -22,7 +22,7 @@ import static io.airlift.slice.testing.SliceAssertions.assertSlicesEqual; import static io.airlift.stats.cardinality.TestUtils.sequence; import static io.airlift.stats.cardinality.Utils.numberOfBuckets; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestDenseHll { @@ -49,10 +49,10 @@ public void testMultipleMerges(int prefixBitLength) merged.mergeWith(current); for (int i = 0; i < numberOfBuckets(prefixBitLength); i++) { - assertEquals(single.getValue(i), merged.getValue(i)); + assertThat(single.getValue(i)).isEqualTo(merged.getValue(i)); } - assertEquals(single.cardinality(), merged.cardinality()); + assertThat(single.cardinality()).isEqualTo(merged.cardinality()); } @Test(dataProvider = "bits") @@ -164,14 +164,14 @@ private static void verifyMerge(int prefixBitLength, List one, List hll1.mergeWith(hll2); hll1.verify(); - assertEquals(hll1.cardinality(), expected.cardinality()); + assertThat(hll1.cardinality()).isEqualTo(expected.cardinality()); assertSlicesEqual(hll1.serialize(), expected.serialize()); } private static void assertSameBuckets(TestingHll testingHll, DenseHll hll) { for (int i = 0; i < testingHll.getBuckets().length; i++) { - assertEquals(hll.getValue(i), testingHll.getBuckets()[i]); + assertThat(hll.getValue(i)).isEqualTo(testingHll.getBuckets()[i]); } } diff --git a/stats/src/test/java/io/airlift/stats/cardinality/TestDenseSerialization.java b/stats/src/test/java/io/airlift/stats/cardinality/TestDenseSerialization.java index d80fbbc6938..9889e2fe358 100644 --- a/stats/src/test/java/io/airlift/stats/cardinality/TestDenseSerialization.java +++ b/stats/src/test/java/io/airlift/stats/cardinality/TestDenseSerialization.java @@ -21,7 +21,7 @@ import static io.airlift.slice.testing.SliceAssertions.assertSlicesEqual; import static io.airlift.stats.cardinality.Utils.numberOfBuckets; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestDenseSerialization { @@ -261,7 +261,7 @@ public void testDeserializeDenseV1NoOverflows() DenseHll deserialized = new DenseHll(serialized); for (int i = 0; i < numberOfBuckets; i++) { - assertEquals(deserialized.getValue(i), 10); + assertThat(deserialized.getValue(i)).isEqualTo(10); } deserialized.verify(); } @@ -289,10 +289,10 @@ public void testDeserializeDenseV1EmptyOverflow() DenseHll deserialized = new DenseHll(serialized); for (int i = 0; i < numberOfBuckets; i++) { if (i == 1) { - assertEquals(deserialized.getValue(i), 17); + assertThat(deserialized.getValue(i)).isEqualTo(17); } else { - assertEquals(deserialized.getValue(i), 2); + assertThat(deserialized.getValue(i)).isEqualTo(2); } } deserialized.verify(); @@ -321,10 +321,10 @@ public void testDeserializeDenseV1Overflow() DenseHll deserialized = new DenseHll(serialized); for (int i = 0; i < numberOfBuckets; i++) { if (i == 1) { - assertEquals(deserialized.getValue(i), 20); + assertThat(deserialized.getValue(i)).isEqualTo(20); } else { - assertEquals(deserialized.getValue(i), 2); + assertThat(deserialized.getValue(i)).isEqualTo(2); } } deserialized.verify(); diff --git a/stats/src/test/java/io/airlift/stats/cardinality/TestHyperLogLog.java b/stats/src/test/java/io/airlift/stats/cardinality/TestHyperLogLog.java index 4e2b9d5a035..a26fbbd2380 100644 --- a/stats/src/test/java/io/airlift/stats/cardinality/TestHyperLogLog.java +++ b/stats/src/test/java/io/airlift/stats/cardinality/TestHyperLogLog.java @@ -25,8 +25,7 @@ import static io.airlift.slice.testing.SliceAssertions.assertSlicesEqual; import static io.airlift.stats.cardinality.TestUtils.sequence; import static java.lang.Math.toIntExact; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestHyperLogLog { @@ -65,12 +64,11 @@ public void testEstimates() for (Map.Entry entry : errors.entrySet()) { // Give an extra error margin. This is mostly a sanity check to catch egregious errors - assertTrue(entry.getValue().stdev() <= expectedStandardError * 1.1, - String.format("Failed at p = %s, cardinality = %s. Expected std error = %s, actual = %s", - indexBits, - entry.getKey(), - expectedStandardError, - entry.getValue().stdev())); + assertThat(entry.getValue().stdev() <= expectedStandardError * 1.1).as(String.format("Failed at p = %s, cardinality = %s. Expected std error = %s, actual = %s", + indexBits, + entry.getKey(), + expectedStandardError, + entry.getValue().stdev())).isTrue(); } } } @@ -79,9 +77,7 @@ public void testEstimates() public void testRetainedSize() throws Exception { - assertEquals( - HyperLogLog.newInstance(8).estimatedInMemorySize(), - toIntExact(instanceSize(HyperLogLog.class) + (new SparseHll(10)).estimatedInMemorySize())); + assertThat(HyperLogLog.newInstance(8).estimatedInMemorySize()).isEqualTo(toIntExact(instanceSize(HyperLogLog.class) + (new SparseHll(10)).estimatedInMemorySize())); } @Test @@ -124,8 +120,8 @@ private void verifyMerge(List one, List two) hll1.mergeWith(hll2); hll1.verify(); - assertEquals(hll1.cardinality(), expected.cardinality()); - assertEquals(hll1.serialize(), expected.serialize()); + assertThat(hll1.cardinality()).isEqualTo(expected.cardinality()); + assertThat(hll1.serialize()).isEqualTo(expected.serialize()); } @Test @@ -153,7 +149,7 @@ private void verifyRoundtrip(List sequence) HyperLogLog deserialized = HyperLogLog.newInstance(serialized); deserialized.verify(); - assertEquals(hll.cardinality(), deserialized.cardinality()); + assertThat(hll.cardinality()).isEqualTo(deserialized.cardinality()); Slice reserialized = deserialized.serialize(); assertSlicesEqual(serialized, reserialized); diff --git a/stats/src/test/java/io/airlift/stats/cardinality/TestSparseHll.java b/stats/src/test/java/io/airlift/stats/cardinality/TestSparseHll.java index 3ca1ee3128e..a8ccc7bc881 100644 --- a/stats/src/test/java/io/airlift/stats/cardinality/TestSparseHll.java +++ b/stats/src/test/java/io/airlift/stats/cardinality/TestSparseHll.java @@ -24,6 +24,7 @@ import static io.airlift.slice.SizeOf.sizeOf; import static io.airlift.slice.testing.SliceAssertions.assertSlicesEqual; import static io.airlift.stats.cardinality.TestUtils.sequence; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertEquals; public class TestSparseHll @@ -91,7 +92,7 @@ public void testRetainedSize() entries = new int[value + 10]; retainedSize = sizeOf(entries) + SPARSE_HLL_INSTANCE_SIZE; } - assertEquals(sparseHll.estimatedInMemorySize(), retainedSize); + assertThat(sparseHll.estimatedInMemorySize()).isEqualTo(retainedSize); } } @@ -120,7 +121,7 @@ private static void verifyMerge(int prefixBitLength, List one, List hll1.mergeWith(hll2); hll1.verify(); - assertEquals(hll1.cardinality(), expected.cardinality()); + assertThat(hll1.cardinality()).isEqualTo(expected.cardinality()); assertSlicesEqual(hll1.serialize(), expected.serialize()); } diff --git a/testing/pom.xml b/testing/pom.xml index b3a09a8fe32..029bca7c8fc 100644 --- a/testing/pom.xml +++ b/testing/pom.xml @@ -36,6 +36,12 @@ hibernate-validator + + org.assertj + assertj-core + test + + org.testng diff --git a/testing/src/test/java/io/airlift/testing/TestAssertions.java b/testing/src/test/java/io/airlift/testing/TestAssertions.java index d82cd7f1b6a..cd2ffb7443e 100644 --- a/testing/src/test/java/io/airlift/testing/TestAssertions.java +++ b/testing/src/test/java/io/airlift/testing/TestAssertions.java @@ -35,10 +35,8 @@ import static io.airlift.testing.Assertions.assertLessThanOrEqual; import static io.airlift.testing.TestAssertions.SubComparable.createSubComparable; import static io.airlift.testing.TestAssertions.SuperComparable.createSuperComparable; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; public class TestAssertions { @@ -471,36 +469,36 @@ public void failBetweenExclusive(Comparable actual, Comparable lowerBound, Compa private void verifyExceptionMessage(AssertionError e, String message, Object... values) { - assertNotNull(e); + assertThat(e).isNotNull(); String actualMessage = e.getMessage(); - assertNotNull(actualMessage); + assertThat(actualMessage).isNotNull(); if (message != null) { - assertTrue(actualMessage.startsWith(message + " ")); + assertThat(actualMessage.startsWith(message + " ")).isTrue(); } else { - assertFalse(actualMessage.startsWith(" ")); + assertThat(actualMessage.startsWith(" ")).isFalse(); } for (Object value : values) { - assertTrue(actualMessage.contains("<" + value + ">")); + assertThat(actualMessage.contains("<" + value + ">")).isTrue(); } } private void verifyExceptionMessageList(AssertionError e, String message, Iterable... lists) { - assertNotNull(e); + assertThat(e).isNotNull(); String actualMessage = e.getMessage(); - assertNotNull(actualMessage); + assertThat(actualMessage).isNotNull(); if (message != null) { - assertTrue(actualMessage.startsWith(message + " ")); + assertThat(actualMessage.startsWith(message + " ")).isTrue(); } else { - assertFalse(actualMessage.startsWith(" ")); + assertThat(actualMessage.startsWith(" ")).isFalse(); } for (Iterable values : lists) { for (Object value : values) { - assertTrue(actualMessage.contains(value.toString())); + assertThat(actualMessage.contains(value.toString())).isTrue(); } } } diff --git a/testing/src/test/java/io/airlift/testing/TestEquivalenceTester.java b/testing/src/test/java/io/airlift/testing/TestEquivalenceTester.java index be7095e2be2..3f83c22d57b 100644 --- a/testing/src/test/java/io/airlift/testing/TestEquivalenceTester.java +++ b/testing/src/test/java/io/airlift/testing/TestEquivalenceTester.java @@ -48,7 +48,7 @@ import static io.airlift.testing.EquivalenceTester.comparisonTester; import static io.airlift.testing.EquivalenceTester.equivalenceTester; import static java.util.Objects.requireNonNull; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.FileAssert.fail; public class TestEquivalenceTester @@ -58,8 +58,8 @@ public void testCheckFailure() { Object o1 = new Object(); Object o2 = new Object(); - assertEquals(new ElementCheckFailure(EQUAL, 0, 0, o1), new ElementCheckFailure(EQUAL, 0, 0, o1)); - assertEquals(new PairCheckFailure(EQUAL, 0, 0, o1, 1, 0, o2), new PairCheckFailure(EQUAL, 0, 0, o1, 1, 0, o2)); + assertThat(new ElementCheckFailure(EQUAL, 0, 0, o1)).isEqualTo(new ElementCheckFailure(EQUAL, 0, 0, o1)); + assertThat(new PairCheckFailure(EQUAL, 0, 0, o1, 1, 0, o2)).isEqualTo(new PairCheckFailure(EQUAL, 0, 0, o1, 1, 0, o2)); } @Test diff --git a/testing/src/test/java/io/airlift/testing/TestTempFile.java b/testing/src/test/java/io/airlift/testing/TestTempFile.java index 4017261bd44..ac8e2853f26 100644 --- a/testing/src/test/java/io/airlift/testing/TestTempFile.java +++ b/testing/src/test/java/io/airlift/testing/TestTempFile.java @@ -4,9 +4,7 @@ import java.io.File; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestTempFile { @@ -18,25 +16,25 @@ public void testTempFile() TempFile tempFile = new TempFile(); File file = tempFile.file(); - assertEquals(file, tempFile.path().toFile()); - assertTrue(file.exists()); - assertTrue(file.isFile()); - assertTrue(file.canRead()); - assertTrue(file.canWrite()); + assertThat(file).isEqualTo(tempFile.path().toFile()); + assertThat(file.exists()).isTrue(); + assertThat(file.isFile()).isTrue(); + assertThat(file.canRead()).isTrue(); + assertThat(file.canWrite()).isTrue(); tempFile.close(); - assertFalse(file.exists()); + assertThat(file.exists()).isFalse(); // verify close does not delete file again - assertTrue(file.createNewFile()); - assertTrue(file.exists()); + assertThat(file.createNewFile()).isTrue(); + assertThat(file.exists()).isTrue(); tempFile.close(); - assertTrue(file.exists()); + assertThat(file.exists()).isTrue(); - assertTrue(file.delete()); + assertThat(file.delete()).isTrue(); } } diff --git a/testing/src/test/java/io/airlift/testing/TestTestingClock.java b/testing/src/test/java/io/airlift/testing/TestTestingClock.java index 62d32f2a85b..69a77e1fbde 100644 --- a/testing/src/test/java/io/airlift/testing/TestTestingClock.java +++ b/testing/src/test/java/io/airlift/testing/TestTestingClock.java @@ -18,7 +18,7 @@ import java.time.Instant; import static java.util.concurrent.TimeUnit.SECONDS; -import static org.testng.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; public class TestTestingClock { @@ -36,7 +36,7 @@ public void test() clock.increment(42, SECONDS); Instant instant3 = clock.instant(); - assertEquals(instant2, instant1); - assertEquals(instant3, instant1.plusSeconds(42)); + assertThat(instant2).isEqualTo(instant1); + assertThat(instant3).isEqualTo(instant1.plusSeconds(42)); } } diff --git a/testing/src/test/java/io/airlift/testing/TestValidationAssertions.java b/testing/src/test/java/io/airlift/testing/TestValidationAssertions.java index a8ef8544e9d..99ad0864bad 100644 --- a/testing/src/test/java/io/airlift/testing/TestValidationAssertions.java +++ b/testing/src/test/java/io/airlift/testing/TestValidationAssertions.java @@ -23,9 +23,7 @@ import static io.airlift.testing.Assertions.assertContains; import static io.airlift.testing.ValidationAssertions.assertFailsValidation; import static io.airlift.testing.ValidationAssertions.assertValidates; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; public class TestValidationAssertions { @@ -51,7 +49,7 @@ public void testAssertValidatesThrowsWithInvalidObject() ok = true; verifyExceptionMessage(e, null, INVALID_OBJECT, null, null); } - assertTrue(ok, "Expected AssertionError"); + assertThat(ok).as("Expected AssertionError").isTrue(); } @Test @@ -66,7 +64,7 @@ public void testAssertValidatesThrowsWithInvalidObjectWithMessage() // success verifyExceptionMessage(e, MESSAGE, INVALID_OBJECT, null, null); } - assertTrue(ok, "Expected AssertionError"); + assertThat(ok).as("Expected AssertionError").isTrue(); } @Test @@ -93,7 +91,7 @@ public void testTheAssertFailsValidationMethodThrowsWithValidObject() verifyExceptionMessage(e, null, VALID_OBJECT, "value", NotNull.class); } - assertTrue(ok, "Expected AssertionError"); + assertThat(ok).as("Expected AssertionError").isTrue(); } @Test @@ -108,19 +106,19 @@ public void testTheAssertFailsValidationWithMessageMethodThrowsWithValidObject() // success verifyExceptionMessage(e, MESSAGE, VALID_OBJECT, "value", NotNull.class); } - assertTrue(ok, "Expected AssertionError"); + assertThat(ok).as("Expected AssertionError").isTrue(); } private void verifyExceptionMessage(AssertionError e, String message, Object value, String property, Class annotation) { - assertNotNull(e); + assertThat(e).isNotNull(); String actualMessage = e.getMessage(); - assertNotNull(actualMessage); + assertThat(actualMessage).isNotNull(); if (message != null) { - assertTrue(actualMessage.startsWith(message + " ")); + assertThat(actualMessage.startsWith(message + " ")).isTrue(); } else { - assertFalse(actualMessage.startsWith(" ")); + assertThat(actualMessage.startsWith(" ")).isFalse(); } assertContains(actualMessage, "<" + value + ">"); diff --git a/trace-token/pom.xml b/trace-token/pom.xml index e001d095aca..4c4fe9f40ce 100644 --- a/trace-token/pom.xml +++ b/trace-token/pom.xml @@ -20,6 +20,12 @@ guice + + org.assertj + assertj-core + test + + org.testng diff --git a/trace-token/src/test/java/io/airlift/tracetoken/TestTraceTokenManager.java b/trace-token/src/test/java/io/airlift/tracetoken/TestTraceTokenManager.java index 4ddf1be0167..754170ead3c 100644 --- a/trace-token/src/test/java/io/airlift/tracetoken/TestTraceTokenManager.java +++ b/trace-token/src/test/java/io/airlift/tracetoken/TestTraceTokenManager.java @@ -17,9 +17,7 @@ import org.testng.annotations.Test; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; public class TestTraceTokenManager { @@ -27,7 +25,7 @@ public class TestTraceTokenManager public void testNoToken() { TraceTokenManager manager = new TraceTokenManager(); - assertNull(manager.getCurrentRequestToken()); + assertThat(manager.getCurrentRequestToken()).isNull(); } @Test @@ -36,12 +34,12 @@ public void testCreateToken() TraceTokenManager manager = new TraceTokenManager(); String token = manager.createAndRegisterNewRequestToken(); - assertEquals(manager.getCurrentRequestToken(), token); - assertEquals(manager.getCurrentRequestToken(), token); + assertThat(manager.getCurrentRequestToken()).isEqualTo(token); + assertThat(manager.getCurrentRequestToken()).isEqualTo(token); String token2 = manager.createAndRegisterNewRequestToken(); - assertEquals(manager.getCurrentRequestToken(), token2); - assertNotEquals(token2, token); + assertThat(manager.getCurrentRequestToken()).isEqualTo(token2); + assertThat(token2).isNotEqualTo(token); } @Test @@ -50,7 +48,7 @@ public void testRegisterCustomToken() TraceTokenManager manager = new TraceTokenManager(); manager.registerRequestToken("abc"); - assertEquals(manager.getCurrentRequestToken(), "abc"); + assertThat(manager.getCurrentRequestToken()).isEqualTo("abc"); } @Test @@ -59,9 +57,9 @@ public void testOverrideRequestToken() TraceTokenManager manager = new TraceTokenManager(); String oldToken = manager.createAndRegisterNewRequestToken(); - assertEquals(manager.getCurrentRequestToken(), oldToken); + assertThat(manager.getCurrentRequestToken()).isEqualTo(oldToken); manager.registerRequestToken("abc"); - assertEquals(manager.getCurrentRequestToken(), "abc"); + assertThat(manager.getCurrentRequestToken()).isEqualTo("abc"); } }