From ef376e7976982a768f70fdbb7b9c2f3215ec2a25 Mon Sep 17 00:00:00 2001 From: Jerry Lee Date: Sat, 3 Aug 2024 20:24:02 +0800 Subject: [PATCH] =?UTF-8?q?test:=20clean=20test=20codes=20=F0=9F=A7=B9?= =?UTF-8?q?=F0=9F=92=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../io/foldright/cffu/CffuFactoryTest.java | 122 +++--- .../java/io/foldright/cffu/CffuStateTest.java | 30 -- .../java/io/foldright/cffu/CffuStateTest.kt | 26 ++ .../test/java/io/foldright/cffu/CffuTest.java | 74 ++-- .../java/io/foldright/cffu/CffuTestHelper.kt | 16 + .../cffu/CompletableFutureUtilsTest.java | 292 ++++++------- .../cffu/DefaultExecutorTestUtils.java | 16 - .../cffu/ListenableFutureUtilsTest.java | 36 +- .../cffu/spi/ExecutorWrapperProviderTest.kt | 6 +- .../io/foldright/cffu/tuple/TupleTest.java | 2 +- .../CffuApiCompatibilityTest.java | 222 +++++----- ...CompletableFutureApiCompatibilityTest.java | 220 +++++----- .../demo/ConcurrencyStrategyDemo.java | 1 + .../CompletableFutureUsageStudyCaseTest.kt} | 51 +-- .../java/io/foldright/test_utils/TestUtils.kt | 95 ++-- .../foldright/test_utils/TestingConstants.kt | 20 + ...PoolManager.kt => TestingExecutorUtils.kt} | 76 ++-- .../TypeParameterDeclarationTest.java | 22 +- .../foldright/cffu/test/CffuExtensionsTest.kt | 408 +++++++++--------- .../test/CompletableFutureExtensionsTest.kt | 162 ++++--- .../test/ListenableFutureExtensionsKtTest.kt | 10 +- scripts/gen_CffuApiCompatibilityTest.sh | 47 +- 22 files changed, 974 insertions(+), 980 deletions(-) delete mode 100644 cffu-core/src/test/java/io/foldright/cffu/CffuStateTest.java create mode 100644 cffu-core/src/test/java/io/foldright/cffu/CffuStateTest.kt create mode 100644 cffu-core/src/test/java/io/foldright/cffu/CffuTestHelper.kt delete mode 100644 cffu-core/src/test/java/io/foldright/cffu/DefaultExecutorTestUtils.java rename cffu-core/src/test/java/io/foldright/{showcases/CompletableFutureUsageShowcaseTest.kt => study/CompletableFutureUsageStudyCaseTest.kt} (91%) create mode 100644 cffu-core/src/test/java/io/foldright/test_utils/TestingConstants.kt rename cffu-core/src/test/java/io/foldright/test_utils/{TestThreadPoolManager.kt => TestingExecutorUtils.kt} (67%) diff --git a/cffu-core/src/test/java/io/foldright/cffu/CffuFactoryTest.java b/cffu-core/src/test/java/io/foldright/cffu/CffuFactoryTest.java index ad9fbe15..55939ab9 100644 --- a/cffu-core/src/test/java/io/foldright/cffu/CffuFactoryTest.java +++ b/cffu-core/src/test/java/io/foldright/cffu/CffuFactoryTest.java @@ -4,9 +4,8 @@ import io.foldright.cffu.tuple.Tuple3; import io.foldright.cffu.tuple.Tuple4; import io.foldright.cffu.tuple.Tuple5; -import io.foldright.test_utils.TestThreadPoolManager; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import io.foldright.test_utils.TestUtils; +import io.foldright.test_utils.TestingExecutorUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.JRE; @@ -17,10 +16,11 @@ import java.util.concurrent.*; import java.util.function.Supplier; +import static io.foldright.cffu.CffuTestHelper.unwrapMadeExecutor; import static io.foldright.cffu.CompletableFutureUtils.failedFuture; import static io.foldright.cffu.CompletableFutureUtils.toCompletableFutureArray; -import static io.foldright.cffu.DefaultExecutorTestUtils.unwrapMadeExecutor; import static io.foldright.test_utils.TestUtils.*; +import static io.foldright.test_utils.TestingConstants.*; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.ForkJoinPool.commonPool; import static java.util.function.Function.identity; @@ -28,9 +28,9 @@ /** - * see io.foldright.compatibility_test.CffuApiCompatibilityTest + * @see io.foldright.compatibility_test.CffuApiCompatibilityTest */ -@SuppressWarnings("RedundantThrows") +@SuppressWarnings({"RedundantThrows", "DataFlowIssue", "JavadocReference"}) class CffuFactoryTest { //////////////////////////////////////////////////////////////////////////////// // region# Constructor Method @@ -53,7 +53,7 @@ void test_newIncompleteCffu() { @Test void test_mRun() throws Exception { - final Runnable runnable = () -> sleep(100); + final Runnable runnable = TestUtils::snoreZzz; final long tick = System.currentTimeMillis(); @SuppressWarnings("unchecked") @@ -73,7 +73,7 @@ void test_mRun() throws Exception { @Test void test_mSupply() throws Exception { final Supplier supplier = () -> { - sleep(100); + snoreZzz(); return n; }; @@ -120,24 +120,24 @@ void test_mSupply() throws Exception { @Test void test_tupleMSupplyAsync() throws Exception { final Supplier supplier_n = () -> { - sleep(100); + snoreZzz(); return n; }; final Supplier supplier_s = () -> { - sleep(100); + snoreZzz(); return s; }; final Supplier supplier_d = () -> { - sleep(100); + snoreZzz(); return d; }; final Supplier supplier_an = () -> { - sleep(100); + snoreZzz(); return anotherN; }; final Supplier supplier_nn = () -> { - sleep(100); + snoreZzz(); return n + n; }; @@ -172,24 +172,24 @@ void test_tupleMSupplyAsync() throws Exception { @Test void test_tupleMSupplyMostSuccessAsync() throws Exception { final Supplier supplier_n = () -> { - sleep(10); + nap(); return n; }; final Supplier supplier_s = () -> { - sleep(10); + nap(); return s; }; final Supplier supplier_d = () -> { - sleep(10); + nap(); return d; }; final Supplier supplier_an = () -> { - sleep(10); + nap(); return anotherN; }; final Supplier supplier_nn = () -> { - sleep(10); + nap(); return n + n; }; assertEquals(Tuple2.of(n, s), cffuFactory.tupleMSupplyMostSuccessAsync(100, TimeUnit.MILLISECONDS, supplier_n, supplier_s).get()); @@ -312,8 +312,8 @@ void test_mostOf() throws Exception { final Cffu completed = cffuFactory.completedFuture(n); final CompletionStage completedStage = cffuFactory.completedStage(n); final Cffu failed = cffuFactory.failedFuture(rte); - final Cffu cancelled = cffuFactory.toCffu(createCancelledFuture()); - final Cffu incomplete = cffuFactory.toCffu(createIncompleteFuture()); + final Cffu cancelled = cffuFactory.toCffu(cancelledFuture()); + final Cffu incomplete = cffuFactory.toCffu(incompleteCf()); assertEquals(0, cffuFactory.mostSuccessResultsOf(null, 10, TimeUnit.MILLISECONDS).get().size()); @@ -340,9 +340,9 @@ void test_mostOf() throws Exception { //////////////////////////////////////////////////////////////////////////////// @Test - void test_anyOf() throws Exception { + void test_anyOf_anySuccessOf() throws Exception { assertEquals(n, cffuFactory.anyOf( - createIncompleteFuture(), + incompleteCf(), completedFuture(n) ).get()); assertEquals(n, cffuFactory.anyOf( @@ -361,7 +361,7 @@ void test_anyOf() throws Exception { //////////////////////////////////////// - assertEquals(n, cffuFactory.anySuccessOf(createIncompleteFuture(), completedFuture(n)).get()); + assertEquals(n, cffuFactory.anySuccessOf(incompleteCf(), completedFuture(n)).get()); assertEquals(n, cffuFactory.anySuccessOf(completedFuture(n)).get()); assertSame(NoCfsProvidedException.class, cffuFactory.anySuccessOf().exceptionNow().getClass()); @@ -404,16 +404,16 @@ void test_anyOf_exceptionally() throws Exception { // even later cfs normally completed! assertSame(rte, assertThrowsExactly(ExecutionException.class, () -> - cffuFactory.anyOf(createIncompleteFuture(), failedFuture(rte), createIncompleteFuture()).get() + cffuFactory.anyOf(incompleteCf(), failedFuture(rte), incompleteCf()).get() ).getCause()); // first normally completed anyOf cf win, // even later cfs exceptionally completed! assertEquals(n, cffuFactory.anyOf( - createIncompleteFuture(), + incompleteCf(), completedFuture(n), - createIncompleteFuture() + incompleteCf() ).get()); } @@ -424,7 +424,7 @@ void test_anySuccessOf__trivial_case() throws Exception { cffuFactory.newIncompleteCffu(), cffuFactory.newIncompleteCffu(), cffuFactory.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), cffuFactory.completedFuture(n) @@ -434,7 +434,7 @@ void test_anySuccessOf__trivial_case() throws Exception { cffuFactory.newIncompleteCffu(), cffuFactory.newIncompleteCffu(), cffuFactory.supplyAsync(() -> { - sleep(300); + snoreZzz(); throw rte; }), cffuFactory.completedFuture(n) @@ -443,11 +443,11 @@ void test_anySuccessOf__trivial_case() throws Exception { // all success assertEquals(n, cffuFactory.anySuccessOf( cffuFactory.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), cffuFactory.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), cffuFactory.completedFuture(n) @@ -457,20 +457,20 @@ void test_anySuccessOf__trivial_case() throws Exception { // success then success assertEquals(n, cffuFactory.anySuccessOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), completedFuture(n) ).get()); // success then failed assertEquals(n, cffuFactory.anySuccessOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); throw rte; }), completedFuture(n) @@ -479,11 +479,11 @@ void test_anySuccessOf__trivial_case() throws Exception { // all success assertEquals(n, cffuFactory.anySuccessOf( CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), completedFuture(n) @@ -639,8 +639,8 @@ void test_mostSuccessTupleOf() throws Exception { final Cffu completed = cffuFactory.completedFuture(n); final CompletionStage anotherCompleted = cffuFactory.completedStage(s); final Cffu failed = cffuFactory.failedFuture(rte); - final Cffu cancelled = cffuFactory.toCffu(createCancelledFuture()); - final Cffu incomplete = cffuFactory.toCffu(createIncompleteFuture()); + final Cffu cancelled = cffuFactory.toCffu(cancelledFuture()); + final Cffu incomplete = cffuFactory.toCffu(incompleteCf()); assertEquals(Tuple2.of(n, s), cffuFactory.mostSuccessTupleOf( 10, TimeUnit.MILLISECONDS, completed, anotherCompleted @@ -807,15 +807,15 @@ void test_toCffu() throws Exception { assertEquals(n, cf.get()); shouldNotBeMinimalStage(cf); - final Cffu cffu_in = cffuFactory.completedFuture(42); + final Cffu cffu_in = cffuFactory.completedFuture(n); - CffuFactory fac = CffuFactory.builder(anotherExecutorService).forbidObtrudeMethods(true).build(); + CffuFactory fac = CffuFactory.builder(dummyExecutor).forbidObtrudeMethods(true).build(); Cffu cffu = fac.toCffu(cffu_in); assertNotSame(cffu_in, cffu); - assertSame(anotherExecutorService, unwrapMadeExecutor(cffu)); + assertSame(dummyExecutor, unwrapMadeExecutor(cffu)); assertSame(fac, cffu.cffuFactory()); assertEquals("obtrude methods is forbidden by cffu", assertThrowsExactly(UnsupportedOperationException.class, () -> - cffu.obtrudeValue(44) + cffu.obtrudeValue(anotherN) ).getMessage()); assertSame(cffu_in, cffuFactory.toCffu(cffu_in)); @@ -920,12 +920,12 @@ void test_getter() { assertSame(executorService, unwrapMadeExecutor(cffuFactory)); assertFalse(cffuFactory.forbidObtrudeMethods()); - CffuFactory fac = CffuFactory.builder(anotherExecutorService).forbidObtrudeMethods(true).build(); - assertSame(anotherExecutorService, unwrapMadeExecutor(fac)); + CffuFactory fac = CffuFactory.builder(dummyExecutor).forbidObtrudeMethods(true).build(); + assertSame(dummyExecutor, unwrapMadeExecutor(fac)); assertTrue(fac.forbidObtrudeMethods()); - final CffuFactory fac2 = cffuFactory.resetDefaultExecutor(anotherExecutorService); - assertSame(anotherExecutorService, unwrapMadeExecutor(fac2)); + final CffuFactory fac2 = cffuFactory.resetDefaultExecutor(dummyExecutor); + assertSame(dummyExecutor, unwrapMadeExecutor(fac2)); assertEquals(cffuFactory.forbidObtrudeMethods(), fac2.forbidObtrudeMethods()); final CffuFactory fac3 = cffuFactory.resetDefaultExecutor(fac2.defaultExecutor()); @@ -940,7 +940,7 @@ void test_forbidObtrudeMethods_property() { Cffu cf = fac2.newIncompleteCffu(); assertEquals("obtrude methods is forbidden by cffu", assertThrowsExactly(UnsupportedOperationException.class, () -> - cf.obtrudeValue(42)).getMessage() + cf.obtrudeValue(n)).getMessage() ); assertEquals("obtrude methods is forbidden by cffu", assertThrowsExactly(UnsupportedOperationException.class, () -> cf.obtrudeException(rte)).getMessage() @@ -959,31 +959,17 @@ void test_executorSetting_MayBe_ThreadPerTaskExecutor() throws Exception { assertTrue(executorClassName.endsWith("$ThreadPerTaskExecutor")); } - assertEquals(42, fac.supplyAsync(() -> 42).get()); + assertEquals(n, fac.supplyAsync(() -> n).get()); } - // endregion //////////////////////////////////////////////////////////////////////////////// - // region# Test helper methods/fields + // region# Test helper fields //////////////////////////////////////////////////////////////////////////////// - private static CffuFactory cffuFactory; - - private static ExecutorService executorService; - - private static ExecutorService anotherExecutorService; + private final CffuFactory cffuFactory = TestingExecutorUtils.getTestCffuFactory(); - @BeforeAll - static void beforeAll() { - executorService = TestThreadPoolManager.createThreadPool("CffuFactoryTest"); - anotherExecutorService = TestThreadPoolManager.createThreadPool("CffuFactoryTest-Another", true); + private final ExecutorService executorService = TestingExecutorUtils.getTestThreadPoolExecutor(); - cffuFactory = CffuFactory.builder(executorService).build(); - } - - @AfterAll - static void afterAll() { - TestThreadPoolManager.shutdownExecutorService(executorService, anotherExecutorService); - } + private final Executor dummyExecutor = Runnable::run; } diff --git a/cffu-core/src/test/java/io/foldright/cffu/CffuStateTest.java b/cffu-core/src/test/java/io/foldright/cffu/CffuStateTest.java deleted file mode 100644 index f066e09a..00000000 --- a/cffu-core/src/test/java/io/foldright/cffu/CffuStateTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package io.foldright.cffu; - -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.condition.EnabledForJreRange; -import org.junit.jupiter.api.condition.JRE; - -import java.util.concurrent.Future; - -import static org.junit.jupiter.api.Assertions.assertEquals; - - -class CffuStateTest { - @Test - @EnabledForJreRange(min = JRE.JAVA_19) - void toCffuState() { - assertEquals(CffuState.RUNNING, CffuState.toCffuState(Future.State.RUNNING)); - assertEquals(CffuState.SUCCESS, CffuState.toCffuState(Future.State.SUCCESS)); - assertEquals(CffuState.FAILED, CffuState.toCffuState(Future.State.FAILED)); - assertEquals(CffuState.CANCELLED, CffuState.toCffuState(Future.State.CANCELLED)); - } - - @Test - @EnabledForJreRange(min = JRE.JAVA_19) - void toFutureState() { - assertEquals(Future.State.RUNNING, CffuState.RUNNING.toFutureState()); - assertEquals(Future.State.SUCCESS, CffuState.SUCCESS.toFutureState()); - assertEquals(Future.State.FAILED, CffuState.FAILED.toFutureState()); - assertEquals(Future.State.CANCELLED, CffuState.CANCELLED.toFutureState()); - } -} diff --git a/cffu-core/src/test/java/io/foldright/cffu/CffuStateTest.kt b/cffu-core/src/test/java/io/foldright/cffu/CffuStateTest.kt new file mode 100644 index 00000000..cdd9f97f --- /dev/null +++ b/cffu-core/src/test/java/io/foldright/cffu/CffuStateTest.kt @@ -0,0 +1,26 @@ +package io.foldright.cffu + +import io.kotest.matchers.shouldBe +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.condition.EnabledForJreRange +import org.junit.jupiter.api.condition.JRE.JAVA_19 +import java.util.concurrent.Future + +@EnabledForJreRange(min = JAVA_19) +private class CffuStateTest { + @Test + fun toCffuState() { + CffuState.toCffuState(Future.State.RUNNING) shouldBe CffuState.RUNNING + CffuState.toCffuState(Future.State.SUCCESS) shouldBe CffuState.SUCCESS + CffuState.toCffuState(Future.State.FAILED) shouldBe CffuState.FAILED + CffuState.toCffuState(Future.State.CANCELLED) shouldBe CffuState.CANCELLED + } + + @Test + fun toFutureState() { + CffuState.RUNNING.toFutureState() shouldBe Future.State.RUNNING + CffuState.SUCCESS.toFutureState() shouldBe Future.State.SUCCESS + CffuState.FAILED.toFutureState() shouldBe Future.State.FAILED + CffuState.CANCELLED.toFutureState() shouldBe Future.State.CANCELLED + } +} diff --git a/cffu-core/src/test/java/io/foldright/cffu/CffuTest.java b/cffu-core/src/test/java/io/foldright/cffu/CffuTest.java index d7550d7c..239650cc 100644 --- a/cffu-core/src/test/java/io/foldright/cffu/CffuTest.java +++ b/cffu-core/src/test/java/io/foldright/cffu/CffuTest.java @@ -4,9 +4,8 @@ import io.foldright.cffu.tuple.Tuple3; import io.foldright.cffu.tuple.Tuple4; import io.foldright.cffu.tuple.Tuple5; -import io.foldright.test_utils.TestThreadPoolManager; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import io.foldright.test_utils.TestUtils; +import io.foldright.test_utils.TestingExecutorUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.JRE; @@ -18,8 +17,10 @@ import java.util.function.Consumer; import java.util.function.Function; -import static io.foldright.cffu.DefaultExecutorTestUtils.unwrapMadeExecutor; -import static io.foldright.test_utils.TestUtils.*; +import static io.foldright.cffu.CffuTestHelper.unwrapMadeExecutor; +import static io.foldright.test_utils.TestUtils.nap; +import static io.foldright.test_utils.TestUtils.snoreZzz; +import static io.foldright.test_utils.TestingConstants.*; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.function.Function.identity; import static org.junit.jupiter.api.Assertions.*; @@ -53,7 +54,7 @@ void test_thenMApply() throws Exception { final Cffu completed = cffuFactory.completedFuture(n); final Function function_n = (x) -> { - sleep(100); + snoreZzz(); return n; }; @@ -97,7 +98,7 @@ void test_thenMAccept() throws Exception { final Cffu completed = cffuFactory.completedFuture(n); final Consumer consumer = (x) -> { assertEquals(n, x); - sleep(100); + snoreZzz(); }; final long tick = System.currentTimeMillis(); @@ -123,7 +124,7 @@ void test_thenMAccept() throws Exception { @Test void test_thenMRun() throws Exception { final Cffu completed = cffuFactory.completedFuture(null); - final Runnable runnable = () -> sleep(100); + final Runnable runnable = TestUtils::snoreZzz; final long tick = System.currentTimeMillis(); @@ -154,25 +155,25 @@ void test_thenMRun() throws Exception { void test_thenTupleMApplyAsync() throws Exception { final Cffu completed = cffuFactory.completedFuture(n); final Function function_n = (x) -> { - sleep(10); + nap(); return n; }; final Function function_s = (x) -> { - sleep(10); + nap(); return s; }; final Function function_d = (x) -> { - sleep(10); + nap(); return d; }; final Function function_an = (x) -> { - sleep(10); + nap(); return anotherN; }; final Function function_nn = (x) -> { - sleep(10); + nap(); return n + n; }; @@ -221,7 +222,7 @@ void test_thenTupleMApplyAsync() throws Exception { @Test void both_fastFail() throws Exception { Cffu cf = cffuFactory.supplyAsync(() -> { - sleep(2_000); + snoreZzz(2_000); return n; }); final Cffu failed = cffuFactory.failedFuture(rte); @@ -431,17 +432,17 @@ void test_cffuJoin() { // Incomplete Future -> join before timeout Cffu cffu = cffuFactory.supplyAsync(() -> { - sleep(300); - return 42; + snoreZzz(); + return n; }); - assertEquals(42, cffu.join(3, TimeUnit.SECONDS)); + assertEquals(n, cffu.join(3, TimeUnit.SECONDS)); } @Test void test_getSuccessNow() { final Consumer> check = (cf) -> { assertNull(cf.getSuccessNow(null)); - assertEquals(42, cf.getSuccessNow(42)); + assertEquals(n, cf.getSuccessNow(n)); }; Cffu incomplete = cffuFactory.newIncompleteCffu(); @@ -459,7 +460,7 @@ void test_cffuState() { Cffu incomplete = cffuFactory.newIncompleteCffu(); assertEquals(CffuState.RUNNING, incomplete.cffuState()); - assertEquals(CffuState.SUCCESS, cffuFactory.completedFuture(42).cffuState()); + assertEquals(CffuState.SUCCESS, cffuFactory.completedFuture(n).cffuState()); assertEquals(CffuState.FAILED, cffuFactory.failedFuture(rte).cffuState()); incomplete.cancel(false); @@ -498,16 +499,16 @@ void test_resetCffuFactory() { @Test void test_isMinimalStage() { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); assertFalse(cf.isMinimalStage()); - assertTrue(((Cffu) cffuFactory.completedStage(42)).isMinimalStage()); + assertTrue(((Cffu) cffuFactory.completedStage(n)).isMinimalStage()); assertTrue(((Cffu) cffuFactory.failedStage(rte)).isMinimalStage()); assertTrue(((Cffu) cf.minimalCompletionStage()).isMinimalStage()); - assertFalse(forbidObtrudeMethodsCffuFactory.completedFuture(42).isMinimalStage()); - assertTrue(((Cffu) forbidObtrudeMethodsCffuFactory.completedStage(42)).isMinimalStage()); + assertFalse(forbidObtrudeMethodsCffuFactory.completedFuture(n).isMinimalStage()); + assertTrue(((Cffu) forbidObtrudeMethodsCffuFactory.completedStage(n)).isMinimalStage()); assertTrue(((Cffu) forbidObtrudeMethodsCffuFactory.failedStage(rte)).isMinimalStage()); } @@ -541,8 +542,8 @@ void test_cffuUnwrap_9_completedStage() { @Test void test_forbidObtrudeMethods() { - assertFalse(cffuFactory.completedFuture(42).forbidObtrudeMethods()); - assertTrue(forbidObtrudeMethodsCffuFactory.completedFuture(42).forbidObtrudeMethods()); + assertFalse(cffuFactory.completedFuture(n).forbidObtrudeMethods()); + assertTrue(forbidObtrudeMethodsCffuFactory.completedFuture(n).forbidObtrudeMethods()); } //////////////////////////////////////////////////////////////////////////////// @@ -554,7 +555,7 @@ void test_forbidObtrudeMethods() { @Test void test_toString() { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); Cffu cffu = cffuFactory.toCffu(cf); assertTrue(cffu.toString().contains(cf.toString())); @@ -563,25 +564,12 @@ void test_toString() { // endregion //////////////////////////////////////////////////////////////////////////////// - // region# Test helper methods/fields + // region# Test helper fields //////////////////////////////////////////////////////////////////////////////// - private static ExecutorService executorService; - - private static CffuFactory cffuFactory; + private final CffuFactory cffuFactory = TestingExecutorUtils.getTestCffuFactory(); - private static CffuFactory forbidObtrudeMethodsCffuFactory; + private final ExecutorService executorService = TestingExecutorUtils.getTestThreadPoolExecutor(); - @BeforeAll - static void beforeAll() { - executorService = TestThreadPoolManager.createThreadPool("CffuTest"); - - cffuFactory = CffuFactory.builder(executorService).build(); - forbidObtrudeMethodsCffuFactory = CffuFactory.builder(executorService).forbidObtrudeMethods(true).build(); - } - - @AfterAll - static void afterAll() { - TestThreadPoolManager.shutdownExecutorService(executorService); - } + private final CffuFactory forbidObtrudeMethodsCffuFactory = CffuFactory.builder(executorService).forbidObtrudeMethods(true).build(); } diff --git a/cffu-core/src/test/java/io/foldright/cffu/CffuTestHelper.kt b/cffu-core/src/test/java/io/foldright/cffu/CffuTestHelper.kt new file mode 100644 index 00000000..76ae8153 --- /dev/null +++ b/cffu-core/src/test/java/io/foldright/cffu/CffuTestHelper.kt @@ -0,0 +1,16 @@ +@file:JvmName("CffuTestHelper") + +package io.foldright.cffu + +import io.foldright.cffu.CffuFactoryBuilder.CffuMadeExecutor +import java.util.concurrent.Executor + +fun CffuFactory.unwrapMadeExecutor(): Executor { + val executor = defaultExecutor() as CffuMadeExecutor + return executor.unwrap() +} + +fun Cffu<*>.unwrapMadeExecutor(): Executor { + val executor = defaultExecutor() as CffuMadeExecutor + return executor.unwrap() +} diff --git a/cffu-core/src/test/java/io/foldright/cffu/CompletableFutureUtilsTest.java b/cffu-core/src/test/java/io/foldright/cffu/CompletableFutureUtilsTest.java index a2074f47..2bcf6a47 100644 --- a/cffu-core/src/test/java/io/foldright/cffu/CompletableFutureUtilsTest.java +++ b/cffu-core/src/test/java/io/foldright/cffu/CompletableFutureUtilsTest.java @@ -4,9 +4,8 @@ import io.foldright.cffu.tuple.Tuple3; import io.foldright.cffu.tuple.Tuple4; import io.foldright.cffu.tuple.Tuple5; -import io.foldright.test_utils.TestThreadPoolManager; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import io.foldright.test_utils.TestUtils; +import io.foldright.test_utils.TestingExecutorUtils; import org.junit.jupiter.api.Test; import java.util.Arrays; @@ -23,6 +22,8 @@ import static io.foldright.cffu.CompletableFutureUtils.*; import static io.foldright.test_utils.TestUtils.*; +import static io.foldright.test_utils.TestingConstants.*; +import static io.foldright.test_utils.TestingExecutorUtils.assertRunningInExecutor; import static java.lang.Thread.currentThread; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.ForkJoinPool.commonPool; @@ -43,12 +44,11 @@ class CompletableFutureUtilsTest { @Test void test_mSupply() throws Exception { final Supplier supplier = () -> { - sleep(100); + snoreZzz(); return n; }; final long tick = System.currentTimeMillis(); - @SuppressWarnings("unchecked") CompletableFuture>[] cfs = new CompletableFuture[]{ mSupplyFastFailAsync(supplier, supplier), @@ -60,14 +60,13 @@ void test_mSupply() throws Exception { mSupplyAsync(supplier, supplier), mSupplyAsync(executorService, supplier, supplier), }; - assertTrue(System.currentTimeMillis() - tick < 50); + for (CompletableFuture> cf : cfs) { assertEquals(Arrays.asList(n, n), cf.get()); } final long tick1 = System.currentTimeMillis(); - @SuppressWarnings("unchecked") CompletableFuture[] cfs1 = new CompletableFuture[]{ mSupplyAnySuccessAsync(supplier, supplier), @@ -75,8 +74,8 @@ void test_mSupply() throws Exception { mSupplyAnyAsync(supplier, supplier), mSupplyAnyAsync(executorService, supplier, supplier), }; - assertTrue(System.currentTimeMillis() - tick1 < 50); + for (CompletableFuture cf : cfs1) { assertEquals(n, cf.get()); } @@ -84,7 +83,7 @@ void test_mSupply() throws Exception { @Test void test_mRun() throws Exception { - final Runnable runnable = () -> sleep(100); + final Runnable runnable = TestUtils::snoreZzz; final long tick = System.currentTimeMillis(); @SuppressWarnings("unchecked") @@ -98,8 +97,8 @@ void test_mRun() throws Exception { mRunAnyAsync(runnable, runnable), mRunAnyAsync(executorService, runnable, runnable), }; - assertTrue(System.currentTimeMillis() - tick < 50); + for (CompletableFuture cf : cfs) { assertNull(cf.get()); } @@ -113,24 +112,24 @@ void test_mRun() throws Exception { @Test void test_tupleMSupplyMostSuccessAsync() throws Exception { final Supplier supplier_n = () -> { - sleep(10); + nap(); return n; }; final Supplier supplier_s = () -> { - sleep(10); + nap(); return s; }; final Supplier supplier_d = () -> { - sleep(10); + nap(); return d; }; final Supplier supplier_an = () -> { - sleep(10); + nap(); return anotherN; }; final Supplier supplier_nn = () -> { - sleep(10); + nap(); return n + n; }; assertEquals(Tuple2.of(n, s), tupleMSupplyMostSuccessAsync(100, TimeUnit.MILLISECONDS, supplier_n, supplier_s).get()); @@ -149,24 +148,24 @@ void test_tupleMSupplyMostSuccessAsync() throws Exception { @Test void test_tupleMSupplyAsync() throws Exception { final Supplier supplier_n = () -> { - sleep(100); + snoreZzz(); return n; }; final Supplier supplier_s = () -> { - sleep(100); + snoreZzz(); return s; }; final Supplier supplier_d = () -> { - sleep(100); + snoreZzz(); return d; }; final Supplier supplier_an = () -> { - sleep(100); + snoreZzz(); return anotherN; }; final Supplier supplier_nn = () -> { - sleep(100); + snoreZzz(); return n + n; }; assertEquals(Tuple2.of(n, s), tupleMSupplyAsync(supplier_n, supplier_s).get()); @@ -185,24 +184,24 @@ void test_tupleMSupplyAsync() throws Exception { @Test void test_tupleMSupplyAllSuccessAsync() throws Exception { final Supplier supplier_n = () -> { - sleep(10); + nap(); return n; }; final Supplier supplier_s = () -> { - sleep(10); + nap(); return s; }; final Supplier supplier_d = () -> { - sleep(10); + nap(); return d; }; final Supplier supplier_an = () -> { - sleep(10); + nap(); return anotherN; }; final Supplier supplier_nn = () -> { - sleep(10); + nap(); return n + n; }; assertEquals(Tuple2.of(n, s), tupleMSupplyAllSuccessAsync(supplier_n, supplier_s).get()); @@ -303,7 +302,7 @@ void test_allOf__exceptionally() throws Exception { // ❗dependent on the implementation behavior of `CF.allOf`️ allResultsOf( CompletableFuture.supplyAsync(() -> { - sleep(100); + snoreZzz(); throw rte; }), failedFuture(anotherRte), @@ -327,16 +326,16 @@ void test_allOf__exceptionally() throws Exception { allResultsOf( completedFuture(n), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(30, TimeUnit.MILLISECONDS) ); // incomplete fail incomplete assertThrowsExactly(TimeoutException.class, () -> allResultsOf( - createIncompleteFuture(), + incompleteCf(), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(100, TimeUnit.MILLISECONDS) ); @@ -362,7 +361,7 @@ void test_allOf__exceptionally() throws Exception { // ❗dependent on the implementation behavior of `CF.allOf`️ allResultsFastFailOf( CompletableFuture.supplyAsync(() -> { - sleep(100); + snoreZzz(); throw rte; }), failedFuture(anotherRte), @@ -386,16 +385,16 @@ void test_allOf__exceptionally() throws Exception { allResultsFastFailOf( completedFuture(n), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(30, TimeUnit.MILLISECONDS) ).getCause()); // incomplete fail incomplete assertSame(rte, assertThrowsExactly(ExecutionException.class, () -> allResultsFastFailOf( - createIncompleteFuture(), + incompleteCf(), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(100, TimeUnit.MILLISECONDS) ).getCause()); @@ -421,7 +420,7 @@ void test_allOf__exceptionally() throws Exception { // ❗dependent on the implementation behavior of `CF.allOf`️ allFastFailOf( CompletableFuture.supplyAsync(() -> { - sleep(100); + snoreZzz(); throw rte; }), failedFuture(anotherRte), @@ -445,16 +444,16 @@ void test_allOf__exceptionally() throws Exception { allFastFailOf( completedFuture(n), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(30, TimeUnit.MILLISECONDS) ).getCause()); // incomplete fail incomplete assertSame(rte, assertThrowsExactly(ExecutionException.class, () -> allFastFailOf( - createIncompleteFuture(), + incompleteCf(), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(100, TimeUnit.MILLISECONDS) ).getCause()); @@ -480,7 +479,7 @@ void test_allOf__exceptionally() throws Exception { // ❗dependent on the implementation behavior of `CF.allOf`️ allOf( CompletableFuture.supplyAsync(() -> { - sleep(100); + snoreZzz(); throw rte; }), failedFuture(anotherRte), @@ -504,16 +503,16 @@ void test_allOf__exceptionally() throws Exception { allOf( completedFuture(n), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(30, TimeUnit.MILLISECONDS) ); // incomplete fail incomplete assertThrowsExactly(TimeoutException.class, () -> allOf( - createIncompleteFuture(), + incompleteCf(), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(100, TimeUnit.MILLISECONDS) ); } @@ -523,8 +522,8 @@ void test_mostOf() throws Exception { final CompletableFuture completed = completedFuture(n); final CompletionStage completedStage = completedStage(n); final CompletableFuture failed = failedFuture(rte); - final CompletableFuture cancelled = createCancelledFuture(); - final CompletableFuture incomplete = createIncompleteFuture(); + final CompletableFuture cancelled = cancelledFuture(); + final CompletableFuture incomplete = incompleteCf(); // 0 input cf assertEquals(0, mostSuccessResultsOf(null, 10, TimeUnit.MILLISECONDS).get().size()); @@ -562,8 +561,8 @@ void test_mostOf() throws Exception { @Test void test_mostOf_wontModifyInputCf() throws Exception { - final CompletableFuture incomplete = createIncompleteFuture(); - final CompletableFuture incomplete2 = createIncompleteFuture(); + final CompletableFuture incomplete = incompleteCf(); + final CompletableFuture incomplete2 = incompleteCf(); assertEquals(Collections.singletonList(null), mostSuccessResultsOf( null, 10, TimeUnit.MILLISECONDS, incomplete @@ -582,7 +581,7 @@ void test_mostOf_wontModifyInputCf() throws Exception { //////////////////////////////////////////////////////////// @Test - void test_anySuccessOf__trivial_case() throws Exception { + void test_anyOf_anySuccessOf__trivial_case() throws Exception { assertEquals(n, anyOf( completedFuture(n), completedStage(n + 1), @@ -601,13 +600,13 @@ void test_anySuccessOf__trivial_case() throws Exception { // success with incomplete CF assertEquals(n, anyOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), completedFuture(n) ).get()); assertEquals(n, anyOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), completedStage(n) ).get()); @@ -632,13 +631,13 @@ void test_anySuccessOf__trivial_case() throws Exception { // success with incomplete CF assertEquals(n, anySuccessOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), completedFuture(n) ).get()); assertEquals(n, anySuccessOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), completedStage(n) ).get()); } @@ -658,7 +657,7 @@ void test_anyOf__exceptionally() throws Exception { // ❗dependent on the implementation behavior of `CF.anyOf`️ anyOf( CompletableFuture.supplyAsync(() -> { - sleep(100); + snoreZzz(); throw rte; }), failedFuture(anotherRte), @@ -670,9 +669,9 @@ void test_anyOf__exceptionally() throws Exception { // incomplete fail incomplete assertSame(rte, assertThrowsExactly(ExecutionException.class, () -> anyOf( - createIncompleteFuture(), + incompleteCf(), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get() ).getCause()); @@ -686,7 +685,7 @@ void test_anyOf__exceptionally() throws Exception { // ❗dependent on the implementation behavior of `CF.allOf`️ anySuccessOf( CompletableFuture.supplyAsync(() -> { - sleep(100); + snoreZzz(); throw rte; }), failedFuture(anotherRte), @@ -698,9 +697,9 @@ void test_anyOf__exceptionally() throws Exception { // incomplete fail incomplete assertThrowsExactly(TimeoutException.class, () -> anySuccessOf( - createIncompleteFuture(), + incompleteCf(), failedFuture(rte), - createIncompleteFuture() + incompleteCf() ).get(30, TimeUnit.MILLISECONDS) ).getCause(); } @@ -709,10 +708,10 @@ void test_anyOf__exceptionally() throws Exception { void test_anyOf__concurrent() throws Exception { // incomplete/wait-success then success assertEquals(n, anyOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), completedFuture(n) @@ -721,11 +720,11 @@ void test_anyOf__concurrent() throws Exception { // wait/success then success assertEquals(n, anyOf( CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), completedFuture(n) @@ -733,10 +732,10 @@ void test_anyOf__concurrent() throws Exception { // success then failed assertEquals(n, anyOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); throw rte; }), completedFuture(n) @@ -746,7 +745,7 @@ void test_anyOf__concurrent() throws Exception { assertSame(rte, assertThrowsExactly(ExecutionException.class, () -> anyOf( CompletableFuture.supplyAsync(() -> { - sleep(100); + snoreZzz(); return n; }), failedFuture(rte), @@ -758,10 +757,10 @@ void test_anyOf__concurrent() throws Exception { // incomplete/wait-success then success assertEquals(n, anySuccessOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), completedFuture(n) @@ -770,11 +769,11 @@ void test_anyOf__concurrent() throws Exception { // wait/success then success assertEquals(n, anySuccessOf( CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); return anotherN; }), completedFuture(n) @@ -782,10 +781,10 @@ void test_anyOf__concurrent() throws Exception { // success then failed assertEquals(n, anySuccessOf( - createIncompleteFuture(), - createIncompleteFuture(), + incompleteCf(), + incompleteCf(), CompletableFuture.supplyAsync(() -> { - sleep(300); + snoreZzz(); throw rte; }), completedFuture(n) @@ -794,7 +793,7 @@ void test_anyOf__concurrent() throws Exception { // failed then success assertEquals(n, anySuccessOf( CompletableFuture.supplyAsync(() -> { - sleep(100); + snoreZzz(); return n; }), failedFuture(rte), @@ -830,7 +829,7 @@ void test_allTupleOf() throws Exception { @Test void test_allTupleOf_exceptionally() throws Exception { - final CompletableFuture incomplete = new CompletableFuture<>(); + final CompletableFuture incomplete = incompleteCf(); final CompletableFuture fail = failedFuture(rte); final CompletableFuture cf_n = completedFuture(n); @@ -869,7 +868,7 @@ void test_allTupleOf_exceptionally() throws Exception { @Test void test_allTupleOf_NotFastFail() throws Exception { - final CompletableFuture incomplete = new CompletableFuture<>(); + final CompletableFuture incomplete = incompleteCf(); final CompletableFuture fail = failedFuture(rte); final CompletableFuture cf_s = completedFuture(s); @@ -928,7 +927,7 @@ void test_delayedExecutor() throws Exception { @Test void test_thenMRun() throws Exception { - final Runnable runnable = () -> sleep(100); + final Runnable runnable = TestUtils::snoreZzz; final CompletableFuture completed = completedFuture(null); final long tick = System.currentTimeMillis(); @@ -943,8 +942,8 @@ void test_thenMRun() throws Exception { thenMRunAnyAsync(completed, runnable, runnable), thenMRunAnyAsync(completed, executorService, runnable, runnable), }; - assertTrue(System.currentTimeMillis() - tick < 50); + for (CompletableFuture cf : cfs) { assertNull(cf.get()); } @@ -954,7 +953,7 @@ void test_thenMRun() throws Exception { void test_thenMAccept() throws Exception { final Consumer consumer = (x) -> { assertEquals(n, x); - sleep(100); + snoreZzz(); }; final CompletableFuture completed = completedFuture(n); @@ -970,8 +969,8 @@ void test_thenMAccept() throws Exception { thenMAcceptAnyAsync(completed, consumer, consumer), thenMAcceptAnyAsync(completed, executorService, consumer, consumer), }; - assertTrue(System.currentTimeMillis() - tick < 50); + for (CompletableFuture cf : cfs) { assertNull(cf.get()); } @@ -980,7 +979,7 @@ void test_thenMAccept() throws Exception { @Test void test_thenMApply() throws Exception { final Function supplier = (x) -> { - sleep(100); + snoreZzz(); return n; }; final CompletableFuture completed = completedFuture(n); @@ -997,8 +996,8 @@ void test_thenMApply() throws Exception { thenMApplyAsync(completed, supplier, supplier), thenMApplyAsync(completed, executorService, supplier, supplier), }; - assertTrue(System.currentTimeMillis() - tick < 50); + for (CompletableFuture> cf : cfs) { assertEquals(Arrays.asList(n, n), cf.get()); } @@ -1011,8 +1010,8 @@ void test_thenMApply() throws Exception { thenMApplyAnyAsync(completed, supplier, supplier), thenMApplyAnyAsync(completed, executorService, supplier, supplier), }; - assertTrue(System.currentTimeMillis() - tick1 < 50); + for (CompletableFuture cf : cfs1) { assertEquals(n, cf.get()); } @@ -1027,25 +1026,25 @@ void test_thenMApply() throws Exception { void test_thenTupleMApplyMostSuccessAsync() throws Exception { final CompletableFuture completed = completedFuture(n); final Function function_n = (x) -> { - sleep(100); + snoreZzz(); return n; }; final Function function_s = (x) -> { - sleep(100); + snoreZzz(); return s; }; final Function function_d = (x) -> { - sleep(100); + snoreZzz(); return d; }; final Function function_an = (x) -> { - sleep(100); + snoreZzz(); return anotherN; }; final Function function_nn = (x) -> { - sleep(100); + snoreZzz(); return n + n; }; assertEquals(Tuple2.of(n, s), thenTupleMApplyMostSuccessAsync(completed, 500, TimeUnit.MILLISECONDS, function_n, function_s).get()); @@ -1065,25 +1064,25 @@ void test_thenTupleMApplyMostSuccessAsync() throws Exception { void test_thenTupleMApplyAllSuccessAsync() throws Exception { final CompletableFuture completed = completedFuture(n); final Function function_n = (x) -> { - sleep(100); + snoreZzz(); return n; }; final Function function_s = (x) -> { - sleep(100); + snoreZzz(); return s; }; final Function function_d = (x) -> { - sleep(100); + snoreZzz(); return d; }; final Function function_an = (x) -> { - sleep(100); + snoreZzz(); return anotherN; }; final Function function_nn = (x) -> { - sleep(100); + snoreZzz(); return n + n; }; assertEquals(Tuple2.of(n, s), thenTupleMApplyAllSuccessAsync(completed, function_n, function_s).get()); @@ -1103,25 +1102,25 @@ void test_thenTupleMApplyAllSuccessAsync() throws Exception { void test_thenTupleMApplyAsync() throws Exception { final CompletableFuture completed = completedFuture(n); final Function function_n = (x) -> { - sleep(100); + snoreZzz(); return n; }; final Function function_s = (x) -> { - sleep(100); + snoreZzz(); return s; }; final Function function_d = (x) -> { - sleep(100); + snoreZzz(); return d; }; final Function function_an = (x) -> { - sleep(100); + snoreZzz(); return anotherN; }; final Function function_nn = (x) -> { - sleep(100); + snoreZzz(); return n + n; }; assertEquals(Tuple2.of(n, s), thenTupleMApplyAsync(completed, function_n, function_s).get()); @@ -1142,8 +1141,8 @@ void test_mostSuccessTupleOf() throws Exception { final CompletableFuture completed = completedFuture(n); final CompletionStage anotherCompleted = completedStage(s); final CompletableFuture failed = failedFuture(rte); - final CompletableFuture cancelled = createCancelledFuture(); - final CompletableFuture incomplete = createIncompleteFuture(); + final CompletableFuture cancelled = cancelledFuture(); + final CompletableFuture incomplete = incompleteCf(); assertEquals(Tuple2.of(n, s), mostSuccessTupleOf( 10, TimeUnit.MILLISECONDS, completed, anotherCompleted @@ -1227,10 +1226,7 @@ void test_both() throws Exception { @Test void both_fastFail() throws Exception { - CompletableFuture cf_n = CompletableFuture.supplyAsync(() -> { - sleep(2_000); - return n; - }); + CompletableFuture cf_n = completeLaterCf(n); final CompletableFuture failed = failedFuture(rte); final CompletableFuture cf_ee = failedFuture(anotherRte); @@ -1331,7 +1327,7 @@ void both_fastFail() throws Exception { @Test void test_either() throws Exception { final CompletableFuture cf_n = completedFuture(n); - CompletableFuture incomplete = createIncompleteFuture(); + CompletableFuture incomplete = incompleteCf(); final Runnable runnable = () -> { }; @@ -1460,22 +1456,22 @@ void test_catching() throws Exception { @Test void test_timeout() throws Exception { assertInstanceOf(TimeoutException.class, assertThrowsExactly(ExecutionException.class, () -> - orTimeout(createIncompleteFuture(), 1, TimeUnit.MILLISECONDS).get() + orTimeout(incompleteCf(), 1, TimeUnit.MILLISECONDS).get() ).getCause()); assertInstanceOf(TimeoutException.class, assertThrowsExactly(ExecutionException.class, () -> - cffuOrTimeout(createIncompleteFuture(), 1, TimeUnit.MILLISECONDS).get() + cffuOrTimeout(incompleteCf(), 1, TimeUnit.MILLISECONDS).get() ).getCause()); assertInstanceOf(TimeoutException.class, assertThrowsExactly(ExecutionException.class, () -> - cffuOrTimeout(createIncompleteFuture(), defaultExecutor(), 1, TimeUnit.MILLISECONDS).get() + cffuOrTimeout(incompleteCf(), defaultExecutor(), 1, TimeUnit.MILLISECONDS).get() ).getCause()); assertEquals(n, orTimeout(completedFuture(n), 1, TimeUnit.MILLISECONDS).get()); assertEquals(n, cffuOrTimeout(completedFuture(n), 1, TimeUnit.MILLISECONDS).get()); assertEquals(n, cffuOrTimeout(completedFuture(n), defaultExecutor(), 1, TimeUnit.MILLISECONDS).get()); - assertEquals(n, completeOnTimeout(createIncompleteFuture(), n, 1, TimeUnit.MILLISECONDS).get()); - assertEquals(n, cffuCompleteOnTimeout(createIncompleteFuture(), n, 1, TimeUnit.MILLISECONDS).get()); - assertEquals(n, cffuCompleteOnTimeout(createIncompleteFuture(), n, defaultExecutor(), 1, TimeUnit.MILLISECONDS).get()); + assertEquals(n, completeOnTimeout(incompleteCf(), n, 1, TimeUnit.MILLISECONDS).get()); + assertEquals(n, cffuCompleteOnTimeout(incompleteCf(), n, 1, TimeUnit.MILLISECONDS).get()); + assertEquals(n, cffuCompleteOnTimeout(incompleteCf(), n, defaultExecutor(), 1, TimeUnit.MILLISECONDS).get()); assertEquals(n, completeOnTimeout(completedFuture(n), anotherN, 1, TimeUnit.MILLISECONDS).get()); assertEquals(n, cffuCompleteOnTimeout(completedFuture(n), anotherN, 1, TimeUnit.MILLISECONDS).get()); @@ -1488,7 +1484,7 @@ void test_safeBehavior_orTimeout() { final List results = IntStream.range(0, 10).boxed().collect(Collectors.toList()); assertEquals(results, results.stream().map(i -> - orTimeout(createIncompleteFuture(), 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { + orTimeout(incompleteCf(), 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { assertInstanceOf(TimeoutException.class, ex); assertTrue(Delayer.atCfDelayerThread()); return i; @@ -1496,7 +1492,7 @@ void test_safeBehavior_orTimeout() { ).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList())); assertEquals(results, results.stream().map(i -> - cffuOrTimeout(createIncompleteFuture(), 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { + cffuOrTimeout(incompleteCf(), 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { assertInstanceOf(TimeoutException.class, ex); assertFalse(Delayer.atCfDelayerThread()); assertNotSame(testThread, currentThread()); @@ -1504,10 +1500,10 @@ void test_safeBehavior_orTimeout() { }) ).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList())); assertEquals(results, results.stream().map(i -> - cffuOrTimeout(createIncompleteFuture(), executorService, 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { + cffuOrTimeout(incompleteCf(), executorService, 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { assertInstanceOf(TimeoutException.class, ex); assertFalse(Delayer.atCfDelayerThread()); - assertTrue(TestThreadPoolManager.isRunInExecutor(executorService)); + assertRunningInExecutor(executorService); return i; }) ).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList())); @@ -1519,7 +1515,7 @@ void test_safeBehavior_completeOnTimeout() { final List results = IntStream.range(0, 10).boxed().collect(Collectors.toList()); assertEquals(results, results.stream().map(i -> - completeOnTimeout(createIncompleteFuture(), i, 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { + completeOnTimeout(incompleteCf(), i, 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { assertNull(ex); assertTrue(Delayer.atCfDelayerThread()); return v; @@ -1527,7 +1523,7 @@ void test_safeBehavior_completeOnTimeout() { ).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList())); assertEquals(results, results.stream().map(i -> - cffuCompleteOnTimeout(createIncompleteFuture(), i, 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { + cffuCompleteOnTimeout(incompleteCf(), i, 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { assertNull(ex); assertFalse(Delayer.atCfDelayerThread()); assertNotSame(testThread, currentThread()); @@ -1535,10 +1531,10 @@ void test_safeBehavior_completeOnTimeout() { }) ).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList())); assertEquals(results, results.stream().map(i -> - cffuCompleteOnTimeout(createIncompleteFuture(), i, executorService, 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { + cffuCompleteOnTimeout(incompleteCf(), i, executorService, 100, TimeUnit.MILLISECONDS).handle((v, ex) -> { assertNull(ex); assertFalse(Delayer.atCfDelayerThread()); - assertTrue(TestThreadPoolManager.isRunInExecutor(executorService)); + assertRunningInExecutor(executorService); return v; }) ).collect(Collectors.toList()).stream().map(CompletableFuture::join).collect(Collectors.toList())); @@ -1692,7 +1688,7 @@ void test_read() { // cancelled tasks //////////////////////////////////////////////////////////////////////////////// - CompletableFuture cancelled = createCancelledFuture(); + CompletableFuture cancelled = cancelledFuture(); assertThrowsExactly(CancellationException.class, cancelled::join); // same as CompletableFuture.join method @@ -1713,7 +1709,7 @@ void test_read() { // incomplete tasks //////////////////////////////////////////////////////////////////////////////// - final CompletableFuture incomplete = createIncompleteFuture(); + final CompletableFuture incomplete = incompleteCf(); assertInstanceOf(TimeoutException.class, assertThrowsExactly(CompletionException.class, () -> join(incomplete, 1, TimeUnit.MILLISECONDS) @@ -1731,22 +1727,26 @@ void test_read() { assertSame(CffuState.RUNNING, state(incomplete)); // Incomplete Future -> join before timeout - CompletableFuture later = createFutureCompleteLater(n); + CompletableFuture later = completeLaterCf(n); assertEquals(n, join(later, 3, TimeUnit.SECONDS)); } @Test void test_write() throws Exception { - assertEquals(n, completeAsync(createIncompleteFuture(), () -> n).get()); - assertEquals(n, completeAsync(createIncompleteFuture(), () -> n, commonPool()).get()); + assertEquals(n, completeAsync(incompleteCf(), () -> n).get()); + assertEquals(n, completeAsync(incompleteCf(), () -> n, commonPool()).get()); if (isJava9Plus()) { - CompletableFuture f = (CompletableFuture) completedStage(42); + CompletableFuture f = (CompletableFuture) completedStage(n); assertThrowsExactly(UnsupportedOperationException.class, () -> completeAsync(f, () -> null) ); + } else { + CompletableFuture f = (CompletableFuture) completedStage(n); + completeAsync(f, () -> null); } + assertSame(rte, assertThrowsExactly(ExecutionException.class, () -> - completeAsync(createIncompleteFuture(), () -> { + completeAsync(incompleteCf(), () -> { throw rte; }).get() ).getCause()); @@ -1757,14 +1757,18 @@ void test_write() throws Exception { //////////////////////////////////////// assertSame(rte, assertThrowsExactly(ExecutionException.class, () -> - completeExceptionallyAsync(createIncompleteFuture(), () -> rte).get() + completeExceptionallyAsync(incompleteCf(), () -> rte).get() ).getCause()); if (isJava9Plus()) { - CompletableFuture f = (CompletableFuture) completedStage(42); + CompletableFuture f = (CompletableFuture) completedStage(n); assertThrowsExactly(UnsupportedOperationException.class, () -> completeExceptionallyAsync(f, () -> rte) ); + } else { + CompletableFuture f = (CompletableFuture) completedStage(n); + completeExceptionallyAsync(f, () -> rte); } + assertEquals(n, completeExceptionallyAsync(completedFuture(n), () -> rte).get()); } @@ -1778,7 +1782,7 @@ void test_re_config() throws Exception { CompletionStage mf = minimalCompletionStage(completedFuture(n)); assertEquals(n, mf.toCompletableFuture().get()); - CompletableFuture cf = createIncompleteFuture(); + CompletableFuture cf = incompleteCf(); copy(cf).complete(n); assertFalse(cf.isDone()); @@ -1791,9 +1795,9 @@ void test_re_config() throws Exception { @Test void test_executor() { Executor executor = defaultExecutor(); - assertIsDefaultExecutor(executor); + assertIsCfDefaultExecutor(executor); - assertIsDefaultExecutor(screenExecutor(commonPool())); + assertIsCfDefaultExecutor(screenExecutor(commonPool())); ExecutorService e = Executors.newCachedThreadPool(); assertSame(e, screenExecutor(e)); @@ -1839,7 +1843,7 @@ void test_unwrapCfException() { // region# Test helper methods/fields //////////////////////////////////////////////////////////////////////////////// - private static void assertIsDefaultExecutor(Executor executor) { + private static void assertIsCfDefaultExecutor(Executor executor) { final boolean USE_COMMON_POOL = ForkJoinPool.getCommonPoolParallelism() > 1; if (USE_COMMON_POOL) { assertSame(commonPool(), executor); @@ -1849,16 +1853,12 @@ private static void assertIsDefaultExecutor(Executor executor) { } } - private static final String testName = "CompletableFutureUtilsTest"; - private static ExecutorService executorService; + // endregion + //////////////////////////////////////////////////////////////////////////////// + // region# Test helper fields + //////////////////////////////////////////////////////////////////////////////// - @BeforeAll - static void beforeAll() { - executorService = TestThreadPoolManager.createThreadPool("CffuTest"); - } + private final ExecutorService executorService = TestingExecutorUtils.getTestThreadPoolExecutor(); - @AfterAll - static void afterAll() { - TestThreadPoolManager.shutdownExecutorService(executorService); - } + private static final String testName = "CompletableFutureUtilsTest"; } diff --git a/cffu-core/src/test/java/io/foldright/cffu/DefaultExecutorTestUtils.java b/cffu-core/src/test/java/io/foldright/cffu/DefaultExecutorTestUtils.java deleted file mode 100644 index 4a6142e3..00000000 --- a/cffu-core/src/test/java/io/foldright/cffu/DefaultExecutorTestUtils.java +++ /dev/null @@ -1,16 +0,0 @@ -package io.foldright.cffu; - -import java.util.concurrent.Executor; - - -public class DefaultExecutorTestUtils { - public static Executor unwrapMadeExecutor(CffuFactory factory) { - final CffuFactoryBuilder.CffuMadeExecutor executor = (CffuFactoryBuilder.CffuMadeExecutor) factory.defaultExecutor(); - return executor.unwrap(); - } - - public static Executor unwrapMadeExecutor(Cffu cffu) { - final CffuFactoryBuilder.CffuMadeExecutor executor = (CffuFactoryBuilder.CffuMadeExecutor) cffu.defaultExecutor(); - return executor.unwrap(); - } -} diff --git a/cffu-core/src/test/java/io/foldright/cffu/ListenableFutureUtilsTest.java b/cffu-core/src/test/java/io/foldright/cffu/ListenableFutureUtilsTest.java index ca61b384..c7e92db8 100644 --- a/cffu-core/src/test/java/io/foldright/cffu/ListenableFutureUtilsTest.java +++ b/cffu-core/src/test/java/io/foldright/cffu/ListenableFutureUtilsTest.java @@ -4,9 +4,7 @@ import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; -import io.foldright.test_utils.TestThreadPoolManager; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import io.foldright.test_utils.TestingExecutorUtils; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.JRE; @@ -15,6 +13,7 @@ import static io.foldright.cffu.ListenableFutureUtils.*; import static io.foldright.test_utils.TestUtils.*; +import static io.foldright.test_utils.TestingConstants.*; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.junit.jupiter.api.Assertions.*; @@ -66,7 +65,7 @@ void test_toListenableFuture() throws Exception { () -> toListenableFuture(failed).get() ).getCause()); - cf = new CompletableFuture<>(); + cf = incompleteCf(); lf = toListenableFuture(cf); lf.cancel(false); assertTrue(lf.isCancelled()); @@ -135,7 +134,7 @@ void test_lf2cf_setCancellationExceptionToCf_cancellationAndPropagation() throws final CompletableFuture cf = toCompletableFuture(lf, executorService, true); assertTrue(cf.completeExceptionally(new IllegalArgumentException())); - sleep(100); + snoreZzz(); waitForAllCfsToComplete(cf); assertFalse(lf.isDone()); @@ -154,13 +153,13 @@ void test_lf2cf_dependentLf() throws Exception { } { final ListenableFuture lf = SettableFuture.create(); - CompletableFuture cf = new CompletableFuture<>(); + CompletableFuture cf = incompleteCf(); CompletableFuture cfWrapperOfLf = cf.thenCompose(v -> toCompletableFuture(lf, MoreExecutors.directExecutor(), true)); cf.cancel(false); - sleep(20); + nap(); assertTrue(cf.isCancelled()); assertThrowsExactly(CancellationException.class, cf::get); @@ -174,7 +173,7 @@ void test_lf2cf_dependentLf() throws Exception { @Test void test_cf2lf_cancellationAndPropagation() throws Exception { - final CompletableFuture cf = new CompletableFuture<>(); + final CompletableFuture cf = incompleteCf(); final ListenableFuture lf = toListenableFuture(cf); assertTrue(lf.cancel(false)); @@ -205,7 +204,7 @@ void showCase_ListenableFuture_cancellationAndPropagation() throws Exception { @Test void showCase_CompletableFuture_cancellationAndPropagation() throws Exception { - final CompletableFuture cf = new CompletableFuture<>(); + final CompletableFuture cf = incompleteCf(); final CompletableFuture transform = cf.thenApplyAsync(x -> x + 1, executorService); assertTrue(cf.cancel(false)); @@ -241,19 +240,12 @@ static void waitForAllCfsToComplete(CompletableFuture... cfs) throws Exceptio CompletableFutureUtils.mostSuccessResultsOf(null, 2, TimeUnit.SECONDS, cfs).join(); } - private static ExecutorService executorService; - - private static CffuFactory cffuFactory; - - @BeforeAll - static void beforeAll() { - executorService = TestThreadPoolManager.createThreadPool("ListenableFutureUtilsTest"); + // endregion + //////////////////////////////////////////////////////////////////////////////// + // region# Test helper fields + //////////////////////////////////////////////////////////////////////////////// - cffuFactory = CffuFactory.builder(executorService).build(); - } + private final CffuFactory cffuFactory = TestingExecutorUtils.getTestCffuFactory(); - @AfterAll - static void afterAll() { - TestThreadPoolManager.shutdownExecutorService(executorService); - } + private final ExecutorService executorService = TestingExecutorUtils.getTestThreadPoolExecutor(); } diff --git a/cffu-core/src/test/java/io/foldright/cffu/spi/ExecutorWrapperProviderTest.kt b/cffu-core/src/test/java/io/foldright/cffu/spi/ExecutorWrapperProviderTest.kt index b1e68460..c07ddd32 100644 --- a/cffu-core/src/test/java/io/foldright/cffu/spi/ExecutorWrapperProviderTest.kt +++ b/cffu-core/src/test/java/io/foldright/cffu/spi/ExecutorWrapperProviderTest.kt @@ -1,7 +1,7 @@ package io.foldright.cffu.spi import io.foldright.cffu.CffuFactory -import io.foldright.cffu.DefaultExecutorTestUtils.unwrapMadeExecutor +import io.foldright.cffu.unwrapMadeExecutor import io.foldright.test_utils.testThreadPoolExecutor import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.types.shouldBeSameInstanceAs @@ -11,7 +11,7 @@ class ExecutorWrapperProviderTest : FunSpec({ test("disable TestExecutorWrapper") { val factory = CffuFactory.builder(testThreadPoolExecutor).build() val cffu = factory.runAsync {} - unwrapMadeExecutor(cffu).shouldBeSameInstanceAs(testThreadPoolExecutor) + cffu.unwrapMadeExecutor() shouldBeSameInstanceAs testThreadPoolExecutor } test("enable TestExecutorWrapper") { @@ -19,7 +19,7 @@ class ExecutorWrapperProviderTest : FunSpec({ val factory = CffuFactory.builder(testThreadPoolExecutor).build() val cffu = factory.runAsync {} - unwrapMadeExecutor(cffu).shouldNotBeSameInstanceAs(testThreadPoolExecutor) + cffu.unwrapMadeExecutor() shouldNotBeSameInstanceAs testThreadPoolExecutor } beforeTest { diff --git a/cffu-core/src/test/java/io/foldright/cffu/tuple/TupleTest.java b/cffu-core/src/test/java/io/foldright/cffu/tuple/TupleTest.java index 0e3e650c..79e1b994 100644 --- a/cffu-core/src/test/java/io/foldright/cffu/tuple/TupleTest.java +++ b/cffu-core/src/test/java/io/foldright/cffu/tuple/TupleTest.java @@ -8,7 +8,7 @@ import static org.junit.jupiter.api.Assertions.*; -@SuppressWarnings({"AssertBetweenInconvertibleTypes", "EqualsWithItself", "SimplifiableAssertion", "ConstantValue", "EqualsBetweenInconvertibleTypes"}) +@SuppressWarnings({"EqualsWithItself", "SimplifiableAssertion", "ConstantValue", "EqualsBetweenInconvertibleTypes"}) public class TupleTest { int e1 = 1; String e2 = "2"; diff --git a/cffu-core/src/test/java/io/foldright/compatibility_test/CffuApiCompatibilityTest.java b/cffu-core/src/test/java/io/foldright/compatibility_test/CffuApiCompatibilityTest.java index 5c8ec629..ab92ca15 100644 --- a/cffu-core/src/test/java/io/foldright/compatibility_test/CffuApiCompatibilityTest.java +++ b/cffu-core/src/test/java/io/foldright/compatibility_test/CffuApiCompatibilityTest.java @@ -1,18 +1,9 @@ package io.foldright.compatibility_test; -//////////////////////////////////////////////////////////////////////////////// -// CompletableFutureApiCompatibilityTest and CffuApiCompatibilityTest are used to test -// the Cffu API compatibility to CompletableFuture. -// -// CffuApiCompatibilityTest.java file is auto generated -// from CompletableFutureApiCompatibilityTest.java -// by script gen_CffuApiCompatibilityTest.sh -//////////////////////////////////////////////////////////////////////////////// - +import io.foldright.test_utils.TestUtils; import io.foldright.cffu.Cffu; import io.foldright.cffu.CffuFactory; -import io.foldright.test_utils.TestThreadPoolManager; -import io.foldright.test_utils.TestUtils; +import io.foldright.test_utils.TestingExecutorUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -22,15 +13,22 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; +import static io.foldright.test_utils.TestingConstants.*; import static org.junit.jupiter.api.Assertions.*; +/** + * {@link CompletableFutureApiCompatibilityTest} and {@link CffuApiCompatibilityTest} + * are used to check the Cffu API compatibility to CompletableFuture. + *

+ * {@code CffuApiCompatibilityTest.java} file is auto generated + * from {@code CompletableFutureApiCompatibilityTest.java} file + * by script {@code scripts/gen_CffuApiCompatibilityTest.sh}. + */ @SuppressWarnings("RedundantThrows") class CffuApiCompatibilityTest { private static final String hello = "Cffu API Compatibility Test - Hello"; - private static final RuntimeException rte = new RuntimeException("Bang"); - //////////////////////////////////////////////////////////////////////////////// // Static Methods //////////////////////////////////////////////////////////////////////////////// @@ -113,8 +111,8 @@ void constructor() throws Exception { Cffu cf = cffuFactory.newIncompleteCffu(); assertFalse(cf.isDone()); - cf.complete(42); - assertEquals(42, cf.get()); + cf.complete(n); + assertEquals(n, cf.get()); } //////////////////////////////////////// @@ -123,9 +121,9 @@ void constructor() throws Exception { @Test void staticMethods_allOf_anyOf() throws Exception { - Cffu f1 = cffuFactory.completedFuture(42); - Cffu f2 = cffuFactory.completedFuture(4242); - Cffu f3 = cffuFactory.completedFuture(424242); + Cffu f1 = cffuFactory.completedFuture(n); + Cffu f2 = cffuFactory.completedFuture(anotherN); + Cffu f3 = cffuFactory.completedFuture(nnn); assertNull(cffuFactory.allOf().get()); assertNull(cffuFactory.allOf(f1, f2).get()); @@ -168,7 +166,7 @@ void staticMethods_delayedExecutor() throws Exception { void simpleThenMethods() throws Exception { final AtomicReference holder = new AtomicReference<>(); - final Cffu cf = cffuFactory.completedFuture(42); + final Cffu cf = cffuFactory.completedFuture(n); cf.thenRun(() -> holder.set(hello)).get(); assertEquals(hello, holder.get()); @@ -201,12 +199,12 @@ void simpleThenMethods() throws Exception { }, anotherExecutorService).get(); assertEquals(hello, holder.get()); - assertEquals(43, cf.thenApply(x -> x + 1).get()); - assertEquals(44, cf.thenApplyAsync(x -> { + assertEquals(n + 1, cf.thenApply(x -> x + 1).get()); + assertEquals(n + 2, cf.thenApplyAsync(x -> { TestUtils.assertCffuRunInDefaultThread(executorService); return x + 2; }).get()); - assertEquals(45, cf.thenApplyAsync(x -> { + assertEquals(n + 3, cf.thenApplyAsync(x -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); return x + 3; }, anotherExecutorService).get()); @@ -216,7 +214,7 @@ void simpleThenMethods() throws Exception { void thenBoth_Methods() throws Exception { final AtomicReference holder = new AtomicReference<>(); - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); cf.runAfterBoth(cf, () -> holder.set(hello)).get(); assertEquals(hello, holder.get()); @@ -249,12 +247,12 @@ void thenBoth_Methods() throws Exception { }, anotherExecutorService).get(); assertEquals(hello, holder.get()); - assertEquals(84, cf.thenCombine(cf, Integer::sum).get()); - assertEquals(84, cf.thenCombineAsync(cf, (a, b) -> { + assertEquals(n * 2, cf.thenCombine(cf, Integer::sum).get()); + assertEquals(n * 2, cf.thenCombineAsync(cf, (a, b) -> { TestUtils.assertCffuRunInDefaultThread(executorService); return Integer.sum(a, b); }).get()); - assertEquals(84, cf.thenCombineAsync(cf, (a, b) -> { + assertEquals(n * 2, cf.thenCombineAsync(cf, (a, b) -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); return Integer.sum(a, b); }, anotherExecutorService).get()); @@ -264,7 +262,7 @@ void thenBoth_Methods() throws Exception { void thenEither_Methods() throws Exception { final AtomicReference holder = new AtomicReference<>(); - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); cf.runAfterEither(cf, () -> holder.set(hello)).get(); assertEquals(hello, holder.get()); @@ -297,12 +295,12 @@ void thenEither_Methods() throws Exception { }, anotherExecutorService).get(); assertEquals(hello, holder.get()); - assertEquals(43, cf.applyToEither(cf, x -> x + 1).get()); - assertEquals(44, cf.applyToEitherAsync(cf, x -> { + assertEquals(n + 1, cf.applyToEither(cf, x -> x + 1).get()); + assertEquals(n + 2, cf.applyToEitherAsync(cf, x -> { TestUtils.assertCffuRunInDefaultThread(executorService); return x + 2; }).get()); - assertEquals(45, cf.applyToEitherAsync(cf, x -> { + assertEquals(n + 3, cf.applyToEitherAsync(cf, x -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); return x + 3; }, anotherExecutorService).get()); @@ -310,12 +308,12 @@ void thenEither_Methods() throws Exception { @Test void errorHandling_methods() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); Cffu failed = TestUtils.safeNewFailedCffu(executorService, rte); // exceptionally - assertEquals(42, cf.exceptionally(t -> 43).get()); - assertEquals(43, failed.exceptionally(t -> 43).get()); + assertEquals(n, cf.exceptionally(t -> anotherN).get()); + assertEquals(anotherN, failed.exceptionally(t -> anotherN).get()); // below methods is tested in below test method // - exceptionallyAsync @@ -323,37 +321,37 @@ void errorHandling_methods() throws Exception { @Test void errorHandling_methods__Java9() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); Cffu failed = TestUtils.safeNewFailedCffu(executorService, rte); - assertEquals(42, cf.exceptionallyAsync(t -> { + assertEquals(n, cf.exceptionallyAsync(t -> { TestUtils.assertCffuRunInDefaultThread(executorService); - return 43; + return anotherN; }).get()); - assertEquals(43, failed.exceptionallyAsync(t -> { + assertEquals(anotherN, failed.exceptionallyAsync(t -> { TestUtils.assertCffuRunInDefaultThread(executorService); - return 43; + return anotherN; }).get()); - assertEquals(42, cf.exceptionallyAsync(t -> { + assertEquals(n, cf.exceptionallyAsync(t -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); - return 44; + return anotherN; }, anotherExecutorService).get()); - assertEquals(44, failed.exceptionallyAsync(t -> { + assertEquals(anotherN, failed.exceptionallyAsync(t -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); - return 44; + return anotherN; }, anotherExecutorService).get()); } @Test void timeoutControl_methods() throws Exception { // For completed - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); - assertEquals(42, + assertEquals(n, cf.orTimeout(20, TimeUnit.MILLISECONDS).get()); - assertEquals(42, - cf.completeOnTimeout(43, 20, TimeUnit.MILLISECONDS).get()); + assertEquals(n, + cf.completeOnTimeout(anotherN, 20, TimeUnit.MILLISECONDS).get()); // for incomplete Cffu incomplete = cffuFactory.newIncompleteCffu(); @@ -362,65 +360,65 @@ void timeoutControl_methods() throws Exception { ).getCause().getClass()); Cffu incomplete2 = cffuFactory.newIncompleteCffu(); - assertEquals(43, incomplete2.completeOnTimeout(43, 20, TimeUnit.MILLISECONDS).get()); + assertEquals(anotherN, incomplete2.completeOnTimeout(anotherN, 20, TimeUnit.MILLISECONDS).get()); } @Test void advancedMethods__thenCompose() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); - assertEquals(43, cf.thenCompose(x -> cffuFactory.completedFuture(43)).get()); - assertEquals(44, cf.thenComposeAsync(x -> { + assertEquals(anotherN, cf.thenCompose(x -> cffuFactory.completedFuture(anotherN)).get()); + assertEquals(anotherN, cf.thenComposeAsync(x -> { TestUtils.assertCffuRunInDefaultThread(executorService); - return cffuFactory.completedFuture(44); + return cffuFactory.completedFuture(anotherN); }).get()); - assertEquals(45, cf.thenComposeAsync(x -> { + assertEquals(anotherN, cf.thenComposeAsync(x -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); - return cffuFactory.completedFuture(45); + return cffuFactory.completedFuture(anotherN); }, anotherExecutorService).get()); } @Test void advancedMethods__exceptionallyCompose() throws Exception { // for success - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); - assertEquals(42, cf.exceptionallyCompose(x -> cffuFactory.completedFuture(43)).get()); - assertEquals(42, cf.exceptionallyComposeAsync(x -> { + assertEquals(n, cf.exceptionallyCompose(x -> cffuFactory.completedFuture(anotherN)).get()); + assertEquals(n, cf.exceptionallyComposeAsync(x -> { TestUtils.assertCffuRunInDefaultThread(executorService); - return cffuFactory.completedFuture(44); + return cffuFactory.completedFuture(anotherN); }).get()); - assertEquals(42, cf.exceptionallyComposeAsync(x -> { + assertEquals(n, cf.exceptionallyComposeAsync(x -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); - return cffuFactory.completedFuture(45); + return cffuFactory.completedFuture(anotherN); }, anotherExecutorService).get()); // for failed Cffu failed = TestUtils.safeNewFailedCffu(executorService, rte); - assertEquals(43, failed.exceptionallyCompose(x -> cffuFactory.completedFuture(43)).get()); - assertEquals(44, failed.exceptionallyComposeAsync(x -> { + assertEquals(anotherN, failed.exceptionallyCompose(x -> cffuFactory.completedFuture(anotherN)).get()); + assertEquals(anotherN, failed.exceptionallyComposeAsync(x -> { TestUtils.assertCffuRunInDefaultThread(executorService); - return cffuFactory.completedFuture(44); + return cffuFactory.completedFuture(anotherN); }).get()); - assertEquals(45, failed.exceptionallyComposeAsync(x -> { + assertEquals(anotherN, failed.exceptionallyComposeAsync(x -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); - return cffuFactory.completedFuture(45); + return cffuFactory.completedFuture(anotherN); }, anotherExecutorService).get()); } @Test void advancedMethods__handle_whenComplete() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); - assertEquals(43, cf.handle((x, e) -> 43).get()); - assertEquals(44, cf.handleAsync((x, e) -> { + assertEquals(anotherN, cf.handle((x, e) -> anotherN).get()); + assertEquals(anotherN, cf.handleAsync((x, e) -> { TestUtils.assertCffuRunInDefaultThread(executorService); - return 44; + return anotherN; }).get()); - assertEquals(45, cf.handleAsync((x, e) -> { + assertEquals(anotherN, cf.handleAsync((x, e) -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); - return 45; + return anotherN; }, anotherExecutorService).get()); final AtomicReference holder = new AtomicReference<>(); @@ -443,11 +441,11 @@ void advancedMethods__handle_whenComplete() throws Exception { @Test void readExplicitlyMethods() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); Cffu failed = TestUtils.safeNewFailedCffu(executorService, rte); Integer r = cf.get(); - assertEquals(42, r); + assertEquals(n, r); assertSame(rte, assertThrowsExactly(ExecutionException.class, failed::get).getCause()); assertEquals(r, cf.get(1, TimeUnit.MILLISECONDS)); @@ -482,10 +480,10 @@ void readExplicitlyMethods() throws Exception { @Test void readExplicitlyMethods__Java19() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); Cffu failed = TestUtils.safeNewFailedCffu(executorService, rte); Integer r = cf.get(); - assertEquals(42, r); + assertEquals(n, r); // resultNow assertEquals(r, cf.resultNow()); @@ -499,7 +497,7 @@ void readExplicitlyMethods__Java19() throws Exception { @Test @EnabledForJreRange(min = JRE.JAVA_19) /* GEN_MARK_KEEP */ void readExplicitlyMethods__Java19_CanNotCompatible() { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); Cffu failed = TestUtils.safeNewFailedCffu(executorService, rte); Cffu incomplete = cffuFactory.newIncompleteCffu(); @@ -511,20 +509,20 @@ void readExplicitlyMethods__Java19_CanNotCompatible() { @Test void writeMethods() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); Cffu incomplete = cffuFactory.newIncompleteCffu(); - assertFalse(cf.complete(4242)); - assertEquals(42, cf.get()); + assertFalse(cf.complete(anotherN)); + assertEquals(n, cf.get()); - assertTrue(incomplete.complete(4242)); - assertEquals(4242, incomplete.get()); + assertTrue(incomplete.complete(anotherN)); + assertEquals(anotherN, incomplete.get()); // below methods is tested in below test method // - completeAsync // completeExceptionally assertFalse(cf.completeExceptionally(rte)); - assertEquals(42, cf.get()); + assertEquals(n, cf.get()); incomplete = cffuFactory.newIncompleteCffu(); assertTrue(incomplete.completeExceptionally(rte)); @@ -538,27 +536,27 @@ void writeMethods() throws Exception { @Test void writeMethods__Java9() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); // completeAsync - assertEquals(42, cf.completeAsync(() -> { + assertEquals(n, cf.completeAsync(() -> { TestUtils.assertCffuRunInDefaultThread(executorService); - return 4242; + return anotherN; }).get()); - assertEquals(42, cf.completeAsync(() -> { + assertEquals(n, cf.completeAsync(() -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); - return 424242; + return anotherN; }, anotherExecutorService).get()); Cffu incomplete = cffuFactory.newIncompleteCffu(); - assertEquals(4242, incomplete.completeAsync(() -> { + assertEquals(anotherN, incomplete.completeAsync(() -> { TestUtils.assertCffuRunInDefaultThread(executorService); - return 4242; + return anotherN; }).get()); incomplete = cffuFactory.newIncompleteCffu(); - assertEquals(424242, incomplete.completeAsync(() -> { + assertEquals(anotherN, incomplete.completeAsync(() -> { TestUtils.assertCffuRunInThreadOf(anotherExecutorService); - return 424242; + return anotherN; }, anotherExecutorService).get()); RuntimeException ex = new RuntimeException(); @@ -579,26 +577,26 @@ void reConfigMethods() throws Exception { // - minimalCompletionStage // - copy - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); // toCompletableFuture - assertEquals(42, cf.toCompletableFuture().get()); + assertEquals(n, cf.toCompletableFuture().get()); } @Test void reConfigMethods__Java9() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); // minimalCompletionStage TestUtils.shouldBeMinimalStage((Cffu) cf.minimalCompletionStage()); // copy - assertEquals(42, cf.copy().get()); + assertEquals(n, cf.copy().get()); } @Test void test_getterMethods() { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); // defaultExecutor assertNotNull(cf.defaultExecutor()); @@ -606,7 +604,7 @@ void test_getterMethods() { @Test void test_inspectionMethods() { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); // getNumberOfDependents assertNotEquals(-1, cf.getNumberOfDependents()); @@ -614,11 +612,11 @@ void test_inspectionMethods() { @Test void test_dangerousMethods() throws Exception { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); // obtrudeValue - cf.obtrudeValue(44); - assertEquals(44, cf.get()); + cf.obtrudeValue(anotherN); + assertEquals(anotherN, cf.get()); // obtrudeException cf.obtrudeException(rte); @@ -627,7 +625,7 @@ void test_dangerousMethods() throws Exception { @Test void test_forApiCompatibility() { - Cffu cf = cffuFactory.completedFuture(42); + Cffu cf = cffuFactory.completedFuture(n); // newIncompleteFuture assertFalse(cf.newIncompleteFuture().isDone()); @@ -663,10 +661,10 @@ void test_similarities_and_differences_between_cancelled_and_exceptionally() thr assertSame(rte, assertThrowsExactly(CompletionException.class, exceptionallyCf::join).getCause()); assertThrowsExactly(CancellationException.class, () -> - cancelledCf.getNow(42) + cancelledCf.getNow(n) ); assertSame(rte, assertThrowsExactly(CompletionException.class, () -> - exceptionallyCf.getNow(42) + exceptionallyCf.getNow(n) ).getCause()); assertTrue(cancelledCf.isCancelled()); @@ -682,14 +680,14 @@ void test_similarities_and_differences_between_cancelled_and_exceptionally() thr assertTrue(cancelledCf.isDone()); assertTrue(exceptionallyCf.isDone()); - assertEquals(42, cancelledCf.exceptionally(throwable -> { + assertEquals(n, cancelledCf.exceptionally(throwable -> { assertInstanceOf(CancellationException.class, throwable); assertNull(throwable.getCause()); - return 42; + return n; }).get()); - assertEquals(42, exceptionallyCf.exceptionally(throwable -> { + assertEquals(n, exceptionallyCf.exceptionally(throwable -> { assertSame(rte, throwable); - return 42; + return n; }).get()); } @@ -723,7 +721,7 @@ void nested_exception() throws Exception { // auto unwrap first level CompletionException checkNo1MoreLevelForCompletionException(cf); - cf = cffuFactory.completedFuture(42); + cf = cffuFactory.completedFuture(n); // auto unwrap first level CompletionException checkNo1MoreLevelForCompletionException(cf.thenRun(() -> { throw new CompletionException(rte); @@ -734,7 +732,7 @@ void nested_exception() throws Exception { // auto unwrap first level ExecutionException check1MoreLevelForExecutionException(cf); - cf = cffuFactory.completedFuture(42); + cf = cffuFactory.completedFuture(n); // auto unwrap first level ExecutionException check1MoreLevelForExecutionException(cf.thenRun(() -> TestUtils.sneakyThrow(new ExecutionException(rte)) @@ -770,14 +768,16 @@ private void check1MoreLevelForExecutionException(Cffu cf) throws Excepti @BeforeAll static void beforeAll() { - executorService = TestThreadPoolManager.createThreadPool(hello); + executorService = TestingExecutorUtils.createThreadPool(hello); cffuFactory = CffuFactory.builder(executorService).build(); - anotherExecutorService = TestThreadPoolManager.createThreadPool(hello, true); + anotherExecutorService = TestingExecutorUtils.createThreadPool(hello, true); + + TestingExecutorUtils.warmupExecutorService(executorService, anotherExecutorService); } @AfterAll static void afterAll() { - TestThreadPoolManager.shutdownExecutorService(executorService, anotherExecutorService); + TestingExecutorUtils.shutdownExecutorService(executorService, anotherExecutorService); } } diff --git a/cffu-core/src/test/java/io/foldright/compatibility_test/CompletableFutureApiCompatibilityTest.java b/cffu-core/src/test/java/io/foldright/compatibility_test/CompletableFutureApiCompatibilityTest.java index 7fb11243..44a470c6 100644 --- a/cffu-core/src/test/java/io/foldright/compatibility_test/CompletableFutureApiCompatibilityTest.java +++ b/cffu-core/src/test/java/io/foldright/compatibility_test/CompletableFutureApiCompatibilityTest.java @@ -1,16 +1,7 @@ package io.foldright.compatibility_test; -//////////////////////////////////////////////////////////////////////////////// -// CompletableFutureApiCompatibilityTest and CffuApiCompatibilityTest are used to test -// the Cffu API compatibility to CompletableFuture. -// -// CffuApiCompatibilityTest.java file is auto generated -// from CompletableFutureApiCompatibilityTest.java -// by script gen_CffuApiCompatibilityTest.sh -//////////////////////////////////////////////////////////////////////////////// - -import io.foldright.test_utils.TestThreadPoolManager; import io.foldright.test_utils.TestUtils; +import io.foldright.test_utils.TestingExecutorUtils; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -20,15 +11,22 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; +import static io.foldright.test_utils.TestingConstants.*; import static org.junit.jupiter.api.Assertions.*; +/** + * {@link CompletableFutureApiCompatibilityTest} and {@link CffuApiCompatibilityTest} + * are used to check the Cffu API compatibility to CompletableFuture. + *

+ * {@code CffuApiCompatibilityTest.java} file is auto generated + * from {@code CompletableFutureApiCompatibilityTest.java} file + * by script {@code scripts/gen_CffuApiCompatibilityTest.sh}. + */ @SuppressWarnings("RedundantThrows") class CompletableFutureApiCompatibilityTest { private static final String hello = "CompletableFuture API Compatibility Test - Hello"; - private static final RuntimeException rte = new RuntimeException("Bang"); - //////////////////////////////////////////////////////////////////////////////// // Static Methods //////////////////////////////////////////////////////////////////////////////// @@ -112,8 +110,8 @@ void constructor() throws Exception { CompletableFuture cf = new CompletableFuture<>(); assertFalse(cf.isDone()); - cf.complete(42); - assertEquals(42, cf.get()); + cf.complete(n); + assertEquals(n, cf.get()); } //////////////////////////////////////// @@ -122,9 +120,9 @@ void constructor() throws Exception { @Test void staticMethods_allOf_anyOf() throws Exception { - CompletableFuture f1 = CompletableFuture.completedFuture(42); - CompletableFuture f2 = CompletableFuture.completedFuture(4242); - CompletableFuture f3 = CompletableFuture.completedFuture(424242); + CompletableFuture f1 = CompletableFuture.completedFuture(n); + CompletableFuture f2 = CompletableFuture.completedFuture(anotherN); + CompletableFuture f3 = CompletableFuture.completedFuture(nnn); assertNull(CompletableFuture.allOf().get()); assertNull(CompletableFuture.allOf(f1, f2).get()); @@ -168,7 +166,7 @@ void staticMethods_delayedExecutor() throws Exception { void simpleThenMethods() throws Exception { final AtomicReference holder = new AtomicReference<>(); - final CompletableFuture cf = CompletableFuture.completedFuture(42); + final CompletableFuture cf = CompletableFuture.completedFuture(n); cf.thenRun(() -> holder.set(hello)).get(); assertEquals(hello, holder.get()); @@ -201,12 +199,12 @@ void simpleThenMethods() throws Exception { }, anotherExecutorService).get(); assertEquals(hello, holder.get()); - assertEquals(43, cf.thenApply(x -> x + 1).get()); - assertEquals(44, cf.thenApplyAsync(x -> { + assertEquals(n + 1, cf.thenApply(x -> x + 1).get()); + assertEquals(n + 2, cf.thenApplyAsync(x -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); return x + 2; }).get()); - assertEquals(45, cf.thenApplyAsync(x -> { + assertEquals(n + 3, cf.thenApplyAsync(x -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); return x + 3; }, anotherExecutorService).get()); @@ -216,7 +214,7 @@ void simpleThenMethods() throws Exception { void thenBoth_Methods() throws Exception { final AtomicReference holder = new AtomicReference<>(); - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); cf.runAfterBoth(cf, () -> holder.set(hello)).get(); assertEquals(hello, holder.get()); @@ -249,12 +247,12 @@ void thenBoth_Methods() throws Exception { }, anotherExecutorService).get(); assertEquals(hello, holder.get()); - assertEquals(84, cf.thenCombine(cf, Integer::sum).get()); - assertEquals(84, cf.thenCombineAsync(cf, (a, b) -> { + assertEquals(n * 2, cf.thenCombine(cf, Integer::sum).get()); + assertEquals(n * 2, cf.thenCombineAsync(cf, (a, b) -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); return Integer.sum(a, b); }).get()); - assertEquals(84, cf.thenCombineAsync(cf, (a, b) -> { + assertEquals(n * 2, cf.thenCombineAsync(cf, (a, b) -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); return Integer.sum(a, b); }, anotherExecutorService).get()); @@ -264,7 +262,7 @@ void thenBoth_Methods() throws Exception { void thenEither_Methods() throws Exception { final AtomicReference holder = new AtomicReference<>(); - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); cf.runAfterEither(cf, () -> holder.set(hello)).get(); assertEquals(hello, holder.get()); @@ -297,12 +295,12 @@ void thenEither_Methods() throws Exception { }, anotherExecutorService).get(); assertEquals(hello, holder.get()); - assertEquals(43, cf.applyToEither(cf, x -> x + 1).get()); - assertEquals(44, cf.applyToEitherAsync(cf, x -> { + assertEquals(n + 1, cf.applyToEither(cf, x -> x + 1).get()); + assertEquals(n + 2, cf.applyToEitherAsync(cf, x -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); return x + 2; }).get()); - assertEquals(45, cf.applyToEitherAsync(cf, x -> { + assertEquals(n + 3, cf.applyToEitherAsync(cf, x -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); return x + 3; }, anotherExecutorService).get()); @@ -310,12 +308,12 @@ void thenEither_Methods() throws Exception { @Test void errorHandling_methods() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); CompletableFuture failed = TestUtils.safeNewFailedCompletableFuture(executorService, rte); // exceptionally - assertEquals(42, cf.exceptionally(t -> 43).get()); - assertEquals(43, failed.exceptionally(t -> 43).get()); + assertEquals(n, cf.exceptionally(t -> anotherN).get()); + assertEquals(anotherN, failed.exceptionally(t -> anotherN).get()); // below methods is tested in below test method // - exceptionallyAsync @@ -324,25 +322,25 @@ void errorHandling_methods() throws Exception { @Test @EnabledForJreRange(min = JRE.JAVA_12) void errorHandling_methods__Java9() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); CompletableFuture failed = TestUtils.safeNewFailedCompletableFuture(executorService, rte); - assertEquals(42, cf.exceptionallyAsync(t -> { + assertEquals(n, cf.exceptionallyAsync(t -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); - return 43; + return anotherN; }).get()); - assertEquals(43, failed.exceptionallyAsync(t -> { + assertEquals(anotherN, failed.exceptionallyAsync(t -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); - return 43; + return anotherN; }).get()); - assertEquals(42, cf.exceptionallyAsync(t -> { + assertEquals(n, cf.exceptionallyAsync(t -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); - return 44; + return anotherN; }, anotherExecutorService).get()); - assertEquals(44, failed.exceptionallyAsync(t -> { + assertEquals(anotherN, failed.exceptionallyAsync(t -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); - return 44; + return anotherN; }, anotherExecutorService).get()); } @@ -350,12 +348,12 @@ void errorHandling_methods__Java9() throws Exception { @EnabledForJreRange(min = JRE.JAVA_9) void timeoutControl_methods() throws Exception { // For completed - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); - assertEquals(42, + assertEquals(n, cf.orTimeout(20, TimeUnit.MILLISECONDS).get()); - assertEquals(42, - cf.completeOnTimeout(43, 20, TimeUnit.MILLISECONDS).get()); + assertEquals(n, + cf.completeOnTimeout(anotherN, 20, TimeUnit.MILLISECONDS).get()); // for incomplete CompletableFuture incomplete = new CompletableFuture<>(); @@ -364,21 +362,21 @@ void timeoutControl_methods() throws Exception { ).getCause().getClass()); CompletableFuture incomplete2 = new CompletableFuture<>(); - assertEquals(43, incomplete2.completeOnTimeout(43, 20, TimeUnit.MILLISECONDS).get()); + assertEquals(anotherN, incomplete2.completeOnTimeout(anotherN, 20, TimeUnit.MILLISECONDS).get()); } @Test void advancedMethods__thenCompose() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); - assertEquals(43, cf.thenCompose(x -> CompletableFuture.completedFuture(43)).get()); - assertEquals(44, cf.thenComposeAsync(x -> { + assertEquals(anotherN, cf.thenCompose(x -> CompletableFuture.completedFuture(anotherN)).get()); + assertEquals(anotherN, cf.thenComposeAsync(x -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); - return CompletableFuture.completedFuture(44); + return CompletableFuture.completedFuture(anotherN); }).get()); - assertEquals(45, cf.thenComposeAsync(x -> { + assertEquals(anotherN, cf.thenComposeAsync(x -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); - return CompletableFuture.completedFuture(45); + return CompletableFuture.completedFuture(anotherN); }, anotherExecutorService).get()); } @@ -386,44 +384,44 @@ void advancedMethods__thenCompose() throws Exception { @EnabledForJreRange(min = JRE.JAVA_12) void advancedMethods__exceptionallyCompose() throws Exception { // for success - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); - assertEquals(42, cf.exceptionallyCompose(x -> CompletableFuture.completedFuture(43)).get()); - assertEquals(42, cf.exceptionallyComposeAsync(x -> { + assertEquals(n, cf.exceptionallyCompose(x -> CompletableFuture.completedFuture(anotherN)).get()); + assertEquals(n, cf.exceptionallyComposeAsync(x -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); - return CompletableFuture.completedFuture(44); + return CompletableFuture.completedFuture(anotherN); }).get()); - assertEquals(42, cf.exceptionallyComposeAsync(x -> { + assertEquals(n, cf.exceptionallyComposeAsync(x -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); - return CompletableFuture.completedFuture(45); + return CompletableFuture.completedFuture(anotherN); }, anotherExecutorService).get()); // for failed CompletableFuture failed = TestUtils.safeNewFailedCompletableFuture(executorService, rte); - assertEquals(43, failed.exceptionallyCompose(x -> CompletableFuture.completedFuture(43)).get()); - assertEquals(44, failed.exceptionallyComposeAsync(x -> { + assertEquals(anotherN, failed.exceptionallyCompose(x -> CompletableFuture.completedFuture(anotherN)).get()); + assertEquals(anotherN, failed.exceptionallyComposeAsync(x -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); - return CompletableFuture.completedFuture(44); + return CompletableFuture.completedFuture(anotherN); }).get()); - assertEquals(45, failed.exceptionallyComposeAsync(x -> { + assertEquals(anotherN, failed.exceptionallyComposeAsync(x -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); - return CompletableFuture.completedFuture(45); + return CompletableFuture.completedFuture(anotherN); }, anotherExecutorService).get()); } @Test void advancedMethods__handle_whenComplete() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); - assertEquals(43, cf.handle((x, e) -> 43).get()); - assertEquals(44, cf.handleAsync((x, e) -> { + assertEquals(anotherN, cf.handle((x, e) -> anotherN).get()); + assertEquals(anotherN, cf.handleAsync((x, e) -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); - return 44; + return anotherN; }).get()); - assertEquals(45, cf.handleAsync((x, e) -> { + assertEquals(anotherN, cf.handleAsync((x, e) -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); - return 45; + return anotherN; }, anotherExecutorService).get()); final AtomicReference holder = new AtomicReference<>(); @@ -446,11 +444,11 @@ void advancedMethods__handle_whenComplete() throws Exception { @Test void readExplicitlyMethods() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); CompletableFuture failed = TestUtils.safeNewFailedCompletableFuture(executorService, rte); Integer r = cf.get(); - assertEquals(42, r); + assertEquals(n, r); assertSame(rte, assertThrowsExactly(ExecutionException.class, failed::get).getCause()); assertEquals(r, cf.get(1, TimeUnit.MILLISECONDS)); @@ -486,10 +484,10 @@ void readExplicitlyMethods() throws Exception { @Test @EnabledForJreRange(min = JRE.JAVA_19) void readExplicitlyMethods__Java19() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); CompletableFuture failed = TestUtils.safeNewFailedCompletableFuture(executorService, rte); Integer r = cf.get(); - assertEquals(42, r); + assertEquals(n, r); // resultNow assertEquals(r, cf.resultNow()); @@ -503,7 +501,7 @@ void readExplicitlyMethods__Java19() throws Exception { @Test @EnabledForJreRange(min = JRE.JAVA_19) /* GEN_MARK_KEEP */ void readExplicitlyMethods__Java19_CanNotCompatible() { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); CompletableFuture failed = TestUtils.safeNewFailedCompletableFuture(executorService, rte); CompletableFuture incomplete = new CompletableFuture<>(); @@ -515,20 +513,20 @@ void readExplicitlyMethods__Java19_CanNotCompatible() { @Test void writeMethods() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); CompletableFuture incomplete = new CompletableFuture<>(); - assertFalse(cf.complete(4242)); - assertEquals(42, cf.get()); + assertFalse(cf.complete(anotherN)); + assertEquals(n, cf.get()); - assertTrue(incomplete.complete(4242)); - assertEquals(4242, incomplete.get()); + assertTrue(incomplete.complete(anotherN)); + assertEquals(anotherN, incomplete.get()); // below methods is tested in below test method // - completeAsync // completeExceptionally assertFalse(cf.completeExceptionally(rte)); - assertEquals(42, cf.get()); + assertEquals(n, cf.get()); incomplete = new CompletableFuture<>(); assertTrue(incomplete.completeExceptionally(rte)); @@ -543,27 +541,27 @@ void writeMethods() throws Exception { @Test @EnabledForJreRange(min = JRE.JAVA_9) void writeMethods__Java9() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); // completeAsync - assertEquals(42, cf.completeAsync(() -> { + assertEquals(n, cf.completeAsync(() -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); - return 4242; + return anotherN; }).get()); - assertEquals(42, cf.completeAsync(() -> { + assertEquals(n, cf.completeAsync(() -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); - return 424242; + return anotherN; }, anotherExecutorService).get()); CompletableFuture incomplete = new CompletableFuture<>(); - assertEquals(4242, incomplete.completeAsync(() -> { + assertEquals(anotherN, incomplete.completeAsync(() -> { TestUtils.assertCompletableFutureRunInDefaultThread(executorService); - return 4242; + return anotherN; }).get()); incomplete = new CompletableFuture<>(); - assertEquals(424242, incomplete.completeAsync(() -> { + assertEquals(anotherN, incomplete.completeAsync(() -> { TestUtils.assertCompletableFutureRunInThreadOf(anotherExecutorService); - return 424242; + return anotherN; }, anotherExecutorService).get()); RuntimeException ex = new RuntimeException(); @@ -584,28 +582,28 @@ void reConfigMethods() throws Exception { // - minimalCompletionStage // - copy - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); // toCompletableFuture - assertEquals(42, cf.toCompletableFuture().get()); + assertEquals(n, cf.toCompletableFuture().get()); } @Test @EnabledForJreRange(min = JRE.JAVA_9) void reConfigMethods__Java9() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); // minimalCompletionStage TestUtils.shouldBeMinimalStage((CompletableFuture) cf.minimalCompletionStage()); // copy - assertEquals(42, cf.copy().get()); + assertEquals(n, cf.copy().get()); } @Test @EnabledForJreRange(min = JRE.JAVA_9) void test_getterMethods() { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); // defaultExecutor assertNotNull(cf.defaultExecutor()); @@ -613,7 +611,7 @@ void test_getterMethods() { @Test void test_inspectionMethods() { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); // getNumberOfDependents assertNotEquals(-1, cf.getNumberOfDependents()); @@ -621,11 +619,11 @@ void test_inspectionMethods() { @Test void test_dangerousMethods() throws Exception { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); // obtrudeValue - cf.obtrudeValue(44); - assertEquals(44, cf.get()); + cf.obtrudeValue(anotherN); + assertEquals(anotherN, cf.get()); // obtrudeException cf.obtrudeException(rte); @@ -635,7 +633,7 @@ void test_dangerousMethods() throws Exception { @Test @EnabledForJreRange(min = JRE.JAVA_9) void test_forApiCompatibility() { - CompletableFuture cf = CompletableFuture.completedFuture(42); + CompletableFuture cf = CompletableFuture.completedFuture(n); // newIncompleteFuture assertFalse(cf.newIncompleteFuture().isDone()); @@ -671,10 +669,10 @@ void test_similarities_and_differences_between_cancelled_and_exceptionally() thr assertSame(rte, assertThrowsExactly(CompletionException.class, exceptionallyCf::join).getCause()); assertThrowsExactly(CancellationException.class, () -> - cancelledCf.getNow(42) + cancelledCf.getNow(n) ); assertSame(rte, assertThrowsExactly(CompletionException.class, () -> - exceptionallyCf.getNow(42) + exceptionallyCf.getNow(n) ).getCause()); assertTrue(cancelledCf.isCancelled()); @@ -690,14 +688,14 @@ void test_similarities_and_differences_between_cancelled_and_exceptionally() thr assertTrue(cancelledCf.isDone()); assertTrue(exceptionallyCf.isDone()); - assertEquals(42, cancelledCf.exceptionally(throwable -> { + assertEquals(n, cancelledCf.exceptionally(throwable -> { assertInstanceOf(CancellationException.class, throwable); assertNull(throwable.getCause()); - return 42; + return n; }).get()); - assertEquals(42, exceptionallyCf.exceptionally(throwable -> { + assertEquals(n, exceptionallyCf.exceptionally(throwable -> { assertSame(rte, throwable); - return 42; + return n; }).get()); } @@ -732,7 +730,7 @@ void nested_exception() throws Exception { // auto unwrap first level CompletionException checkNo1MoreLevelForCompletionException(cf); - cf = CompletableFuture.completedFuture(42); + cf = CompletableFuture.completedFuture(n); // auto unwrap first level CompletionException checkNo1MoreLevelForCompletionException(cf.thenRun(() -> { throw new CompletionException(rte); @@ -743,7 +741,7 @@ void nested_exception() throws Exception { // auto unwrap first level ExecutionException check1MoreLevelForExecutionException(cf); - cf = CompletableFuture.completedFuture(42); + cf = CompletableFuture.completedFuture(n); // auto unwrap first level ExecutionException check1MoreLevelForExecutionException(cf.thenRun(() -> TestUtils.sneakyThrow(new ExecutionException(rte)) @@ -779,14 +777,16 @@ private void check1MoreLevelForExecutionException(CompletableFuture cf) t @BeforeAll static void beforeAll() { - executorService = TestThreadPoolManager.createThreadPool(hello); + executorService = TestingExecutorUtils.createThreadPool(hello); /* GEN_MARK_FACTORY_INIT */ - anotherExecutorService = TestThreadPoolManager.createThreadPool(hello, true); + anotherExecutorService = TestingExecutorUtils.createThreadPool(hello, true); + + TestingExecutorUtils.warmupExecutorService(executorService, anotherExecutorService); } @AfterAll static void afterAll() { - TestThreadPoolManager.shutdownExecutorService(executorService, anotherExecutorService); + TestingExecutorUtils.shutdownExecutorService(executorService, anotherExecutorService); } } diff --git a/cffu-core/src/test/java/io/foldright/demo/ConcurrencyStrategyDemo.java b/cffu-core/src/test/java/io/foldright/demo/ConcurrencyStrategyDemo.java index eb19595e..359f7880 100644 --- a/cffu-core/src/test/java/io/foldright/demo/ConcurrencyStrategyDemo.java +++ b/cffu-core/src/test/java/io/foldright/demo/ConcurrencyStrategyDemo.java @@ -12,6 +12,7 @@ import static io.foldright.cffu.CompletableFutureUtils.*; +@SuppressWarnings({"ThrowablePrintedToSystemOut", "SameParameterValue"}) public class ConcurrencyStrategyDemo { public static final ExecutorService myBizExecutor = Executors.newCachedThreadPool(); public static final CffuFactory cffuFactory = CffuFactory.builder(myBizExecutor).build(); diff --git a/cffu-core/src/test/java/io/foldright/showcases/CompletableFutureUsageShowcaseTest.kt b/cffu-core/src/test/java/io/foldright/study/CompletableFutureUsageStudyCaseTest.kt similarity index 91% rename from cffu-core/src/test/java/io/foldright/showcases/CompletableFutureUsageShowcaseTest.kt rename to cffu-core/src/test/java/io/foldright/study/CompletableFutureUsageStudyCaseTest.kt index d8597be6..f68549b4 100644 --- a/cffu-core/src/test/java/io/foldright/showcases/CompletableFutureUsageShowcaseTest.kt +++ b/cffu-core/src/test/java/io/foldright/study/CompletableFutureUsageStudyCaseTest.kt @@ -1,4 +1,4 @@ -package io.foldright.showcases +package io.foldright.study import io.foldright.test_utils.* import io.kotest.core.spec.style.FunSpec @@ -17,10 +17,10 @@ import java.lang.Thread.currentThread import java.util.concurrent.* import java.util.concurrent.atomic.AtomicBoolean -class CompletableFutureUsageShowcaseTest : FunSpec({ - val n = 42 - val anotherN = 424242 - val rte = RuntimeException("Bang") +/** + * Study CompletableFuture usage. + */ +class CompletableFutureUsageStudyCaseTest : FunSpec({ test("execution thread/executor behavior: then*(non-Async) operations chained after COMPLETED CF(completed by immediate value), trigger by then* invocation and run in place SEQUENTIALLY").config( invocations = 100 @@ -71,7 +71,7 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ sequenceChecker.assertSeq("supplyAsync completed CF", seq++) currentThread() shouldNotBe mainThread - assertRunInExecutor(testThreadPoolExecutor) + assertRunningInExecutor(testThreadPoolExecutor) n }, testThreadPoolExecutor) @@ -123,12 +123,12 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ blocker.block() currentThread() shouldNotBe mainThread - assertNotRunInExecutor(testThreadPoolExecutor) + assertNotRunningInExecutor(testThreadPoolExecutor) } .thenRunAsync({ thenNonAsyncOpThread = currentThread() - assertRunInExecutor(testThreadPoolExecutor) + assertRunningInExecutor(testThreadPoolExecutor) }, testThreadPoolExecutor) // ! switch executor ! .thenApply { // when NOT async, @@ -152,7 +152,7 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ // // - executor is NOT inherited after switch! // - use the DEFAULT EXECUTOR of CompletableFuture, if no executor specified. - assertNotRunInExecutor(testThreadPoolExecutor) + assertNotRunningInExecutor(testThreadPoolExecutor) } } f.join() @@ -160,7 +160,7 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ fun checkThreadSwitchBehaviorThenApplyAsync(executor: ExecutorService) { val f0 = CompletableFuture.supplyAsync({ - assertRunInExecutor(executor) + assertRunningInExecutor(executor) emptyList() }, executor) @@ -245,7 +245,7 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ sequenceChecker.assertSeq("create exceptionallyAsync", 1) currentThread() shouldNotBe mainThread - assertRunInExecutor(testThreadPoolExecutor) + assertRunningInExecutor(testThreadPoolExecutor) it.shouldBeTypeOf() it.cause shouldBeSameInstanceAs rte @@ -312,7 +312,7 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ f0.completeAsync({ sequenceChecker.assertSeq("in completeAsync", 2) - assertRunInExecutor(testThreadPoolExecutor) + assertRunningInExecutor(testThreadPoolExecutor) "done" }, testThreadPoolExecutor) @@ -322,20 +322,14 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ } test("timeout control: normally completed with replacement value").config(enabledIf = java9Plus) { - val f = CompletableFuture.supplyAsync { - sleep(1000) - n - }.completeOnTimeout(anotherN, 1, TimeUnit.MILLISECONDS) + val f = completeLaterCf(n) + .completeOnTimeout(anotherN, 1, TimeUnit.MILLISECONDS) f.await() shouldBe anotherN } test("timeout control: exceptionally completed with java.util.concurrent.TimeoutException").config(enabledIf = java9Plus) { - val f = CompletableFuture - .supplyAsync { - sleep(1000) - n - } + val f = completeLaterCf(n) .orTimeout(1, TimeUnit.MILLISECONDS) .exceptionally { it.shouldBeTypeOf() @@ -356,17 +350,14 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ }, delayer).await() // if run in CI environment, use large tolerance 50ms, because CI environment is more unstable. - val tolerance = if (isCiEnv()) 50 else 10 + val tolerance = if (isCiEnv()) 50 else 20 duration.shouldBeBetween(delay, delay + tolerance) } xtest("performance CF then*").config(invocations = 10) { val times = 1_000_000 - var f = CompletableFuture.supplyAsync( - { sleep(); currentTimeMillis() }, - testThreadPoolExecutor - ) + var f = completeLaterCf({ currentTimeMillis() }, executor = testForkJoinPoolExecutor) val tick = currentTimeMillis() repeat(times) { @@ -389,13 +380,13 @@ class CompletableFutureUsageShowcaseTest : FunSpec({ cf.minimalCompletionStage().handle { _, t -> t.shouldBeTypeOf() t.cause shouldBeSameInstanceAs rte - 42 - }.toCompletableFuture().await() shouldBe 42 + n + }.toCompletableFuture().await() shouldBe n cf.thenApply { it }.handle { _, t -> t.shouldBeTypeOf() t.cause shouldBeSameInstanceAs rte - 42 - }.toCompletableFuture().await() shouldBe 42 + n + }.toCompletableFuture().await() shouldBe n } }) diff --git a/cffu-core/src/test/java/io/foldright/test_utils/TestUtils.kt b/cffu-core/src/test/java/io/foldright/test_utils/TestUtils.kt index 5ce6945f..763754d0 100644 --- a/cffu-core/src/test/java/io/foldright/test_utils/TestUtils.kt +++ b/cffu-core/src/test/java/io/foldright/test_utils/TestUtils.kt @@ -14,49 +14,43 @@ import io.kotest.matchers.shouldBe import org.apache.commons.lang3.JavaVersion import org.apache.commons.lang3.SystemUtils.isJavaVersionAtLeast import java.util.concurrent.* +import java.util.function.Supplier //////////////////////////////////////////////////////////////////////////////// -// constants for testing +// region# util methods for testing //////////////////////////////////////////////////////////////////////////////// -const val n = 42 -const val anotherN = 424242 -const val s = "S42" -const val d = 42.1 - -@JvmField -val rte = RuntimeException("Bang") - -@JvmField -val anotherRte = RuntimeException("AnotherBang") - -//////////////////////////////////////////////////////////////////////////////// -// util methods for testing -//////////////////////////////////////////////////////////////////////////////// - -fun createIncompleteFuture(): CompletableFuture = CompletableFuture() +fun incompleteCf(): CompletableFuture = CompletableFuture() @JvmOverloads -fun createFutureCompleteLater(value: T, millis: Long = 100): CompletableFuture = CompletableFuture.supplyAsync { +fun completeLaterCf(value: T, millis: Long = 100): CompletableFuture = CompletableFuture.supplyAsync { sleep(millis) value } -fun createCancelledFuture(): CompletableFuture = CompletableFuture().apply { - cancel(false) +@JvmOverloads +fun completeLaterCf( + value: () -> T, millis: Long = 100, executor: Executor = DEFAULT_EXECUTOR +): CompletableFuture { + val action = Supplier { + sleep(millis) + value() + } + return if (executor === DEFAULT_EXECUTOR) CompletableFuture.supplyAsync(action) + else CompletableFuture.supplyAsync(action, executor) } -/** - * sleep without throwing checked exception - */ @JvmOverloads -fun sleep(millis: Long = 10) { - Thread.sleep(millis) +fun cancelledFuture(mayInterruptIfRunning: Boolean = false): CompletableFuture = CompletableFuture().apply { + cancel(mayInterruptIfRunning) } +private val DEFAULT_EXECUTOR: Executor = Executor { /* do nothing */ } + +// endregion //////////////////////////////////////////////////////////////////////////////// -// Helper functions for api compatibility test: +// region# Helper functions for API compatibility test // - CompletableFutureApiCompatibilityTest // - CffuApiCompatibilityTest //////////////////////////////////////////////////////////////////////////////// @@ -78,27 +72,53 @@ fun safeNewFailedCffu(executorService: ExecutorService, t: Throwable): Cffu< return CffuFactory.builder(executorService).build().failedFuture(t) } -@Suppress("UNUSED_PARAMETER") fun assertCompletableFutureRunInDefaultThread(executorService: ExecutorService) { - // do nothing + assertNotRunningInExecutor(executorService) } fun assertCompletableFutureRunInThreadOf(executorService: ExecutorService) { - assertRunInExecutor(executorService) + assertRunningInExecutor(executorService) } fun assertCffuRunInDefaultThread(executorService: ExecutorService) { - assertRunInExecutor(executorService) + assertRunningInExecutor(executorService) } fun assertCffuRunInThreadOf(executorService: ExecutorService) { - assertRunInExecutor(executorService) + assertRunningInExecutor(executorService) } +// endregion //////////////////////////////////////////////////////////////////////////////// -// Simple util functions +// region# some simple util functions //////////////////////////////////////////////////////////////////////////////// +/** + * sleep without throwing checked exception + */ +@JvmOverloads +fun sleep(millis: Long = 10) { + Thread.sleep(millis) +} + +/** + * sleep short time + */ +@JvmOverloads +fun nap(millis: Long = 10) { + Thread.sleep(millis) +} + +/** + * sleep long time + */ +@JvmOverloads +fun snoreZzz(millis: Long = 100) { + Thread.sleep(millis) +} + +fun sneakyThrow(ex: Throwable): Unit = throw ex + fun merge(list1: List, list2: List) = list1.merge(list2) @JvmName("mergeExt") @@ -109,10 +129,9 @@ infix fun List.merge(other: List): List = mutableListOf().apply fun addCurrentThreadName(names: List) = names + Thread.currentThread().name -fun sneakyThrow(ex: Throwable): Unit = throw ex - +// endregion //////////////////////////////////////////////////////////////////////////////// -// Assertion functions for CF/Cffu +// region# Assertion functions for CF/Cffu //////////////////////////////////////////////////////////////////////////////// fun CompletableFuture.shouldBeMinimalStage() { @@ -756,8 +775,9 @@ private fun CompletionStage.shouldCompletionStageMethodsAllowed(recursive toString() } +// endregion //////////////////////////////////////////////////////////////////////////////// -// Java Version Checker +// region# Java Version Checker //////////////////////////////////////////////////////////////////////////////// fun isJava9Plus() = isJavaVersionAtLeast(JavaVersion.JAVA_9) @@ -770,8 +790,9 @@ fun isJava19Plus(): Boolean = isJavaVersionAtLeast(JavaVersion.JAVA_19) // https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables fun isCiEnv(): Boolean = System.getenv("CI")?.lowercase() == "true" +// endregion //////////////////////////////////////////////////////////////////////////////// -// Kotest conditions +// region# Kotest conditions //////////////////////////////////////////////////////////////////////////////// val java9Plus: (TestCase) -> Boolean = { isJava9Plus() } diff --git a/cffu-core/src/test/java/io/foldright/test_utils/TestingConstants.kt b/cffu-core/src/test/java/io/foldright/test_utils/TestingConstants.kt new file mode 100644 index 00000000..a5fe0384 --- /dev/null +++ b/cffu-core/src/test/java/io/foldright/test_utils/TestingConstants.kt @@ -0,0 +1,20 @@ +@file:JvmName("TestingConstants") + +package io.foldright.test_utils + + +//////////////////////////////////////////////////////////////////////////////// +// constants for testing +//////////////////////////////////////////////////////////////////////////////// + +const val n = 42 +const val anotherN = 4242 +const val nnn = 424242 +const val s = "S42" +const val d = 42.5 + +@JvmField +val rte = RuntimeException("Bang") + +@JvmField +val anotherRte = RuntimeException("AnotherBang") diff --git a/cffu-core/src/test/java/io/foldright/test_utils/TestThreadPoolManager.kt b/cffu-core/src/test/java/io/foldright/test_utils/TestingExecutorUtils.kt similarity index 67% rename from cffu-core/src/test/java/io/foldright/test_utils/TestThreadPoolManager.kt rename to cffu-core/src/test/java/io/foldright/test_utils/TestingExecutorUtils.kt index 4c49c13c..8487da5b 100644 --- a/cffu-core/src/test/java/io/foldright/test_utils/TestThreadPoolManager.kt +++ b/cffu-core/src/test/java/io/foldright/test_utils/TestingExecutorUtils.kt @@ -1,10 +1,9 @@ -@file:JvmName("TestThreadPoolManager") +@file:JvmName("TestingExecutorUtils") package io.foldright.test_utils import io.foldright.cffu.CffuFactory import io.kotest.core.config.AbstractProjectConfig -import io.kotest.core.listeners.AfterProjectListener import io.kotest.core.listeners.BeforeProjectListener import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue @@ -14,22 +13,33 @@ import java.util.concurrent.atomic.AtomicLong import kotlin.random.Random import kotlin.random.nextULong +//////////////////////////////////////////////////////////////////////////////// +// region# test executors for kotest +//////////////////////////////////////////////////////////////////////////////// val THREAD_COUNT_OF_POOL: Int = (Runtime.getRuntime().availableProcessors() * 2).coerceAtLeast(4).coerceAtMost(15) +val testThreadPoolExecutor: ExecutorService = + createThreadPool("CompletableFutureUseTest_ThreadPool") + +val testCffuFactory: CffuFactory = CffuFactory.builder(testThreadPoolExecutor).build() + +val testForkJoinPoolExecutor: ExecutorService = + createThreadPool("CompletableFutureUseTest_ForkJoinPool", true) + @JvmOverloads fun createThreadPool(threadNamePrefix: String, isForkJoin: Boolean = false): ExecutorService { val counter = AtomicLong() - val prefix = "${threadNamePrefix}_${Random.nextULong()}" + val prefix = "${threadNamePrefix}_${Random.nextULong()}_" val executorService = if (!isForkJoin) ThreadPoolExecutor( /* corePoolSize = */ THREAD_COUNT_OF_POOL, /* maximumPoolSize = */ THREAD_COUNT_OF_POOL, - /* keepAliveTime = */ 1, /* unit = */ TimeUnit.DAYS, + /* keepAliveTime = */ 2, TimeUnit.MINUTES, /* workQueue = */ ArrayBlockingQueue(5000) ) { r -> Thread(r).apply { - name = "${prefix}_${counter.getAndIncrement()}" + name = "${prefix}${counter.getAndIncrement()}" isDaemon = true } } @@ -37,43 +47,55 @@ fun createThreadPool(threadNamePrefix: String, isForkJoin: Boolean = false): Exe ForkJoinPool( /* parallelism = */ THREAD_COUNT_OF_POOL,/* factory = */ { fjPool -> ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(fjPool).apply { - name = "${prefix}_${counter.getAndIncrement()}" + name = "${prefix}${counter.getAndIncrement()}" } }, /* handler = */ null, /* asyncMode = */ false ) return object : ExecutorService by executorService, ThreadPoolAcquaintance { - override fun isMyThread(thread: Thread): Boolean = thread.name.startsWith(prefix) + override fun own(thread: Thread): Boolean = thread.name.startsWith(prefix) override fun unwrap(): ExecutorService = executorService - override fun toString(): String = "test ${if (isForkJoin) "ForkJoinPool" else "ThreadPoolExecutor"} $prefix" + override fun toString(): String = + "test ${if (isForkJoin) "ForkJoinPool" else "ThreadPoolExecutor"} with thread name prefix `$prefix`" } } -private fun Executor.doesOwnThread(thread: Thread): Boolean = (this as ThreadPoolAcquaintance).isMyThread(thread) - private interface ThreadPoolAcquaintance { - fun isMyThread(thread: Thread): Boolean + fun own(thread: Thread): Boolean fun unwrap(): ExecutorService } -fun isRunInExecutor(executor: Executor): Boolean = - executor.doesOwnThread(currentThread()) +// endregion +//////////////////////////////////////////////////////////////////////////////// +// region# check methods for thread/executor relationship +//////////////////////////////////////////////////////////////////////////////// -fun assertRunInExecutor(executor: Executor) { - isRunInExecutor(executor).shouldBeTrue() +fun assertRunningInExecutor(executor: Executor) { + isRunningInExecutor(executor).shouldBeTrue() } -fun assertNotRunInExecutor(executor: Executor) { - executor.doesOwnThread(currentThread()).shouldBeFalse() +fun assertNotRunningInExecutor(executor: Executor) { + isRunningInExecutor(executor).shouldBeFalse() } +private fun isRunningInExecutor(executor: Executor): Boolean = + currentThread().belongsTo(executor) + +private fun Thread.belongsTo(executor: Executor): Boolean = + (executor as ThreadPoolAcquaintance).own(this) + +// endregion +//////////////////////////////////////////////////////////////////////////////// +// region# util method for executors +//////////////////////////////////////////////////////////////////////////////// + fun warmupExecutorService(vararg executors: ExecutorService) { executors.flatMap { executor -> (0 until THREAD_COUNT_OF_POOL * 2).map { - executor.submit { sleep() } + executor.submit { nap() } } }.forEach { f: Future<*> -> f.get() } } @@ -90,24 +112,18 @@ fun shutdownExecutorService(vararg executors: ExecutorService) { } } +// endregion //////////////////////////////////////////////////////////////////////////////// -// executors for kotest +// region# Kotest Listener //////////////////////////////////////////////////////////////////////////////// -val testThreadPoolExecutor: ExecutorService = - createThreadPool("CompletableFutureUseTest_ThreadPool") - -val testCffuFactory: CffuFactory = CffuFactory.builder(testThreadPoolExecutor).build() - -val testForkJoinPoolExecutor: ExecutorService = - createThreadPool("CompletableFutureUseTest_ForkJoinPool", true) - /** * https://kotest.io/docs/framework/project-config.html */ -object CffuKotestProjectConfig : AbstractProjectConfig(), BeforeProjectListener, AfterProjectListener { +object CffuKotestProjectConfig : AbstractProjectConfig(), BeforeProjectListener { override suspend fun beforeProject() { println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") + println("call beforeProject") println("Env Infos:") println("Parallelism of ForkJoinPool: ${ForkJoinPool.getCommonPoolParallelism()}") println("Available Processors of Runtime: ${Runtime.getRuntime().availableProcessors()}") @@ -118,8 +134,4 @@ object CffuKotestProjectConfig : AbstractProjectConfig(), BeforeProjectListener, warmupExecutorService(testThreadPoolExecutor, testForkJoinPoolExecutor) } - - override suspend fun afterProject() { - shutdownExecutorService(testThreadPoolExecutor, testForkJoinPoolExecutor) - } } diff --git a/cffu-kotlin/src/test/java/io/foldright/cffu/generics/TypeParameterDeclarationTest.java b/cffu-kotlin/src/test/java/io/foldright/cffu/generics/TypeParameterDeclarationTest.java index 17d0671f..77b74b3c 100644 --- a/cffu-kotlin/src/test/java/io/foldright/cffu/generics/TypeParameterDeclarationTest.java +++ b/cffu-kotlin/src/test/java/io/foldright/cffu/generics/TypeParameterDeclarationTest.java @@ -1,13 +1,10 @@ package io.foldright.cffu.generics; import io.foldright.cffu.CompletableFutureUtils; -import io.foldright.test_utils.TestThreadPoolManager; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Supplier; @@ -20,7 +17,7 @@ /** * Checks type parameter declaration, Variance(covariance/contravariance) */ -@SuppressWarnings({"UnnecessaryLocalVariable", "unused", "RedundantThrows"}) +@SuppressWarnings({"unused", "RedundantThrows"}) public class TypeParameterDeclarationTest { private static final CompletableFuture f = completedFuture(42); @@ -34,12 +31,12 @@ void checkTypeParameterDeclaration_peek_completeAsync() throws Exception { }; CompletableFutureUtils.peek(fe, c).get(); CompletableFutureUtils.peekAsync(fe, c).get(); - CompletableFutureUtils.peekAsync(fe, c, executorService).get(); + CompletableFutureUtils.peekAsync(fe, c, executor).get(); final Supplier s = () -> 0; fs.complete(0); CompletableFutureUtils.completeAsync(fs, s).complete(1); - CompletableFutureUtils.completeAsync(fs, s, executorService).complete(1); + CompletableFutureUtils.completeAsync(fs, s, executor).complete(1); CompletableFuture ffe = orTimeout(fe, 1, TimeUnit.MILLISECONDS); CompletableFuture ffs = orTimeout(fs, 1, TimeUnit.MILLISECONDS); @@ -62,15 +59,6 @@ void checkTypeParameterDeclaration_get() throws Exception { Object iq = fq.get(); } - private static ExecutorService executorService; + private final Executor executor = Runnable::run; - @BeforeAll - static void beforeAll() { - executorService = TestThreadPoolManager.createThreadPool("TypeParameterDeclarationTest"); - } - - @AfterAll - static void afterAll() { - TestThreadPoolManager.shutdownExecutorService(executorService); - } } diff --git a/cffu-kotlin/src/test/java/io/foldright/cffu/test/CffuExtensionsTest.kt b/cffu-kotlin/src/test/java/io/foldright/cffu/test/CffuExtensionsTest.kt index 506e2df9..190368ea 100644 --- a/cffu-kotlin/src/test/java/io/foldright/cffu/test/CffuExtensionsTest.kt +++ b/cffu-kotlin/src/test/java/io/foldright/cffu/test/CffuExtensionsTest.kt @@ -2,9 +2,10 @@ package io.foldright.cffu.test import io.foldright.cffu.Cffu import io.foldright.cffu.CffuFactory -import io.foldright.cffu.DefaultExecutorTestUtils import io.foldright.cffu.NoCfsProvidedException import io.foldright.cffu.kotlin.* +import io.foldright.cffu.unwrapMadeExecutor +import io.foldright.test_utils.n import io.foldright.test_utils.testCffuFactory import io.foldright.test_utils.testForkJoinPoolExecutor import io.foldright.test_utils.testThreadPoolExecutor @@ -18,13 +19,10 @@ import io.kotest.matchers.types.shouldBeTypeOf import io.kotest.matchers.types.shouldNotBeSameInstanceAs import io.kotest.matchers.types.shouldNotBeTypeOf import kotlinx.coroutines.future.await -import java.util.concurrent.* - -const val n = 42 -const val anotherN = 4242 -const val s = "43" -const val d = 44.0 -val rte = RuntimeException("Bang") +import java.util.concurrent.CompletableFuture +import java.util.concurrent.CompletionStage +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit class CffuExtensionsTest : FunSpec({ @@ -76,115 +74,115 @@ class CffuExtensionsTest : FunSpec({ // collection listOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) listOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsOfCffu().await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsOfCffu().await() shouldBe listOf(n, n + 1, n + 2) setOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) listOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), - ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), + ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) setOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), - ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), + ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) // Array arrayOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) arrayOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsOfCffu().await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsOfCffu().await() shouldBe listOf(n, n + 1, n + 2) arrayOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), - ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), + ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) // FIXME: java.lang.ClassCastException if not providing the type parameter explicitly: // class [Ljava.lang.Object; cannot be cast to class [Ljava.util.concurrent.CompletionStage; arrayOf>( - CompletableFuture.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + CompletableFuture.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) //////////////////////////////////////// // collection listOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allOfCffu(testCffuFactory).await().shouldBeNull() listOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allOfCffu().await().shouldBeNull() setOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allOfCffu(testCffuFactory).await().shouldBeNull() listOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), ).allOfCffu(testCffuFactory).await().shouldBeNull() setOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), ).allOfCffu(testCffuFactory).await().shouldBeNull() // Array arrayOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allOfCffu(testCffuFactory).await().shouldBeNull() arrayOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allOfCffu().await().shouldBeNull() arrayOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), ).allOfCffu(testCffuFactory).await().shouldBeNull() //////////////////////////////////////// @@ -192,107 +190,107 @@ class CffuExtensionsTest : FunSpec({ // collection listOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) listOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsFastFailOfCffu().await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsFastFailOfCffu().await() shouldBe listOf(n, n + 1, n + 2) setOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) listOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), - ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), + ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) setOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), - ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), + ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) // Array arrayOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) arrayOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), - ).allResultsFastFailOfCffu().await() shouldBe listOf(42, 43, 44) + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), + ).allResultsFastFailOfCffu().await() shouldBe listOf(n, n + 1, n + 2) arrayOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), - ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(42, 43, 44) + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), + ).allResultsFastFailOfCffu(testCffuFactory).await() shouldBe listOf(n, n + 1, n + 2) //////////////////////////////////////// // collection listOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allFastFailOfCffu(testCffuFactory).await().shouldBeNull() listOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allFastFailOfCffu().await().shouldBeNull() setOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allFastFailOfCffu(testCffuFactory).await().shouldBeNull() listOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), ).allFastFailOfCffu(testCffuFactory).await().shouldBeNull() setOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), ).allFastFailOfCffu(testCffuFactory).await().shouldBeNull() // Array arrayOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allFastFailOfCffu(testCffuFactory).await().shouldBeNull() arrayOf( - testCffuFactory.completedFuture(42), - testCffuFactory.completedFuture(43), - testCffuFactory.completedFuture(44), + testCffuFactory.completedFuture(n), + testCffuFactory.completedFuture(n + 1), + testCffuFactory.completedFuture(n + 2), ).allFastFailOfCffu().await().shouldBeNull() arrayOf( - CompletableFuture.completedFuture(42), - CompletableFuture.completedFuture(43), - CompletableFuture.completedFuture(44), + CompletableFuture.completedFuture(n), + CompletableFuture.completedFuture(n + 1), + CompletableFuture.completedFuture(n + 2), ).allFastFailOfCffu(testCffuFactory).await().shouldBeNull() } @@ -301,40 +299,40 @@ class CffuExtensionsTest : FunSpec({ listOf( testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, 42) + testCffuFactory.completedFuture(n), + ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, n) setOf( testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS).await() shouldBe listOf(-1, 42) + testCffuFactory.completedFuture(n), + ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS).await() shouldBe listOf(-1, n) listOf( CompletableFuture(), - CompletableFuture.completedFuture(42), - ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, 42) + CompletableFuture.completedFuture(n), + ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, n) // Array arrayOf( testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, 42) + testCffuFactory.completedFuture(n), + ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, n) arrayOf( testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS).await() shouldBe listOf(-1, 42) + testCffuFactory.completedFuture(n), + ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS).await() shouldBe listOf(-1, n) arrayOf( CompletableFuture(), - CompletableFuture.completedFuture(42), - ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, 42) + CompletableFuture.completedFuture(n), + ).mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, n) // FIXME: java.lang.ClassCastException if not providing the type parameter explicitly: // class [Ljava.lang.Object; cannot be cast to class [Ljava.util.concurrent.CompletionStage; - arrayOf>(CompletableFuture(), testCffuFactory.completedFuture(42)) - .mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, 42) + arrayOf>(CompletableFuture(), testCffuFactory.completedFuture(n)) + .mostSuccessResultsOfCffu(-1, 10, TimeUnit.MILLISECONDS, testCffuFactory).await() shouldBe listOf(-1, n) } test("anyOf*") { @@ -343,52 +341,52 @@ class CffuExtensionsTest : FunSpec({ listOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anyOfCffu(testCffuFactory).await() shouldBe n listOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anyOfCffu().await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anyOfCffu().await() shouldBe n setOf( testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), + testCffuFactory.completedFuture(n), testCffuFactory.newIncompleteCffu(), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + ).anyOfCffu(testCffuFactory).await() shouldBe n listOf( CompletableFuture(), CompletableFuture(), - CompletableFuture.completedFuture(42), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + CompletableFuture.completedFuture(n), + ).anyOfCffu(testCffuFactory).await() shouldBe n setOf( CompletableFuture(), - CompletableFuture.completedFuture(42), + CompletableFuture.completedFuture(n), CompletableFuture(), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + ).anyOfCffu(testCffuFactory).await() shouldBe n // Array arrayOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anyOfCffu(testCffuFactory).await() shouldBe n arrayOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anyOfCffu().await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anyOfCffu().await() shouldBe n arrayOf( CompletableFuture(), CompletableFuture(), - CompletableFuture.completedFuture(42), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + CompletableFuture.completedFuture(n), + ).anyOfCffu(testCffuFactory).await() shouldBe n //////////////////////////////////////// @@ -397,52 +395,52 @@ class CffuExtensionsTest : FunSpec({ listOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anyOfCffu(testCffuFactory).await() shouldBe n listOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anyOfCffu().await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anyOfCffu().await() shouldBe n setOf( testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), + testCffuFactory.completedFuture(n), testCffuFactory.newIncompleteCffu(), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + ).anyOfCffu(testCffuFactory).await() shouldBe n listOf( CompletableFuture(), CompletableFuture(), - CompletableFuture.completedFuture(42), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + CompletableFuture.completedFuture(n), + ).anyOfCffu(testCffuFactory).await() shouldBe n setOf( CompletableFuture(), - CompletableFuture.completedFuture(42), + CompletableFuture.completedFuture(n), CompletableFuture(), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + ).anyOfCffu(testCffuFactory).await() shouldBe n // Array arrayOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anyOfCffu(testCffuFactory).await() shouldBe n arrayOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anyOfCffu().await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anyOfCffu().await() shouldBe n arrayOf( CompletableFuture(), CompletableFuture(), - CompletableFuture.completedFuture(42), - ).anyOfCffu(testCffuFactory).await() shouldBe 42 + CompletableFuture.completedFuture(n), + ).anyOfCffu(testCffuFactory).await() shouldBe n //////////////////////////////////////// @@ -451,52 +449,52 @@ class CffuExtensionsTest : FunSpec({ listOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n listOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anySuccessOfCffu().await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anySuccessOfCffu().await() shouldBe n setOf( testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), + testCffuFactory.completedFuture(n), testCffuFactory.newIncompleteCffu(), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n listOf( CompletableFuture(), CompletableFuture(), - CompletableFuture.completedFuture(42), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + CompletableFuture.completedFuture(n), + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n setOf( CompletableFuture(), - CompletableFuture.completedFuture(42), + CompletableFuture.completedFuture(n), CompletableFuture(), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n // Array arrayOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n arrayOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anySuccessOfCffu().await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anySuccessOfCffu().await() shouldBe n arrayOf( CompletableFuture(), CompletableFuture(), - CompletableFuture.completedFuture(42), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + CompletableFuture.completedFuture(n), + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n shouldThrow { arrayOf>().anySuccessOfCffu(testCffuFactory).await() @@ -509,52 +507,52 @@ class CffuExtensionsTest : FunSpec({ listOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n listOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anySuccessOfCffu().await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anySuccessOfCffu().await() shouldBe n setOf( testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), + testCffuFactory.completedFuture(n), testCffuFactory.newIncompleteCffu(), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n listOf( CompletableFuture(), CompletableFuture(), - CompletableFuture.completedFuture(42), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + CompletableFuture.completedFuture(n), + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n setOf( CompletableFuture(), - CompletableFuture.completedFuture(42), + CompletableFuture.completedFuture(n), CompletableFuture(), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n // Array arrayOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n arrayOf( testCffuFactory.newIncompleteCffu(), testCffuFactory.newIncompleteCffu(), - testCffuFactory.completedFuture(42), - ).anySuccessOfCffu().await() shouldBe 42 + testCffuFactory.completedFuture(n), + ).anySuccessOfCffu().await() shouldBe n arrayOf( CompletableFuture(), CompletableFuture(), - CompletableFuture.completedFuture(42), - ).anySuccessOfCffu(testCffuFactory).await() shouldBe 42 + CompletableFuture.completedFuture(n), + ).anySuccessOfCffu(testCffuFactory).await() shouldBe n } val cffuFactoryForOptional = CffuFactory.builder(Executors.newCachedThreadPool()).build() @@ -655,9 +653,3 @@ class CffuExtensionsTest : FunSpec({ } } }) - -fun CffuFactory.unwrapMadeExecutor(): Executor = - DefaultExecutorTestUtils.unwrapMadeExecutor(this) - -fun Cffu<*>.unwrapMadeExecutor(): Executor = - DefaultExecutorTestUtils.unwrapMadeExecutor(this) diff --git a/cffu-kotlin/src/test/java/io/foldright/cffu/test/CompletableFutureExtensionsTest.kt b/cffu-kotlin/src/test/java/io/foldright/cffu/test/CompletableFutureExtensionsTest.kt index b4631f09..e636858c 100644 --- a/cffu-kotlin/src/test/java/io/foldright/cffu/test/CompletableFutureExtensionsTest.kt +++ b/cffu-kotlin/src/test/java/io/foldright/cffu/test/CompletableFutureExtensionsTest.kt @@ -4,9 +4,7 @@ import io.foldright.cffu.CffuState import io.foldright.cffu.CompletableFutureUtils import io.foldright.cffu.NoCfsProvidedException import io.foldright.cffu.kotlin.* -import io.foldright.test_utils.createIncompleteFuture -import io.foldright.test_utils.sleep -import io.foldright.test_utils.testThreadPoolExecutor +import io.foldright.test_utils.* import io.kotest.assertions.throwables.shouldThrowExactly import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.booleans.shouldBeFalse @@ -27,125 +25,125 @@ import java.util.function.Function.identity class CompletableFutureExtensionsTest : FunSpec({ test("allOf*") { listOf( - completedFuture(42), - completedFuture(43), - completedFuture(44), - ).allResultsOfCompletableFuture().await() shouldBe listOf(42, 43, 44) + completedFuture(n), + completedFuture(n + 1), + completedFuture(n + 2), + ).allResultsOfCompletableFuture().await() shouldBe listOf(n, n + 1, n + 2) listOf>().allResultsOfCompletableFuture().await() shouldBe emptyList() setOf( - completedFuture(42), - completedFuture(43), - completedFuture(44), - ).allResultsOfCompletableFuture().await() shouldBe listOf(42, 43, 44) + completedFuture(n), + completedFuture(n + 1), + completedFuture(n + 2), + ).allResultsOfCompletableFuture().await() shouldBe listOf(n, n + 1, n + 2) arrayOf( - completedFuture(42), - completedFuture(43), - completedFuture(44), - ).allResultsOfCompletableFuture().await() shouldBe listOf(42, 43, 44) + completedFuture(n), + completedFuture(n + 1), + completedFuture(n + 2), + ).allResultsOfCompletableFuture().await() shouldBe listOf(n, n + 1, n + 2) arrayOf>().allResultsOfCompletableFuture().await() shouldBe emptyList() //////////////////////////////////////// listOf( - completedFuture(42), - completedFuture("42"), - completedFuture(42.0), + completedFuture(n), + completedFuture(s), + completedFuture(d), ).allOfCompletableFuture().await().shouldBeNull() listOf>().allOfCompletableFuture().await().shouldBeNull() setOf( - completedFuture(42), - completedFuture("42"), - completedFuture(42.0), + completedFuture(n), + completedFuture(s), + completedFuture(d), ).allOfCompletableFuture().await().shouldBeNull() arrayOf( - completedFuture(42), - completedFuture("42"), - completedFuture(42.0), + completedFuture(n), + completedFuture(s), + completedFuture(d), ).allOfCompletableFuture().await().shouldBeNull() arrayOf>().allOfCompletableFuture().await().shouldBeNull() //////////////////////////////////////// listOf( - completedFuture(42), - completedFuture(43), - completedFuture(44), - ).allResultsFastFailOfCompletableFuture().await() shouldBe listOf(42, 43, 44) + completedFuture(n), + completedFuture(n + 1), + completedFuture(n + 2), + ).allResultsFastFailOfCompletableFuture().await() shouldBe listOf(n, n + 1, n + 2) listOf>().allResultsFastFailOfCompletableFuture().await() shouldBe emptyList() setOf( - completedFuture(42), - completedFuture(43), - completedFuture(44), - ).allResultsFastFailOfCompletableFuture().await() shouldBe listOf(42, 43, 44) + completedFuture(n), + completedFuture(n + 1), + completedFuture(n + 2), + ).allResultsFastFailOfCompletableFuture().await() shouldBe listOf(n, n + 1, n + 2) arrayOf( - completedFuture(42), - completedFuture(43), - completedFuture(44), - ).allResultsFastFailOfCompletableFuture().await() shouldBe listOf(42, 43, 44) + completedFuture(n), + completedFuture(n + 1), + completedFuture(n + 2), + ).allResultsFastFailOfCompletableFuture().await() shouldBe listOf(n, n + 1, n + 2) arrayOf>().allResultsFastFailOfCompletableFuture().await() shouldBe emptyList() //////////////////////////////////////// listOf( - completedFuture(42), - completedFuture("42"), - completedFuture(42.0), + completedFuture(n), + completedFuture(s), + completedFuture(d), ).allFastFailOfCompletableFuture().await().shouldBeNull() listOf>().allFastFailOfCompletableFuture().await().shouldBeNull() setOf( - completedFuture(42), - completedFuture("42"), - completedFuture(42.0), + completedFuture(n), + completedFuture(s), + completedFuture(d), ).allFastFailOfCompletableFuture().await().shouldBeNull() arrayOf( - completedFuture(42), - completedFuture("42"), - completedFuture(42.0), + completedFuture(n), + completedFuture(s), + completedFuture(d), ).allFastFailOfCompletableFuture().await().shouldBeNull() arrayOf>().allFastFailOfCompletableFuture().await().shouldBeNull() } test("mostSuccessResultsOfCompletableFuture") { - listOf(CompletableFuture(), completedFuture(42)) - .mostSuccessResultsOfCompletableFuture(null, 10, TimeUnit.MILLISECONDS).await() shouldBe listOf(null, 42) - listOf(CompletableFuture(), completedFuture(42)) + listOf(CompletableFuture(), completedFuture(n)) + .mostSuccessResultsOfCompletableFuture(null, 10, TimeUnit.MILLISECONDS).await() shouldBe listOf(null, n) + listOf(CompletableFuture(), completedFuture(n)) .mostSuccessResultsOfCompletableFuture(null, testThreadPoolExecutor, 10, TimeUnit.MILLISECONDS) - .await() shouldBe listOf(null, 42) + .await() shouldBe listOf(null, n) - arrayOf(CompletableFuture(), completedFuture(42)) - .mostSuccessResultsOfCompletableFuture(null, 10, TimeUnit.MILLISECONDS).await() shouldBe listOf(null, 42) - arrayOf(CompletableFuture(), completedFuture(42)) + arrayOf(CompletableFuture(), completedFuture(n)) + .mostSuccessResultsOfCompletableFuture(null, 10, TimeUnit.MILLISECONDS).await() shouldBe listOf(null, n) + arrayOf(CompletableFuture(), completedFuture(n)) .mostSuccessResultsOfCompletableFuture(null, testThreadPoolExecutor, 10, TimeUnit.MILLISECONDS) - .await() shouldBe listOf(null, 42) + .await() shouldBe listOf(null, n) } test("anyOf*") { listOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anyOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anyOfCompletableFuture().await() shouldBe n listOf>().anyOfCompletableFuture().isDone.shouldBeFalse() setOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anyOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anyOfCompletableFuture().await() shouldBe n arrayOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anyOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anyOfCompletableFuture().await() shouldBe n arrayOf>().anyOfCompletableFuture().isDone.shouldBeFalse() //////////////////////////////////////// @@ -153,21 +151,21 @@ class CompletableFutureExtensionsTest : FunSpec({ listOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anyOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anyOfCompletableFuture().await() shouldBe n listOf>().anyOfCompletableFuture().isDone.shouldBeFalse() setOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anyOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anyOfCompletableFuture().await() shouldBe n arrayOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anyOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anyOfCompletableFuture().await() shouldBe n arrayOf>().anyOfCompletableFuture().isDone.shouldBeFalse() //////////////////////////////////////// @@ -175,23 +173,23 @@ class CompletableFutureExtensionsTest : FunSpec({ listOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anySuccessOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anySuccessOfCompletableFuture().await() shouldBe n shouldThrowExactly { listOf>().anySuccessOfCompletableFuture().await() } setOf( CompletableFuture(), - completedFuture(42), + completedFuture(n), CompletableFuture(), - ).anySuccessOfCompletableFuture().await() shouldBe 42 + ).anySuccessOfCompletableFuture().await() shouldBe n arrayOf( CompletableFuture(), - completedFuture(42), + completedFuture(n), CompletableFuture(), - ).anySuccessOfCompletableFuture().await() shouldBe 42 + ).anySuccessOfCompletableFuture().await() shouldBe n shouldThrowExactly { arrayOf>().anySuccessOfCompletableFuture().await() } @@ -201,8 +199,8 @@ class CompletableFutureExtensionsTest : FunSpec({ listOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anySuccessOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anySuccessOfCompletableFuture().await() shouldBe n shouldThrowExactly { listOf>().anySuccessOfCompletableFuture().await() } @@ -210,14 +208,14 @@ class CompletableFutureExtensionsTest : FunSpec({ setOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anySuccessOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anySuccessOfCompletableFuture().await() shouldBe n arrayOf( CompletableFuture(), CompletableFuture(), - completedFuture(42), - ).anySuccessOfCompletableFuture().await() shouldBe 42 + completedFuture(n), + ).anySuccessOfCompletableFuture().await() shouldBe n shouldThrowExactly { arrayOf>().anySuccessOfCompletableFuture().await() } @@ -229,7 +227,7 @@ class CompletableFutureExtensionsTest : FunSpec({ test("both fastFail") { val cf = CompletableFuture.supplyAsync { - sleep(2_000) + snoreZzz(2_000) n } val failed = CompletableFutureUtils.failedFuture(rte) @@ -427,15 +425,15 @@ class CompletableFutureExtensionsTest : FunSpec({ } test("write methods") { - createIncompleteFuture().completeAsync { n }.get() shouldBe n - createIncompleteFuture().completeAsync({ n }, testThreadPoolExecutor).get() shouldBe n + incompleteCf().completeAsync { n }.get() shouldBe n + incompleteCf().completeAsync({ n }, testThreadPoolExecutor).get() shouldBe n shouldThrowExactly { - createIncompleteFuture().completeExceptionallyAsync { rte }.get() + incompleteCf().completeExceptionallyAsync { rte }.get() }.cause shouldBeSameInstanceAs rte shouldThrowExactly { - createIncompleteFuture().completeExceptionallyAsync({ rte }, testThreadPoolExecutor).get() + incompleteCf().completeExceptionallyAsync({ rte }, testThreadPoolExecutor).get() }.cause shouldBeSameInstanceAs rte } diff --git a/cffu-kotlin/src/test/java/io/foldright/cffu/test/ListenableFutureExtensionsKtTest.kt b/cffu-kotlin/src/test/java/io/foldright/cffu/test/ListenableFutureExtensionsKtTest.kt index ce99b448..0213e9aa 100644 --- a/cffu-kotlin/src/test/java/io/foldright/cffu/test/ListenableFutureExtensionsKtTest.kt +++ b/cffu-kotlin/src/test/java/io/foldright/cffu/test/ListenableFutureExtensionsKtTest.kt @@ -5,6 +5,8 @@ import io.foldright.cffu.CompletableFutureUtils.failedFuture import io.foldright.cffu.kotlin.toCffu import io.foldright.cffu.kotlin.toCompletableFuture import io.foldright.cffu.kotlin.toListenableFuture +import io.foldright.test_utils.n +import io.foldright.test_utils.rte import io.foldright.test_utils.testCffuFactory import io.foldright.test_utils.testThreadPoolExecutor import io.kotest.assertions.throwables.shouldThrowExactly @@ -20,7 +22,9 @@ class ListenableFutureExtensionsKtTest : FunSpec({ lf.toCompletableFuture(testThreadPoolExecutor, true).get() shouldBe n val failed = Futures.immediateFailedFuture(rte) - shouldThrowExactly { failed.toCompletableFuture(testThreadPoolExecutor, true).get() }.cause shouldBeSameInstanceAs rte + shouldThrowExactly { + failed.toCompletableFuture(testThreadPoolExecutor, true).get() + }.cause shouldBeSameInstanceAs rte } test("toCffu") { @@ -28,7 +32,9 @@ class ListenableFutureExtensionsKtTest : FunSpec({ lf.toCffu(testCffuFactory, true).get() shouldBe n val failed = Futures.immediateFailedFuture(rte) - shouldThrowExactly { failed.toCffu(testCffuFactory, true).get() }.cause shouldBeSameInstanceAs rte + shouldThrowExactly { + failed.toCffu(testCffuFactory, true).get() + }.cause shouldBeSameInstanceAs rte } test("toListenableFuture") { diff --git a/scripts/gen_CffuApiCompatibilityTest.sh b/scripts/gen_CffuApiCompatibilityTest.sh index 50ef8f6a..c7b7ee3b 100755 --- a/scripts/gen_CffuApiCompatibilityTest.sh +++ b/scripts/gen_CffuApiCompatibilityTest.sh @@ -9,33 +9,36 @@ readonly target_file="$TEST_FILE_DIR/CffuApiCompatibilityTest.java" trap 'chmod -w "$target_file"' EXIT chmod +w "$target_file" -sed -r '/^import /,${ - # skip if GEN_MARK_KEEP - /\bGEN_MARK_KEEP\b/b +sed -r ' + /^import /,/^import static/ { + # adjust imports + s/import io\.foldright\.test_utils\.TestingExecutorUtils;/import io.foldright.cffu.Cffu;\nimport io.foldright.cffu.CffuFactory;\nimport io.foldright.test_utils.TestingExecutorUtils;/ + /import java.util.concurrent.CompletableFuture;/d + } - # adjust imports - s/import io\.foldright\.test_utils\.TestThreadPoolManager;/import io.foldright.cffu.Cffu;\nimport io.foldright.cffu.CffuFactory;\nimport io.foldright.test_utils.TestThreadPoolManager;/ - /import java.util.concurrent.CompletableFuture;/d + /^class /,$ { + # skip if GEN_MARK_KEEP + /\bGEN_MARK_KEEP\b/b - # replace JUnit test class name - s/\bclass\s+CompletableFutureApiCompatibilityTest\b/class CffuApiCompatibilityTest/ + # replace JUnit test class name + s/\bclass\s+CompletableFutureApiCompatibilityTest\b/class CffuApiCompatibilityTest/ - /@EnabledForJreRange\(.*\)$/d + /@EnabledForJreRange\(.*\)$/d - # replace CompatibilityTestHelper methods - s/\b(TestUtils)\.(\w*)CompletableFuture(\w*)/\1\.\2Cffu\3/g + # replace CompatibilityTestHelper methods + s/\b(TestUtils)\.(\w*)CompletableFuture(\w*)/\1\.\2Cffu\3/g - # replace CompletableFuture constructor to cffuFactory.newIncompleteCffu() methods - s/\bnew\s+CompletableFuture<>/cffuFactory.newIncompleteCffu/g + # replace CompletableFuture constructor to cffuFactory.newIncompleteCffu() methods + s/\bnew\s+CompletableFuture<>/cffuFactory.newIncompleteCffu/g - # replace static methods of CompletableFuture - s/\bCompletableFuture\./cffuFactory\./g + # replace static methods of CompletableFuture + s/\bCompletableFuture\./cffuFactory\./g - # replace CompletableFuture class name - s/\bCompletableFuture\b/Cffu/g + # replace CompletableFuture class name + s/\bCompletableFuture\b/Cffu/g - # generate new contents - s/^(\s*).*\bGEN_MARK_FACTORY_FIELD\b.*$/\1private static CffuFactory cffuFactory;/ - s/^(\s*).*\bGEN_MARK_FACTORY_INIT\b.*$/\1cffuFactory = CffuFactory.builder\(executorService\).build\(\);/ - -}' "$source_file" >"$target_file" + # generate new contents + s/^(\s*).*\bGEN_MARK_FACTORY_FIELD\b.*$/\1private static CffuFactory cffuFactory;/ + s/^(\s*).*\bGEN_MARK_FACTORY_INIT\b.*$/\1cffuFactory = CffuFactory.builder\(executorService\).build\(\);/ + } + ' "$source_file" >"$target_file"