From b357781df21cc825ef41a308744d33f3e749bd37 Mon Sep 17 00:00:00 2001 From: Yann Ann Date: Fri, 14 Oct 2022 11:06:29 +0800 Subject: [PATCH] [Migrate][Test] Migrate junit4 -> junit5 test cases in common, service, and spi modules (#12363) --- .../common/ConstantsTest.java | 9 +- .../common/exception/ExceptionTest.java | 24 +-- .../common/graph/DAGTest.java | 119 ++++++----- .../common/os/OSUtilsTest.java | 34 ++-- .../common/utils/CodeGenerateUtilsTest.java | 8 +- .../common/utils/DateUtilsTest.java | 106 +++++----- .../common/utils/EncryptionUtilsTest.java | 6 +- .../common/utils/FileUtilsTest.java | 51 +++-- .../utils/LocalServerHttpUtilsTest.java | 34 ++-- .../common/utils/NetUtilsTest.java | 45 ++--- .../common/utils/PropertyUtilsTest.java | 11 +- .../common/utils/RetryerUtilsTest.java | 88 ++++---- .../common/utils/ScriptRunnerTest.java | 8 +- .../common/utils/StringTest.java | 6 +- .../service/alert/AlertClientServiceTest.java | 39 ++-- .../alert/ProcessAlertManagerTest.java | 17 +- .../service/cache/CacheNotifyServiceTest.java | 24 +-- .../service/cron/CronUtilsTest.java | 92 ++++----- .../expand/CuringGlobalParamsServiceTest.java | 42 ++-- ...ePlaceholderResolverExpandServiceTest.java | 18 +- .../service/log/LogClientTest.java | 27 ++- .../log/LoggerRequestProcessorTest.java | 39 ++-- .../service/log/MasterLogFilterTest.java | 10 +- .../log/SensitiveDataConverterTest.java | 17 +- .../service/log/TaskLogDiscriminatorTest.java | 20 +- .../service/log/TaskLogFilterTest.java | 10 +- .../service/log/WorkerLogFilterTest.java | 10 +- .../service/process/ProcessServiceTest.java | 189 +++++++----------- .../PeerTaskInstancePriorityQueueTest.java | 39 ++-- .../queue/TaskPriorityQueueImplTest.java | 77 ++++--- .../service/storage/impl/HadoopUtilsTest.java | 21 +- .../service/storage/impl/OssOperatorTest.java | 81 ++++---- .../service/utils/CommonUtilsTest.java | 29 ++- .../service/utils/LogUtilsTest.java | 24 +-- .../service/utils/ProcessUtilsTest.java | 33 ++- .../spi/params/PluginParamsTransferTest.java | 19 +- .../spi/plugin/PrioritySPIFactoryTest.java | 14 +- .../spi/utils/JSONUtilsTest.java | 78 ++++---- .../spi/utils/StringUtilsTest.java | 37 ++-- 39 files changed, 717 insertions(+), 838 deletions(-) diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/ConstantsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/ConstantsTest.java index 4c15c04f8c..96b438031d 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/ConstantsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/ConstantsTest.java @@ -18,9 +18,8 @@ package org.apache.dolphinscheduler.common; import org.apache.commons.lang3.SystemUtils; - -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * Constants Test @@ -33,9 +32,9 @@ public class ConstantsTest { @Test public void testPID() { if (SystemUtils.IS_OS_WINDOWS) { - Assert.assertEquals(Constants.PID, "handle"); + Assertions.assertEquals(Constants.PID, "handle"); } else { - Assert.assertEquals(Constants.PID, "pid"); + Assertions.assertEquals(Constants.PID, "pid"); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/exception/ExceptionTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/exception/ExceptionTest.java index 6a670c9b61..e49d8d9b29 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/exception/ExceptionTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/exception/ExceptionTest.java @@ -18,8 +18,8 @@ package org.apache.dolphinscheduler.common.exception; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ExceptionTest { @@ -28,16 +28,16 @@ public class ExceptionTest { final String message = "Test"; RuntimeException time = new RuntimeException(message); - Assert.assertNull(new BaseException().getMessage()); - Assert.assertNotNull(new BaseException(message).getMessage()); - Assert.assertNotNull(new BaseException(message, time).getMessage()); - Assert.assertNotNull(new BaseException(time).getCause()); - Assert.assertNotNull(new BaseException(message, time, false, false).getMessage()); + Assertions.assertNull(new BaseException().getMessage()); + Assertions.assertNotNull(new BaseException(message).getMessage()); + Assertions.assertNotNull(new BaseException(message, time).getMessage()); + Assertions.assertNotNull(new BaseException(time).getCause()); + Assertions.assertNotNull(new BaseException(message, time, false, false).getMessage()); - Assert.assertNull(new StorageOperateNoConfiguredException().getMessage()); - Assert.assertNotNull(new StorageOperateNoConfiguredException(message).getMessage()); - Assert.assertNotNull(new StorageOperateNoConfiguredException(message, time).getMessage()); - Assert.assertNotNull(new StorageOperateNoConfiguredException(time).getCause()); - Assert.assertNotNull(new StorageOperateNoConfiguredException(message, time, false, false).getMessage()); + Assertions.assertNull(new StorageOperateNoConfiguredException().getMessage()); + Assertions.assertNotNull(new StorageOperateNoConfiguredException(message).getMessage()); + Assertions.assertNotNull(new StorageOperateNoConfiguredException(message, time).getMessage()); + Assertions.assertNotNull(new StorageOperateNoConfiguredException(time).getCause()); + Assertions.assertNotNull(new StorageOperateNoConfiguredException(message, time, false, false).getMessage()); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/graph/DAGTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/graph/DAGTest.java index 5d7e27bf8c..deff8a2ea5 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/graph/DAGTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/graph/DAGTest.java @@ -16,9 +16,10 @@ */ package org.apache.dolphinscheduler.common.graph; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -26,18 +27,16 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.*; - public class DAGTest { private DAG graph; private static final Logger logger = LoggerFactory.getLogger(DAGTest.class); - @Before + @BeforeEach public void setup() { graph = new DAG<>(); } - @After + @AfterEach public void tearDown() { clear(); } @@ -46,7 +45,7 @@ public class DAGTest { graph = null; graph = new DAG<>(); - assertEquals(graph.getNodesCount(), 0); + Assertions.assertEquals(graph.getNodesCount(), 0); } @@ -65,20 +64,20 @@ public class DAGTest { } // construction side - assertTrue(graph.addEdge(1, 2)); + Assertions.assertTrue(graph.addEdge(1, 2)); - assertTrue(graph.addEdge(2, 5)); + Assertions.assertTrue(graph.addEdge(2, 5)); - assertTrue(graph.addEdge(3, 5)); + Assertions.assertTrue(graph.addEdge(3, 5)); - assertTrue(graph.addEdge(4, 6)); + Assertions.assertTrue(graph.addEdge(4, 6)); - assertTrue(graph.addEdge(5, 6)); + Assertions.assertTrue(graph.addEdge(5, 6)); - assertTrue(graph.addEdge(6, 7)); + Assertions.assertTrue(graph.addEdge(6, 7)); - assertEquals(graph.getNodesCount(), 7); - assertEquals(graph.getEdgesCount(), 6); + Assertions.assertEquals(graph.getNodesCount(), 7); + Assertions.assertEquals(graph.getEdgesCount(), 6); } @@ -94,12 +93,12 @@ public class DAGTest { graph.addNode(2, null); graph.addNode(5, "v(5)"); - assertEquals(graph.getNodesCount(), 3); + Assertions.assertEquals(graph.getNodesCount(), 3); - assertEquals(graph.getNode(1), "v(1)"); - assertTrue(graph.containsNode(1)); + Assertions.assertEquals(graph.getNode(1), "v(1)"); + Assertions.assertTrue(graph.containsNode(1)); - assertFalse(graph.containsNode(10)); + Assertions.assertFalse(graph.containsNode(10)); } @@ -110,24 +109,24 @@ public class DAGTest { public void testAddEdge() { clear(); - assertFalse(graph.addEdge(1, 2, "edge(1 -> 2)", false)); + Assertions.assertFalse(graph.addEdge(1, 2, "edge(1 -> 2)", false)); graph.addNode(1, "v(1)"); - assertTrue(graph.addEdge(1, 2, "edge(1 -> 2)",true)); + Assertions.assertTrue(graph.addEdge(1, 2, "edge(1 -> 2)",true)); graph.addNode(2, "v(2)"); - assertTrue(graph.addEdge(1, 2, "edge(1 -> 2)",true)); + Assertions.assertTrue(graph.addEdge(1, 2, "edge(1 -> 2)",true)); - assertFalse(graph.containsEdge(1, 3)); + Assertions.assertFalse(graph.containsEdge(1, 3)); - assertTrue(graph.containsEdge(1, 2)); - assertEquals(graph.getEdgesCount(), 1); + Assertions.assertTrue(graph.containsEdge(1, 2)); + Assertions.assertEquals(graph.getEdgesCount(), 1); int node = 3; graph.addNode(node, "v(3)"); - assertFalse(graph.addEdge(node, node)); + Assertions.assertFalse(graph.addEdge(node, node)); } @@ -139,7 +138,7 @@ public class DAGTest { public void testSubsequentNodes() { makeGraph(); - assertEquals(graph.getSubsequentNodes(1).size(), 1); + Assertions.assertEquals(graph.getSubsequentNodes(1).size(), 1); } @@ -151,10 +150,10 @@ public class DAGTest { public void testIndegree() { makeGraph(); - assertEquals(graph.getIndegree(1), 0); - assertEquals(graph.getIndegree(2), 1); - assertEquals(graph.getIndegree(3), 0); - assertEquals(graph.getIndegree(4), 0); + Assertions.assertEquals(graph.getIndegree(1), 0); + Assertions.assertEquals(graph.getIndegree(2), 1); + Assertions.assertEquals(graph.getIndegree(3), 0); + Assertions.assertEquals(graph.getIndegree(4), 0); } @@ -165,11 +164,11 @@ public class DAGTest { public void testBeginNode() { makeGraph(); - assertEquals(graph.getBeginNode().size(), 3); + Assertions.assertEquals(graph.getBeginNode().size(), 3); - assertTrue(graph.getBeginNode().contains(1)); - assertTrue(graph.getBeginNode().contains(3)); - assertTrue(graph.getBeginNode().contains(4)); + Assertions.assertTrue(graph.getBeginNode().contains(1)); + Assertions.assertTrue(graph.getBeginNode().contains(3)); + Assertions.assertTrue(graph.getBeginNode().contains(4)); } @@ -180,9 +179,9 @@ public class DAGTest { public void testEndNode() { makeGraph(); - assertEquals(graph.getEndNode().size(), 1); + Assertions.assertEquals(graph.getEndNode().size(), 1); - assertTrue(graph.getEndNode().contains(7)); + Assertions.assertTrue(graph.getEndNode().contains(7)); } @@ -204,10 +203,10 @@ public class DAGTest { graph.addEdge(2, 3); graph.addEdge(3, 4); - assertFalse(graph.hasCycle()); + Assertions.assertFalse(graph.hasCycle()); } catch (Exception e) { e.printStackTrace(); - fail(); + Assertions.fail(); } @@ -215,15 +214,15 @@ public class DAGTest { boolean addResult = graph.addEdge(4, 1); if(!addResult){ - assertTrue(true); + Assertions.assertTrue(true); } graph.addEdge(5, 1); - assertFalse(graph.hasCycle()); + Assertions.assertFalse(graph.hasCycle()); } catch (Exception e) { e.printStackTrace(); - fail(); + Assertions.fail(); } clear(); @@ -241,10 +240,10 @@ public class DAGTest { graph.addEdge(4, 5); graph.addEdge(5, 2);//会失败,添加不进去,所以下一步无环 - assertFalse(graph.hasCycle()); + Assertions.assertFalse(graph.hasCycle()); } catch (Exception e) { e.printStackTrace(); - fail(); + Assertions.fail(); } } @@ -264,10 +263,10 @@ public class DAGTest { topoList.add(6); topoList.add(7); - assertEquals(graph.topologicalSort(),topoList); + Assertions.assertEquals(graph.topologicalSort(),topoList); } catch (Exception e) { e.printStackTrace(); - fail(); + Assertions.fail(); } } @@ -290,11 +289,11 @@ public class DAGTest { topoList.add(4); topoList.add(5); - assertEquals(graph.topologicalSort(),topoList); + Assertions.assertEquals(graph.topologicalSort(),topoList); } catch (Exception e) { e.printStackTrace(); - fail(); + Assertions.fail(); } } @@ -318,24 +317,24 @@ public class DAGTest { } // construction node - assertTrue(graph.addEdge(1, 2)); + Assertions.assertTrue(graph.addEdge(1, 2)); - assertTrue(graph.addEdge(1, 3)); + Assertions.assertTrue(graph.addEdge(1, 3)); - assertTrue(graph.addEdge(2, 5)); - assertTrue(graph.addEdge(3, 4)); + Assertions.assertTrue(graph.addEdge(2, 5)); + Assertions.assertTrue(graph.addEdge(3, 4)); - assertTrue(graph.addEdge(4, 6)); + Assertions.assertTrue(graph.addEdge(4, 6)); - assertTrue(graph.addEdge(5, 6)); + Assertions.assertTrue(graph.addEdge(5, 6)); - assertTrue(graph.addEdge(6, 7)); - assertTrue(graph.addEdge(6, 8)); + Assertions.assertTrue(graph.addEdge(6, 7)); + Assertions.assertTrue(graph.addEdge(6, 8)); - assertEquals(graph.getNodesCount(), 8); + Assertions.assertEquals(graph.getNodesCount(), 8); logger.info(Arrays.toString(graph.topologicalSort().toArray())); @@ -347,7 +346,7 @@ public class DAGTest { logger.info(i + " subsequentNodes : " + graph.getSubsequentNodes(i)); } logger.info(6 + " previousNodesb: " + graph.getPreviousNodes(6)); - assertEquals(5, graph.getSubsequentNodes(2).toArray()[0]); + Assertions.assertEquals(5, graph.getSubsequentNodes(2).toArray()[0]); } @@ -357,7 +356,7 @@ public class DAGTest { try { graph.topologicalSort(); } catch (Exception e) { - assertTrue(e.getMessage().contains("serious error: graph has cycle")); + Assertions.assertTrue(e.getMessage().contains("serious error: graph has cycle")); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/os/OSUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/os/OSUtilsTest.java index f21b58070a..7525d1c76e 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/os/OSUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/os/OSUtilsTest.java @@ -16,17 +16,15 @@ */ package org.apache.dolphinscheduler.common.os; -import org.apache.dolphinscheduler.common.utils.OSUtils; - import org.apache.commons.lang3.SystemUtils; - -import java.util.List; - -import org.junit.Assert; -import org.junit.Test; +import org.apache.dolphinscheduler.common.utils.OSUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.List; + /** * OSUtilsTest */ @@ -38,35 +36,35 @@ public class OSUtilsTest { public void memoryUsage() { double memoryUsage = OSUtils.memoryUsage(); logger.info("memoryUsage : {}", memoryUsage); - Assert.assertTrue(memoryUsage >= 0.0); + Assertions.assertTrue(memoryUsage >= 0.0); } @Test public void diskAvailable() { double diskAvailable = OSUtils.diskAvailable(); logger.info("diskAvailable : {}", diskAvailable); - Assert.assertTrue(diskAvailable >= 0.0); + Assertions.assertTrue(diskAvailable >= 0.0); } @Test public void loadAverage() { double loadAverage = OSUtils.loadAverage(); logger.info("loadAverage : {}", loadAverage); - Assert.assertTrue(loadAverage >= 0.0); + Assertions.assertTrue(loadAverage >= 0.0); } @Test public void cpuUsage() { double cpuUsage = OSUtils.cpuUsage(); logger.info("cpuUsage : {}", cpuUsage); - Assert.assertTrue(cpuUsage >= 0.0); + Assertions.assertTrue(cpuUsage >= 0.0); } @Test public void availablePhysicalMemorySize() { double physicalMemorySize = OSUtils.availablePhysicalMemorySize(); logger.info("physicalMemorySize : {}", physicalMemorySize); - Assert.assertTrue(physicalMemorySize >= 0.0); + Assertions.assertTrue(physicalMemorySize >= 0.0); } @@ -74,11 +72,11 @@ public class OSUtilsTest { public void existTenantCodeInLinux() { if (SystemUtils.IS_OS_LINUX) { boolean test = OSUtils.existTenantCodeInLinux("root"); - Assert.assertTrue(test); + Assertions.assertTrue(test); boolean test1 = OSUtils.existTenantCodeInLinux("xxxtt"); - Assert.assertFalse(test1); + Assertions.assertFalse(test1); } else { - Assert.assertFalse("system must be linux", false); + Assertions.assertFalse(false, "system must be linux"); } } @@ -87,10 +85,10 @@ public class OSUtilsTest { public void existOSTenandCode() { if (SystemUtils.IS_OS_LINUX) { List userList = OSUtils.getUserList(); - Assert.assertTrue(userList.contains("root")); - Assert.assertFalse(userList.contains("xxxtt")); + Assertions.assertTrue(userList.contains("root")); + Assertions.assertFalse(userList.contains("xxxtt")); } else { - Assert.assertFalse("system must be linux", false); + Assertions.assertFalse(false, "system must be linux"); } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/CodeGenerateUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/CodeGenerateUtilsTest.java index d949bd82b8..e484b61f8d 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/CodeGenerateUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/CodeGenerateUtilsTest.java @@ -17,10 +17,10 @@ package org.apache.dolphinscheduler.common.utils; -import java.util.HashSet; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import java.util.HashSet; public class CodeGenerateUtilsTest { @Test @@ -28,7 +28,7 @@ public class CodeGenerateUtilsTest { HashSet existsCode = new HashSet<>(); for (int i = 0; i < 100; i++) { Long currentCode = CodeGenerateUtils.getInstance().genCode(); - Assert.assertFalse(existsCode.contains(currentCode)); + Assertions.assertFalse(existsCode.contains(currentCode)); existsCode.add(currentCode); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/DateUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/DateUtilsTest.java index e4cbff3223..36ffe1134a 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/DateUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/DateUtilsTest.java @@ -18,7 +18,12 @@ package org.apache.dolphinscheduler.common.utils; import org.apache.dolphinscheduler.common.thread.ThreadLocalContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import javax.management.timer.Timer; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.ZoneId; @@ -26,21 +31,14 @@ import java.time.ZonedDateTime; import java.util.Date; import java.util.TimeZone; -import javax.management.timer.Timer; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - public class DateUtilsTest { - @Before + @BeforeEach public void before() { ThreadLocalContext.getTimezoneThreadLocal().remove(); } - @After + @AfterEach public void after() { ThreadLocalContext.getTimezoneThreadLocal().remove(); } @@ -57,7 +55,7 @@ public class DateUtilsTest { String readableDate = DateUtils.format2Readable(endDate.getTime() - startDate.getTime()); - Assert.assertEquals("01 09:23:08", readableDate); + Assertions.assertEquals("01 09:23:08", readableDate); } @Test @@ -68,67 +66,67 @@ public class DateUtilsTest { Date monday = DateUtils.getMonday(curr); Date sunday = DateUtils.getSunday(monday); - Assert.assertEquals(monday, monday1); - Assert.assertEquals(sunday, sunday1); + Assertions.assertEquals(monday, monday1); + Assertions.assertEquals(sunday, sunday1); } @Test public void dateToString() { Date d1 = DateUtils.stringToDate("2019-01-28"); - Assert.assertNull(d1); + Assertions.assertNull(d1); d1 = DateUtils.stringToDate("2019-01-28 00:00:00"); - Assert.assertEquals(DateUtils.dateToString(d1), "2019-01-28 00:00:00"); + Assertions.assertEquals(DateUtils.dateToString(d1), "2019-01-28 00:00:00"); } @Test public void getSomeDay() { Date d1 = DateUtils.stringToDate("2019-01-31 00:00:00"); Date curr = DateUtils.getSomeDay(d1, 1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-02-01 00:00:00"); - Assert.assertEquals(DateUtils.dateToString(DateUtils.getSomeDay(d1, -31)), "2018-12-31 00:00:00"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-02-01 00:00:00"); + Assertions.assertEquals(DateUtils.dateToString(DateUtils.getSomeDay(d1, -31)), "2018-12-31 00:00:00"); } @Test public void getFirstDayOfMonth() { Date d1 = DateUtils.stringToDate("2019-01-31 00:00:00"); Date curr = DateUtils.getFirstDayOfMonth(d1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-01 00:00:00"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-01 00:00:00"); d1 = DateUtils.stringToDate("2019-01-31 01:59:00"); curr = DateUtils.getFirstDayOfMonth(d1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-01 01:59:00"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-01 01:59:00"); } @Test public void getSomeHourOfDay() { Date d1 = DateUtils.stringToDate("2019-01-31 11:59:59"); Date curr = DateUtils.getSomeHourOfDay(d1, -1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-31 10:00:00"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-31 10:00:00"); curr = DateUtils.getSomeHourOfDay(d1, 0); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:00:00"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:00:00"); curr = DateUtils.getSomeHourOfDay(d1, 2); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-31 13:00:00"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-31 13:00:00"); curr = DateUtils.getSomeHourOfDay(d1, 24); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-02-01 11:00:00"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-02-01 11:00:00"); } @Test public void getLastDayOfMonth() { Date d1 = DateUtils.stringToDate("2019-01-31 11:59:59"); Date curr = DateUtils.getLastDayOfMonth(d1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:59:59"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:59:59"); d1 = DateUtils.stringToDate("2019-01-02 11:59:59"); curr = DateUtils.getLastDayOfMonth(d1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:59:59"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:59:59"); d1 = DateUtils.stringToDate("2019-02-02 11:59:59"); curr = DateUtils.getLastDayOfMonth(d1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-02-28 11:59:59"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-02-28 11:59:59"); d1 = DateUtils.stringToDate("2020-02-02 11:59:59"); curr = DateUtils.getLastDayOfMonth(d1); - Assert.assertEquals(DateUtils.dateToString(curr), "2020-02-29 11:59:59"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2020-02-29 11:59:59"); } @Test @@ -136,7 +134,7 @@ public class DateUtilsTest { Date d1 = DateUtils.stringToDate("2019-01-31 11:59:59"); Date curr = DateUtils.getStartOfDay(d1); String expected = new SimpleDateFormat("yyyy-MM-dd").format(d1) + " 00:00:00"; - Assert.assertEquals(DateUtils.dateToString(curr), expected); + Assertions.assertEquals(DateUtils.dateToString(curr), expected); } @Test @@ -144,27 +142,27 @@ public class DateUtilsTest { Date d1 = DateUtils.stringToDate("2019-01-31 11:00:59"); Date curr = DateUtils.getEndOfDay(d1); String expected = new SimpleDateFormat("yyyy-MM-dd").format(d1) + " 23:59:59"; - Assert.assertEquals(DateUtils.dateToString(curr), expected); + Assertions.assertEquals(DateUtils.dateToString(curr), expected); } @Test public void getStartOfHour() { Date d1 = DateUtils.stringToDate("2019-01-31 11:00:59"); Date curr = DateUtils.getStartOfHour(d1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:00:00"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:00:00"); } @Test public void getEndOfHour() { Date d1 = DateUtils.stringToDate("2019-01-31 11:00:59"); Date curr = DateUtils.getEndOfHour(d1); - Assert.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:59:59"); + Assertions.assertEquals(DateUtils.dateToString(curr), "2019-01-31 11:59:59"); } @Test public void getCurrentTimeStamp() { String timeStamp = DateUtils.getCurrentTimeStamp(); - Assert.assertNotNull(timeStamp); + Assertions.assertNotNull(timeStamp); } @Test @@ -174,49 +172,49 @@ public class DateUtilsTest { Date start = DateUtils.stringToDate("2020-01-20 11:00:00"); Date end = DateUtils.stringToDate("2020-01-21 12:10:10"); String duration = DateUtils.format2Duration(start, end); - Assert.assertEquals("1d 1h 10m 10s", duration); + Assertions.assertEquals("1d 1h 10m 10s", duration); duration = DateUtils.format2Duration(end, start); - Assert.assertNull(duration); + Assertions.assertNull(duration); // hours minutes seconds start = DateUtils.stringToDate("2020-01-20 11:00:00"); end = DateUtils.stringToDate("2020-01-20 12:10:10"); duration = DateUtils.format2Duration(start, end); - Assert.assertEquals("1h 10m 10s", duration); + Assertions.assertEquals("1h 10m 10s", duration); // minutes seconds start = DateUtils.stringToDate("2020-01-20 11:00:00"); end = DateUtils.stringToDate("2020-01-20 11:10:10"); duration = DateUtils.format2Duration(start, end); - Assert.assertEquals("10m 10s", duration); + Assertions.assertEquals("10m 10s", duration); // minutes seconds start = DateUtils.stringToDate("2020-01-20 11:10:00"); end = DateUtils.stringToDate("2020-01-20 11:10:10"); duration = DateUtils.format2Duration(start, end); - Assert.assertEquals("10s", duration); + Assertions.assertEquals("10s", duration); start = DateUtils.stringToDate("2020-01-20 11:10:00"); end = DateUtils.stringToDate("2020-01-21 11:10:10"); duration = DateUtils.format2Duration(start, end); - Assert.assertEquals("1d 10s", duration); + Assertions.assertEquals("1d 10s", duration); start = DateUtils.stringToDate("2020-01-20 11:10:00"); end = DateUtils.stringToDate("2020-01-20 16:10:10"); duration = DateUtils.format2Duration(start, end); - Assert.assertEquals("5h 10s", duration); + Assertions.assertEquals("5h 10s", duration); // startTime = endTime, default 1s start = DateUtils.stringToDate("2020-01-20 11:10:00"); end = DateUtils.stringToDate("2020-01-20 11:10:00"); duration = DateUtils.format2Duration(start, end); - Assert.assertEquals("1s", duration); + Assertions.assertEquals("1s", duration); // endTime is null, use current time start = DateUtils.stringToDate("2020-01-20 11:10:00"); duration = DateUtils.format2Duration(start, null); - Assert.assertNotNull(duration); + Assertions.assertNotNull(duration); } @Test @@ -225,16 +223,16 @@ public class DateUtilsTest { Date date = new Date(); Date defaultTimeZoneDate = DateUtils.transformTimezoneDate(date, TimeZone.getDefault().getID()); - Assert.assertEquals(DateUtils.dateToString(date), DateUtils.dateToString(defaultTimeZoneDate)); + Assertions.assertEquals(DateUtils.dateToString(date), DateUtils.dateToString(defaultTimeZoneDate)); Date targetTimeZoneDate = DateUtils.transformTimezoneDate(date, TimeZone.getDefault().getID(), "Asia/Shanghai"); - Assert.assertEquals(DateUtils.dateToString(date, TimeZone.getDefault().getID()), DateUtils.dateToString(targetTimeZoneDate, "Asia/Shanghai")); + Assertions.assertEquals(DateUtils.dateToString(date, TimeZone.getDefault().getID()), DateUtils.dateToString(targetTimeZoneDate, "Asia/Shanghai")); } @Test public void testGetTimezone() { - Assert.assertNull(DateUtils.getTimezone(null)); - Assert.assertEquals(TimeZone.getTimeZone("MST"), DateUtils.getTimezone("MST")); + Assertions.assertNull(DateUtils.getTimezone(null)); + Assertions.assertEquals(TimeZone.getTimeZone("MST"), DateUtils.getTimezone("MST")); } @Test @@ -243,13 +241,13 @@ public class DateUtilsTest { String time = "2019-01-28 00:00:00"; ThreadLocalContext.timezoneThreadLocal.set("UTC"); Date utcDate = DateUtils.stringToDate(time); - Assert.assertEquals(time, DateUtils.dateToString(utcDate)); + Assertions.assertEquals(time, DateUtils.dateToString(utcDate)); ThreadLocalContext.timezoneThreadLocal.set("Asia/Shanghai"); Date shanghaiDate = DateUtils.stringToDate(time); - Assert.assertEquals(time, DateUtils.dateToString(shanghaiDate)); + Assertions.assertEquals(time, DateUtils.dateToString(shanghaiDate)); - Assert.assertEquals(Timer.ONE_HOUR * 8, utcDate.getTime() - shanghaiDate.getTime()); + Assertions.assertEquals(Timer.ONE_HOUR * 8, utcDate.getTime() - shanghaiDate.getTime()); } @@ -261,7 +259,7 @@ public class DateUtilsTest { ZonedDateTime utcNow = asiaShNow.minusHours(8); String asiaShNowStr = DateUtils.dateToString(utcNow, asiaSh); String utcNowStr = DateUtils.dateToString(asiaShNow, utc); - Assert.assertEquals(asiaShNowStr, utcNowStr); + Assertions.assertEquals(asiaShNowStr, utcNowStr); } @Test @@ -272,17 +270,17 @@ public class DateUtilsTest { sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); Date date = sdf.parse(timeString); long timeStamp = DateUtils.dateToTimeStamp(date); - Assert.assertEquals(1664456400000L, timeStamp); + Assertions.assertEquals(1664456400000L, timeStamp); // Tokyo Date String tokyoTime = "2022-09-29 22:00:00"; sdf.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo")); date = sdf.parse(tokyoTime); timeStamp = DateUtils.dateToTimeStamp(date); - Assert.assertEquals(1664456400000L, timeStamp); + Assertions.assertEquals(1664456400000L, timeStamp); date = null; - Assert.assertEquals(0L, DateUtils.dateToTimeStamp(date)); + Assertions.assertEquals(0L, DateUtils.dateToTimeStamp(date)); } @Test @@ -291,13 +289,13 @@ public class DateUtilsTest { SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); String sd = sdf.format(new Date(timeStamp)); - Assert.assertEquals("2022-09-29 21:00:00", sd); + Assertions.assertEquals("2022-09-29 21:00:00", sd); sdf.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo")); sd = sdf.format(new Date(timeStamp)); - Assert.assertEquals("2022-09-29 22:00:00", sd); + Assertions.assertEquals("2022-09-29 22:00:00", sd); Date date = DateUtils.timeStampToDate(0L); - Assert.assertNull(date); + Assertions.assertNull(date); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/EncryptionUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/EncryptionUtilsTest.java index fc7f65930c..28db71b5a7 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/EncryptionUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/EncryptionUtilsTest.java @@ -16,8 +16,8 @@ */ package org.apache.dolphinscheduler.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * encryption utils @@ -27,7 +27,7 @@ public class EncryptionUtilsTest { @Test public void testGetMd5() { - Assert.assertEquals(EncryptionUtils.getMd5(null), EncryptionUtils.getMd5("")); + Assertions.assertEquals(EncryptionUtils.getMd5(null), EncryptionUtils.getMd5("")); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/FileUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/FileUtilsTest.java index ec8c9c425e..c5e6e3354b 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/FileUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/FileUtilsTest.java @@ -17,51 +17,50 @@ package org.apache.dolphinscheduler.common.utils; -import static org.apache.dolphinscheduler.common.Constants.YYYYMMDDHHMMSS; - import org.apache.dolphinscheduler.common.Constants; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.FileInputStream; import java.io.FileNotFoundException; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.MockedStatic; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import static org.apache.dolphinscheduler.common.Constants.YYYYMMDDHHMMSS; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class FileUtilsTest { @Test public void testGetDownloadFilename() { try (MockedStatic mockedDateUtils = Mockito.mockStatic(DateUtils.class)) { mockedDateUtils.when(() -> DateUtils.getCurrentTime(YYYYMMDDHHMMSS)).thenReturn("20190101101059"); - Assert.assertEquals("/tmp/dolphinscheduler/download/20190101101059/test", + Assertions.assertEquals("/tmp/dolphinscheduler/download/20190101101059/test", FileUtils.getDownloadFilename("test")); } } @Test public void testGetUploadFilename() { - Assert.assertEquals("/tmp/dolphinscheduler/aaa/resources/bbb", + Assertions.assertEquals("/tmp/dolphinscheduler/aaa/resources/bbb", FileUtils.getUploadFilename("aaa", "bbb")); } @Test public void testGetProcessExecDir() { String dir = FileUtils.getProcessExecDir(1L, 2L, 1, 3, 4); - Assert.assertEquals("/tmp/dolphinscheduler/exec/process/1/2_1/3/4", dir); + Assertions.assertEquals("/tmp/dolphinscheduler/exec/process/1/2_1/3/4", dir); } @Test public void testCreateWorkDirIfAbsent() { try { FileUtils.createWorkDirIfAbsent("/tmp/createWorkDirAndUserIfAbsent"); - Assert.assertTrue(true); + Assertions.assertTrue(true); } catch (Exception e) { - Assert.assertTrue(false); + Assertions.fail(); } } @@ -69,11 +68,11 @@ public class FileUtilsTest { public void testSetValue() { try { PropertyUtils.setValue(Constants.DATASOURCE_ENCRYPTION_ENABLE, "true"); - Assert.assertTrue(PropertyUtils.getBoolean(Constants.DATASOURCE_ENCRYPTION_ENABLE)); + Assertions.assertTrue(PropertyUtils.getBoolean(Constants.DATASOURCE_ENCRYPTION_ENABLE)); PropertyUtils.setValue(Constants.DATASOURCE_ENCRYPTION_ENABLE, "false"); - Assert.assertFalse(PropertyUtils.getBoolean(Constants.DATASOURCE_ENCRYPTION_ENABLE)); + Assertions.assertFalse(PropertyUtils.getBoolean(Constants.DATASOURCE_ENCRYPTION_ENABLE)); } catch (Exception e) { - Assert.assertTrue(false); + Assertions.fail(); } } @@ -85,7 +84,7 @@ public class FileUtilsTest { FileUtils.writeContent2File(content, filePath); String fileContent = FileUtils.readFile2Str(new FileInputStream(filePath)); - Assert.assertEquals(content, fileContent); + Assertions.assertEquals(content, fileContent); } @Test @@ -93,29 +92,29 @@ public class FileUtilsTest { // test case which do not directory traversal String path; path = "abc.txt"; - Assert.assertFalse(FileUtils.directoryTraversal(path)); + Assertions.assertFalse(FileUtils.directoryTraversal(path)); path = "abc...txt"; - Assert.assertFalse(FileUtils.directoryTraversal(path)); + Assertions.assertFalse(FileUtils.directoryTraversal(path)); path = "..abc.txt"; - Assert.assertFalse(FileUtils.directoryTraversal(path)); + Assertions.assertFalse(FileUtils.directoryTraversal(path)); // test case which will directory traversal path = "../abc.txt"; - Assert.assertTrue(FileUtils.directoryTraversal(path)); + Assertions.assertTrue(FileUtils.directoryTraversal(path)); path = "../../abc.txt"; - Assert.assertTrue(FileUtils.directoryTraversal(path)); + Assertions.assertTrue(FileUtils.directoryTraversal(path)); path = "abc../def.txt"; - Assert.assertTrue(FileUtils.directoryTraversal(path)); + Assertions.assertTrue(FileUtils.directoryTraversal(path)); path = "abc./def.txt"; - Assert.assertTrue(FileUtils.directoryTraversal(path)); + Assertions.assertTrue(FileUtils.directoryTraversal(path)); path = "abc/def...txt"; - Assert.assertTrue(FileUtils.directoryTraversal(path)); + Assertions.assertTrue(FileUtils.directoryTraversal(path)); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/LocalServerHttpUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/LocalServerHttpUtilsTest.java index 561d844ed2..f03066ef49 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/LocalServerHttpUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/LocalServerHttpUtilsTest.java @@ -17,23 +17,19 @@ package org.apache.dolphinscheduler.common.utils; +import com.fasterxml.jackson.databind.node.ObjectNode; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; import org.apache.dolphinscheduler.common.Constants; - import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; - -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.node.ObjectNode; - -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - public class LocalServerHttpUtilsTest extends TestCase { public static final Logger logger = LoggerFactory.getLogger(LocalServerHttpUtilsTest.class); @@ -50,11 +46,11 @@ public class LocalServerHttpUtilsTest extends TestCase { // success String result = null; result = HttpUtils.get("http://localhost:" + server.getServerPort() + "/test.json"); - Assert.assertNotNull(result); + Assertions.assertNotNull(result); ObjectNode jsonObject = JSONUtils.parseObject(result); - Assert.assertEquals("Github", jsonObject.path("name").asText()); + Assertions.assertEquals("Github", jsonObject.path("name").asText()); result = HttpUtils.get("http://123.333.111.33/ccc"); - Assert.assertNull(result); + Assertions.assertNull(result); } public void testGetResponseContentString() { @@ -68,19 +64,19 @@ public class LocalServerHttpUtilsTest extends TestCase { String responseContent = null; responseContent = HttpUtils.getResponseContentString(httpget, httpclient); - Assert.assertNotNull(responseContent); + Assertions.assertNotNull(responseContent); responseContent = HttpUtils.getResponseContentString(null, httpclient); - Assert.assertNull(responseContent); + Assertions.assertNull(responseContent); responseContent = HttpUtils.getResponseContentString(httpget, null); - Assert.assertNull(responseContent); + Assertions.assertNull(responseContent); } public void testGetHttpClient() { CloseableHttpClient httpClient1 = HttpUtils.getInstance(); CloseableHttpClient httpClient2 = HttpUtils.getInstance(); - Assert.assertEquals(httpClient1, httpClient2); + Assertions.assertEquals(httpClient1, httpClient2); } public void testKerberosHttpsGet() { @@ -89,19 +85,19 @@ public class LocalServerHttpUtilsTest extends TestCase { logger.info(PropertyUtils.getString(Constants.JAVA_SECURITY_KRB5_CONF_PATH)); String url = "https://www.apache.org/"; logger.info(KerberosHttpClient.get(url)); - Assert.assertTrue(true); + Assertions.assertTrue(true); } public void testHttpsGet() { String url = "https://www.apache.org/"; logger.info(HttpUtils.get(url)); - Assert.assertTrue(true); + Assertions.assertTrue(true); } public void testHttpGet() { String url = "http://www.apache.org/"; logger.info(HttpUtils.get(url)); - Assert.assertTrue(true); + Assertions.assertTrue(true); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/NetUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/NetUtilsTest.java index 7e0a8f3603..20625f29c2 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/NetUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/NetUtilsTest.java @@ -17,26 +17,23 @@ package org.apache.dolphinscheduler.common.utils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; import java.net.InetAddress; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; public class NetUtilsTest { @Test public void testGetAddr() { - assertEquals(NetUtils.getHost() + ":5678", NetUtils.getAddr(5678)); - assertEquals("127.0.0.1:5678", NetUtils.getAddr("127.0.0.1", 5678)); - assertEquals("localhost:1234", NetUtils.getAddr("localhost", 1234)); + Assertions.assertEquals(NetUtils.getHost() + ":5678", NetUtils.getAddr(5678)); + Assertions.assertEquals("127.0.0.1:5678", NetUtils.getAddr("127.0.0.1", 5678)); + Assertions.assertEquals("localhost:1234", NetUtils.getAddr("localhost", 1234)); } @Test @@ -48,23 +45,23 @@ public class NetUtilsTest { when(address.getCanonicalHostName()) .thenReturn("dolphinscheduler-worker-0.dolphinscheduler-worker-headless.default.svc.cluster.local"); when(address.getHostName()).thenReturn("dolphinscheduler-worker-0"); - assertEquals("dolphinscheduler-worker-0.dolphinscheduler-worker-headless", NetUtils.getHost(address)); + Assertions.assertEquals("dolphinscheduler-worker-0.dolphinscheduler-worker-headless", NetUtils.getHost(address)); address = mock(InetAddress.class); when(address.getCanonicalHostName()) .thenReturn("busybox-1.default-subdomain.my-namespace.svc.cluster-domain.example"); when(address.getHostName()).thenReturn("busybox-1"); - assertEquals("busybox-1.default-subdomain", NetUtils.getHost(address)); + Assertions.assertEquals("busybox-1.default-subdomain", NetUtils.getHost(address)); address = mock(InetAddress.class); when(address.getCanonicalHostName()).thenReturn("dolphinscheduler.cluster-domain.example"); when(address.getHostName()).thenReturn("dolphinscheduler"); - assertEquals("dolphinscheduler.cluster-domain.example", NetUtils.getHost(address)); + Assertions.assertEquals("dolphinscheduler.cluster-domain.example", NetUtils.getHost(address)); address = mock(InetAddress.class); when(address.getCanonicalHostName()).thenReturn("dolphinscheduler-worker-0"); when(address.getHostName()).thenReturn("dolphinscheduler-worker-0"); - assertEquals("dolphinscheduler-worker-0", NetUtils.getHost(address)); + Assertions.assertEquals("dolphinscheduler-worker-0", NetUtils.getHost(address)); } } @@ -75,46 +72,46 @@ public class NetUtilsTest { .thenReturn("dolphinscheduler-worker-0.dolphinscheduler-worker-headless.default.svc.cluster.local"); when(address.getHostName()).thenReturn("dolphinscheduler-worker-0"); when(address.getHostAddress()).thenReturn("172.17.0.15"); - assertEquals("172.17.0.15", NetUtils.getHost(address)); + Assertions.assertEquals("172.17.0.15", NetUtils.getHost(address)); } @Test public void testGetLocalHost() { - assertNotNull(NetUtils.getHost()); + Assertions.assertNotNull(NetUtils.getHost()); } @Test public void testIsValidAddress() { - assertFalse(NetUtils.isValidV4Address(null)); + Assertions.assertFalse(NetUtils.isValidV4Address(null)); InetAddress address = mock(InetAddress.class); when(address.isLoopbackAddress()).thenReturn(true); - assertFalse(NetUtils.isValidV4Address(address)); + Assertions.assertFalse(NetUtils.isValidV4Address(address)); address = mock(InetAddress.class); when(address.getHostAddress()).thenReturn("localhost"); - assertFalse(NetUtils.isValidV4Address(address)); + Assertions.assertFalse(NetUtils.isValidV4Address(address)); address = mock(InetAddress.class); when(address.getHostAddress()).thenReturn("0.0.0.0"); when(address.isAnyLocalAddress()).thenReturn(true); - assertFalse(NetUtils.isValidV4Address(address)); + Assertions.assertFalse(NetUtils.isValidV4Address(address)); address = mock(InetAddress.class); when(address.getHostAddress()).thenReturn("127.0.0.1"); when(address.isLoopbackAddress()).thenReturn(true); - assertFalse(NetUtils.isValidV4Address(address)); + Assertions.assertFalse(NetUtils.isValidV4Address(address)); address = mock(InetAddress.class); when(address.getHostAddress()).thenReturn("1.2.3.4"); - assertTrue(NetUtils.isValidV4Address(address)); + Assertions.assertTrue(NetUtils.isValidV4Address(address)); address = mock(InetAddress.class); when(address.getHostAddress()).thenReturn("1.2.3.4:80"); - assertFalse(NetUtils.isValidV4Address(address)); + Assertions.assertFalse(NetUtils.isValidV4Address(address)); address = mock(InetAddress.class); when(address.getHostAddress()).thenReturn("256.0.0.1"); - assertFalse(NetUtils.isValidV4Address(address)); + Assertions.assertFalse(NetUtils.isValidV4Address(address)); address = mock(InetAddress.class); when(address.getHostAddress()).thenReturn("127.0.0.0.1"); - assertFalse(NetUtils.isValidV4Address(address)); + Assertions.assertFalse(NetUtils.isValidV4Address(address)); address = mock(InetAddress.class); when(address.getHostAddress()).thenReturn("-1.2.3.4"); - assertFalse(NetUtils.isValidV4Address(address)); + Assertions.assertFalse(NetUtils.isValidV4Address(address)); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/PropertyUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/PropertyUtilsTest.java index b8c1cdac65..b4c6426372 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/PropertyUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/PropertyUtilsTest.java @@ -17,22 +17,19 @@ package org.apache.dolphinscheduler.common.utils; -import static org.junit.Assert.assertNotNull; - import org.apache.dolphinscheduler.common.Constants; - -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class PropertyUtilsTest { @Test public void getString() { - assertNotNull(PropertyUtils.getString(Constants.FS_DEFAULT_FS)); + Assertions.assertNotNull(PropertyUtils.getString(Constants.FS_DEFAULT_FS)); } @Test public void getResUploadStartupState() { - Assert.assertFalse(PropertyUtils.getResUploadStartupState()); + Assertions.assertFalse(PropertyUtils.getResUploadStartupState()); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/RetryerUtilsTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/RetryerUtilsTest.java index 7841e46585..8fcbdea5d0 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/RetryerUtilsTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/RetryerUtilsTest.java @@ -18,8 +18,8 @@ package org.apache.dolphinscheduler.common.utils; import com.github.rholder.retry.RetryException; import com.github.rholder.retry.Retryer; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.ExecutionException; @@ -28,21 +28,21 @@ public class RetryerUtilsTest { @Test public void testDefaultRetryer() { Retryer retryer = RetryerUtils.getDefaultRetryer(); - Assert.assertNotNull(retryer); + Assertions.assertNotNull(retryer); try { boolean result = retryer.call(() -> true); - Assert.assertTrue(result); + Assertions.assertTrue(result); } catch (ExecutionException | RetryException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } Retryer retryer1 = RetryerUtils.getDefaultRetryer(true); - Assert.assertEquals(retryer, retryer1); + Assertions.assertEquals(retryer, retryer1); } @Test public void testDefaultRetryerResultCheck() { Retryer retryer = RetryerUtils.getDefaultRetryer(); - Assert.assertNotNull(retryer); + Assertions.assertNotNull(retryer); try { for (int execTarget = 1; execTarget <= 3; execTarget++) { int finalExecTarget = execTarget; @@ -51,11 +51,11 @@ public class RetryerUtilsTest { execTime[0]++; return execTime[0] == finalExecTarget; }); - Assert.assertEquals(finalExecTarget, execTime[0]); - Assert.assertTrue(result); + Assertions.assertEquals(finalExecTarget, execTime[0]); + Assertions.assertTrue(result); } } catch (ExecutionException | RetryException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } int[] execTime = {0}; try { @@ -63,19 +63,19 @@ public class RetryerUtilsTest { execTime[0]++; return execTime[0] == 4; }); - Assert.fail("Retry times not reached"); + Assertions.fail("Retry times not reached"); } catch (RetryException e) { - Assert.assertEquals(3, e.getNumberOfFailedAttempts()); - Assert.assertEquals(3, execTime[0]); + Assertions.assertEquals(3, e.getNumberOfFailedAttempts()); + Assertions.assertEquals(3, execTime[0]); } catch (ExecutionException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } } @Test public void testDefaultRetryerResultNoCheck() { Retryer retryer = RetryerUtils.getDefaultRetryer(false); - Assert.assertNotNull(retryer); + Assertions.assertNotNull(retryer); try { for (int execTarget = 1; execTarget <= 5; execTarget++) { int[] execTime = {0}; @@ -83,11 +83,11 @@ public class RetryerUtilsTest { execTime[0]++; return execTime[0] > 1; }); - Assert.assertEquals(1, execTime[0]); - Assert.assertFalse(result); + Assertions.assertEquals(1, execTime[0]); + Assertions.assertFalse(result); } } catch (ExecutionException | RetryException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } } @@ -101,11 +101,11 @@ public class RetryerUtilsTest { execTime[0]++; return execTime[0] == finalExecTarget; }); - Assert.assertEquals(finalExecTarget, execTime[0]); - Assert.assertTrue(result); + Assertions.assertEquals(finalExecTarget, execTime[0]); + Assertions.assertTrue(result); } } catch (ExecutionException | RetryException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } int[] execTime = {0}; try { @@ -113,12 +113,12 @@ public class RetryerUtilsTest { execTime[0]++; return execTime[0] == 4; }); - Assert.fail("Recall times not reached"); + Assertions.fail("Recall times not reached"); } catch (RetryException e) { - Assert.assertEquals(3, e.getNumberOfFailedAttempts()); - Assert.assertEquals(3, execTime[0]); + Assertions.assertEquals(3, e.getNumberOfFailedAttempts()); + Assertions.assertEquals(3, execTime[0]); } catch (ExecutionException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } } @@ -132,11 +132,11 @@ public class RetryerUtilsTest { execTime[0]++; return execTime[0] == finalExecTarget; }, true); - Assert.assertEquals(finalExecTarget, execTime[0]); - Assert.assertTrue(result); + Assertions.assertEquals(finalExecTarget, execTime[0]); + Assertions.assertTrue(result); } } catch (ExecutionException | RetryException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } int[] execTime = {0}; try { @@ -144,12 +144,12 @@ public class RetryerUtilsTest { execTime[0]++; return execTime[0] == 4; }, true); - Assert.fail("Recall times not reached"); + Assertions.fail("Recall times not reached"); } catch (RetryException e) { - Assert.assertEquals(3, e.getNumberOfFailedAttempts()); - Assert.assertEquals(3, execTime[0]); + Assertions.assertEquals(3, e.getNumberOfFailedAttempts()); + Assertions.assertEquals(3, execTime[0]); } catch (ExecutionException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } } @@ -162,11 +162,11 @@ public class RetryerUtilsTest { execTime[0]++; return execTime[0] > 1; }, false); - Assert.assertEquals(1, execTime[0]); - Assert.assertFalse(result); + Assertions.assertEquals(1, execTime[0]); + Assertions.assertFalse(result); } } catch (ExecutionException | RetryException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } } @@ -182,11 +182,11 @@ public class RetryerUtilsTest { } return true; }, checkResult); - Assert.assertEquals(finalExecTarget, execTime[0]); - Assert.assertTrue(result); + Assertions.assertEquals(finalExecTarget, execTime[0]); + Assertions.assertTrue(result); } } catch (ExecutionException | RetryException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } int[] execTime = {0}; try { @@ -197,14 +197,14 @@ public class RetryerUtilsTest { } return true; }, checkResult); - Assert.fail("Recall times not reached"); + Assertions.fail("Recall times not reached"); } catch (RetryException e) { - Assert.assertEquals(3, e.getNumberOfFailedAttempts()); - Assert.assertEquals(3, execTime[0]); - Assert.assertNotNull(e.getCause()); - Assert.assertEquals(3, Integer.parseInt(e.getCause().getMessage())); + Assertions.assertEquals(3, e.getNumberOfFailedAttempts()); + Assertions.assertEquals(3, execTime[0]); + Assertions.assertNotNull(e.getCause()); + Assertions.assertEquals(3, Integer.parseInt(e.getCause().getMessage())); } catch (ExecutionException e) { - Assert.fail("Retry call failed " + e.getMessage()); + Assertions.fail("Retry call failed " + e.getMessage()); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/ScriptRunnerTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/ScriptRunnerTest.java index befc290fc1..cb983ae450 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/ScriptRunnerTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/ScriptRunnerTest.java @@ -16,10 +16,10 @@ */ package org.apache.dolphinscheduler.common.utils; -import java.io.StringReader; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; -import org.junit.Assert; -import org.junit.Test; +import java.io.StringReader; public class ScriptRunnerTest { @Test @@ -32,6 +32,6 @@ public class ScriptRunnerTest { } catch (Exception e) { exception = e; } - Assert.assertNotNull(exception); + Assertions.assertNotNull(exception); } } diff --git a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/StringTest.java b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/StringTest.java index 0f8055d6bb..d818eef21a 100644 --- a/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/StringTest.java +++ b/dolphinscheduler-common/src/test/java/org/apache/dolphinscheduler/common/utils/StringTest.java @@ -16,8 +16,8 @@ */ package org.apache.dolphinscheduler.common.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -47,7 +47,7 @@ public class StringTest { } } double during = (System.currentTimeMillis() - start) / 1000.0; - Assert.assertEquals("1_0000000000_0000000001", origin); + Assertions.assertEquals("1_0000000000_0000000001", origin); } } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/alert/AlertClientServiceTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/alert/AlertClientServiceTest.java index 686888face..3b7d7b2eae 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/alert/AlertClientServiceTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/alert/AlertClientServiceTest.java @@ -24,23 +24,22 @@ import org.apache.dolphinscheduler.remote.command.alert.AlertSendRequestCommand; import org.apache.dolphinscheduler.remote.command.alert.AlertSendResponseCommand; import org.apache.dolphinscheduler.remote.command.alert.AlertSendResponseResult; import org.apache.dolphinscheduler.remote.factory.NettyRemotingClientFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(MockitoJUnitRunner.class) +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +@ExtendWith(MockitoExtension.class) public class AlertClientServiceTest { private static final Logger logger = LoggerFactory.getLogger(AlertClientServiceTest.class); @@ -51,7 +50,7 @@ public class AlertClientServiceTest { private MockedStatic mockedNettyRemotingClientFactory; - @Before + @BeforeEach public void before() throws Exception { client = Mockito.mock(NettyRemotingClient.class); mockedNettyRemotingClientFactory = Mockito.mockStatic(NettyRemotingClientFactory.class); @@ -60,7 +59,7 @@ public class AlertClientServiceTest { alertClient = new AlertClientService(); } - @After + @AfterEach public void after() { mockedNettyRemotingClientFactory.close(); } @@ -76,7 +75,7 @@ public class AlertClientServiceTest { // 1.alter server does not exist AlertSendResponseCommand alertSendResponseCommand = alertClient.sendAlert(host, port, groupId, title, content, WarningType.FAILURE.getCode()); - Assert.assertNull(alertSendResponseCommand); + Assertions.assertNull(alertSendResponseCommand); AlertSendRequestCommand alertSendRequestCommand = new AlertSendRequestCommand(groupId, title, content, WarningType.FAILURE.getCode()); @@ -98,7 +97,7 @@ public class AlertClientServiceTest { Mockito.when(client.sendSync(Mockito.any(), Mockito.any(), Mockito.anyLong())).thenReturn(resCommand); alertSendResponseCommand = alertClient.sendAlert(host, port, groupId, title, content, WarningType.FAILURE.getCode()); - Assert.assertFalse(alertSendResponseCommand.isSuccess()); + Assertions.assertFalse(alertSendResponseCommand.isSuccess()); alertSendResponseCommand.getResResults().forEach(result -> logger .info("alert send response result, status:{}, message:{}", result.isSuccess(), result.getMessage())); @@ -113,7 +112,7 @@ public class AlertClientServiceTest { Mockito.when(client.sendSync(Mockito.any(), Mockito.any(), Mockito.anyLong())).thenReturn(resCommand); alertSendResponseCommand = alertClient.sendAlert(host, port, groupId, title, content, WarningType.FAILURE.getCode()); - Assert.assertFalse(alertSendResponseCommand.isSuccess()); + Assertions.assertFalse(alertSendResponseCommand.isSuccess()); alertSendResponseCommand.getResResults().forEach(result -> logger .info("alert send response result, status:{}, message:{}", result.isSuccess(), result.getMessage())); @@ -127,7 +126,7 @@ public class AlertClientServiceTest { Mockito.when(client.sendSync(Mockito.any(), Mockito.any(), Mockito.anyLong())).thenReturn(resCommand); alertSendResponseCommand = alertClient.sendAlert(host, port, groupId, title, content, WarningType.FAILURE.getCode()); - Assert.assertFalse(alertSendResponseCommand.isSuccess()); + Assertions.assertFalse(alertSendResponseCommand.isSuccess()); alertSendResponseCommand.getResResults().forEach(result -> logger .info("alert send response result, status:{}, message:{}", result.isSuccess(), result.getMessage())); @@ -140,7 +139,7 @@ public class AlertClientServiceTest { Mockito.when(client.sendSync(Mockito.any(), Mockito.any(), Mockito.anyLong())).thenReturn(resCommand); alertSendResponseCommand = alertClient.sendAlert(host, port, groupId, title, content, WarningType.FAILURE.getCode()); - Assert.assertFalse(alertSendResponseCommand.isSuccess()); + Assertions.assertFalse(alertSendResponseCommand.isSuccess()); alertSendResponseCommand.getResResults().forEach(result -> logger .info("alert send response result, status:{}, message:{}", result.isSuccess(), result.getMessage())); @@ -154,7 +153,7 @@ public class AlertClientServiceTest { Mockito.when(client.sendSync(Mockito.any(), Mockito.any(), Mockito.anyLong())).thenReturn(resCommand); alertSendResponseCommand = alertClient.sendAlert(host, port, groupId, title, content, WarningType.FAILURE.getCode()); - Assert.assertTrue(alertSendResponseCommand.isSuccess()); + Assertions.assertTrue(alertSendResponseCommand.isSuccess()); alertSendResponseCommand.getResResults().forEach(result -> logger .info("alert send response result, status:{}, message:{}", result.isSuccess(), result.getMessage())); diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/alert/ProcessAlertManagerTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/alert/ProcessAlertManagerTest.java index e0fbc58b9a..a1622da903 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/alert/ProcessAlertManagerTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/alert/ProcessAlertManagerTest.java @@ -24,23 +24,22 @@ import org.apache.dolphinscheduler.dao.AlertDao; import org.apache.dolphinscheduler.dao.entity.ProcessInstance; import org.apache.dolphinscheduler.dao.entity.ProjectUser; import org.apache.dolphinscheduler.dao.entity.TaskInstance; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + /** * ProcessAlertManager Test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ProcessAlertManagerTest { private static final Logger logger = LoggerFactory.getLogger(ProcessAlertManagerTest.class); diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/cache/CacheNotifyServiceTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/cache/CacheNotifyServiceTest.java index a3dafb677b..8655def27b 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/cache/CacheNotifyServiceTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/cache/CacheNotifyServiceTest.java @@ -28,29 +28,23 @@ import org.apache.dolphinscheduler.remote.command.CommandType; import org.apache.dolphinscheduler.remote.config.NettyServerConfig; import org.apache.dolphinscheduler.service.cache.impl.CacheNotifyServiceImpl; import org.apache.dolphinscheduler.service.registry.RegistryClient; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.ArrayList; +import java.util.List; /** * tenant cache proxy test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) public class CacheNotifyServiceTest { - @Rule - public final ExpectedException exception = ExpectedException.none(); - @InjectMocks private CacheNotifyServiceImpl cacheNotifyService; @@ -67,7 +61,7 @@ public class CacheNotifyServiceTest { NettyRemotingServer nettyRemotingServer = new NettyRemotingServer(serverConfig); nettyRemotingServer.registerProcessor(CommandType.CACHE_EXPIRE, (channel, command) -> { - Assert.assertEquals(cacheExpireCommand, command); + Assertions.assertEquals(cacheExpireCommand, command); }); nettyRemotingServer.start(); diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/cron/CronUtilsTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/cron/CronUtilsTest.java index 1e2b2548eb..199a351feb 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/cron/CronUtilsTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/cron/CronUtilsTest.java @@ -17,36 +17,26 @@ package org.apache.dolphinscheduler.service.cron; -import static com.cronutils.model.field.expression.FieldExpressionFactory.always; -import static com.cronutils.model.field.expression.FieldExpressionFactory.every; -import static com.cronutils.model.field.expression.FieldExpressionFactory.on; -import static com.cronutils.model.field.expression.FieldExpressionFactory.questionMark; - +import com.cronutils.builder.CronBuilder; +import com.cronutils.model.Cron; +import com.cronutils.model.CronType; +import com.cronutils.model.definition.CronDefinitionBuilder; +import com.cronutils.model.field.CronField; +import com.cronutils.model.field.CronFieldName; +import com.cronutils.model.field.expression.*; import org.apache.dolphinscheduler.common.enums.CycleEnum; import org.apache.dolphinscheduler.common.utils.DateUtils; import org.apache.dolphinscheduler.service.exceptions.CronParseException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Date; -import org.junit.Assert; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.cronutils.builder.CronBuilder; -import com.cronutils.model.Cron; -import com.cronutils.model.CronType; -import com.cronutils.model.definition.CronDefinitionBuilder; -import com.cronutils.model.field.CronField; -import com.cronutils.model.field.CronFieldName; -import com.cronutils.model.field.expression.Always; -import com.cronutils.model.field.expression.And; -import com.cronutils.model.field.expression.Between; -import com.cronutils.model.field.expression.Every; -import com.cronutils.model.field.expression.On; -import com.cronutils.model.field.expression.QuestionMark; +import static com.cronutils.model.field.expression.FieldExpressionFactory.*; /** * CronUtilsTest @@ -67,7 +57,7 @@ public class CronUtilsTest { String cronAsString = cron.asString(); // 0 */5 * * * ? * Every five minutes(once every 5 minutes) - Assert.assertEquals("0 */5 * * * ? *", cronAsString); + Assertions.assertEquals("0 */5 * * * ? *", cronAsString); } @@ -79,12 +69,12 @@ public class CronUtilsTest { String strCrontab = "0 1 2 3 * ? *"; Cron depCron = CronUtils.parse2Cron(strCrontab); - Assert.assertEquals("0", depCron.retrieve(CronFieldName.SECOND).getExpression().asString()); - Assert.assertEquals("1", depCron.retrieve(CronFieldName.MINUTE).getExpression().asString()); - Assert.assertEquals("2", depCron.retrieve(CronFieldName.HOUR).getExpression().asString()); - Assert.assertEquals("3", depCron.retrieve(CronFieldName.DAY_OF_MONTH).getExpression().asString()); - Assert.assertEquals("*", depCron.retrieve(CronFieldName.MONTH).getExpression().asString()); - Assert.assertEquals("*", depCron.retrieve(CronFieldName.YEAR).getExpression().asString()); + Assertions.assertEquals("0", depCron.retrieve(CronFieldName.SECOND).getExpression().asString()); + Assertions.assertEquals("1", depCron.retrieve(CronFieldName.MINUTE).getExpression().asString()); + Assertions.assertEquals("2", depCron.retrieve(CronFieldName.HOUR).getExpression().asString()); + Assertions.assertEquals("3", depCron.retrieve(CronFieldName.DAY_OF_MONTH).getExpression().asString()); + Assertions.assertEquals("*", depCron.retrieve(CronFieldName.MONTH).getExpression().asString()); + Assertions.assertEquals("*", depCron.retrieve(CronFieldName.YEAR).getExpression().asString()); } /** @@ -93,27 +83,27 @@ public class CronUtilsTest { @Test public void testScheduleType() throws CronParseException { CycleEnum cycleEnum = CronUtils.getMaxCycle(CronUtils.parse2Cron("0 */1 * * * ? *")); - Assert.assertEquals("MINUTE", cycleEnum.name()); + Assertions.assertEquals("MINUTE", cycleEnum.name()); CycleEnum cycleEnum2 = CronUtils.getMaxCycle("0 * * * * ? *"); - Assert.assertEquals("MINUTE", cycleEnum2.name()); + Assertions.assertEquals("MINUTE", cycleEnum2.name()); CycleEnum cycleEnum3 = CronUtils.getMiniCycle(CronUtils.parse2Cron("0 * * * * ? *")); - Assert.assertEquals("MINUTE", cycleEnum3.name()); + Assertions.assertEquals("MINUTE", cycleEnum3.name()); CycleEnum cycleEnum4 = CronUtils.getMaxCycle(CronUtils.parse2Cron("0 0 7 * 1 ? *")); - Assert.assertEquals("YEAR", cycleEnum4.name()); + Assertions.assertEquals("YEAR", cycleEnum4.name()); cycleEnum4 = CronUtils.getMiniCycle(CronUtils.parse2Cron("0 0 7 * 1 ? *")); - Assert.assertEquals("DAY", cycleEnum4.name()); + Assertions.assertEquals("DAY", cycleEnum4.name()); CycleEnum cycleEnum5 = CronUtils.getMaxCycle(CronUtils.parse2Cron("0 0 7 * 1/1 ? *")); - Assert.assertEquals("MONTH", cycleEnum5.name()); + Assertions.assertEquals("MONTH", cycleEnum5.name()); CycleEnum cycleEnum6 = CronUtils.getMaxCycle(CronUtils.parse2Cron("0 0 7 * 1-2 ? *")); - Assert.assertEquals("YEAR", cycleEnum6.name()); + Assertions.assertEquals("YEAR", cycleEnum6.name()); CycleEnum cycleEnum7 = CronUtils.getMaxCycle(CronUtils.parse2Cron("0 0 7 * 1,2 ? *")); - Assert.assertEquals("YEAR", cycleEnum7.name()); + Assertions.assertEquals("YEAR", cycleEnum7.name()); } /** @@ -184,7 +174,7 @@ public class CronUtilsTest { logger.info("can't get scheduleType"); } } - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test @@ -194,31 +184,31 @@ public class CronUtilsTest { ZonedDateTime to = ZonedDateTime.ofInstant(DateUtils.stringToDate("2020-01-31 00:00:00").toInstant(), ZoneId.systemDefault()); // test date - Assert.assertEquals(0, CronUtils.getFireDateList(to, from, "0 0 0 * * ? ").size()); + Assertions.assertEquals(0, CronUtils.getFireDateList(to, from, "0 0 0 * * ? ").size()); try { // test error cron // should throw exception CronUtils.getFireDateList(from, to, "0 0 0 * *").size(); - Assert.assertTrue(false); + Assertions.fail(); } catch (CronParseException cronParseException) { - Assert.assertTrue(true); + Assertions.assertTrue(true); } // test cron - Assert.assertEquals(30, CronUtils.getFireDateList(from, to, "0 0 0 * * ? ").size()); + Assertions.assertEquals(30, CronUtils.getFireDateList(from, to, "0 0 0 * * ? ").size()); // test other - Assert.assertEquals(30, CronUtils.getFireDateList(from, to, CronUtils.parse2Cron("0 0 0 * * ? ")).size()); - Assert.assertEquals(5, CronUtils.getSelfFireDateList(from, to, CronUtils.parse2Cron("0 0 0 * * ? "), 5).size()); + Assertions.assertEquals(30, CronUtils.getFireDateList(from, to, CronUtils.parse2Cron("0 0 0 * * ? ")).size()); + Assertions.assertEquals(5, CronUtils.getSelfFireDateList(from, to, CronUtils.parse2Cron("0 0 0 * * ? "), 5).size()); from = ZonedDateTime.ofInstant(DateUtils.stringToDate("2020-01-01 00:02:00").toInstant(), ZoneId.systemDefault()); to = ZonedDateTime.ofInstant(DateUtils.stringToDate("2020-01-01 00:02:00").toInstant(), ZoneId.systemDefault()); - Assert.assertEquals(1, + Assertions.assertEquals(1, CronUtils.getFireDateList(from.minusSeconds(1L), to, CronUtils.parse2Cron("0 * * * * ? ")).size()); from = ZonedDateTime.ofInstant(DateUtils.stringToDate("2020-01-01 00:02:00").toInstant(), ZoneId.systemDefault()); to = ZonedDateTime.ofInstant(DateUtils.stringToDate("2020-01-01 00:04:00").toInstant(), ZoneId.systemDefault()); - Assert.assertEquals(2, + Assertions.assertEquals(2, CronUtils.getFireDateList(from.minusSeconds(1L), to.minusSeconds(1L), CronUtils.parse2Cron("0 * * * * ? ")) .size()); } @@ -227,14 +217,14 @@ public class CronUtilsTest { public void getExpirationTime() { Date startTime = DateUtils.stringToDate("2020-02-07 18:30:00"); Date expirationTime = CronUtils.getExpirationTime(startTime, CycleEnum.HOUR); - Assert.assertEquals("2020-02-07 19:30:00", DateUtils.dateToString(expirationTime)); + Assertions.assertEquals("2020-02-07 19:30:00", DateUtils.dateToString(expirationTime)); expirationTime = CronUtils.getExpirationTime(startTime, CycleEnum.DAY); - Assert.assertEquals("2020-02-07 23:59:59", DateUtils.dateToString(expirationTime)); + Assertions.assertEquals("2020-02-07 23:59:59", DateUtils.dateToString(expirationTime)); expirationTime = CronUtils.getExpirationTime(startTime, CycleEnum.WEEK); - Assert.assertEquals("2020-02-07 23:59:59", DateUtils.dateToString(expirationTime)); + Assertions.assertEquals("2020-02-07 23:59:59", DateUtils.dateToString(expirationTime)); expirationTime = CronUtils.getExpirationTime(startTime, CycleEnum.MONTH); - Assert.assertEquals("2020-02-07 23:59:59", DateUtils.dateToString(expirationTime)); + Assertions.assertEquals("2020-02-07 23:59:59", DateUtils.dateToString(expirationTime)); expirationTime = CronUtils.getExpirationTime(startTime, CycleEnum.YEAR); - Assert.assertEquals("2020-02-07 18:30:00", DateUtils.dateToString(expirationTime)); + Assertions.assertEquals("2020-02-07 18:30:00", DateUtils.dateToString(expirationTime)); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/expand/CuringGlobalParamsServiceTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/expand/CuringGlobalParamsServiceTest.java index e89748446c..b8fe224561 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/expand/CuringGlobalParamsServiceTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/expand/CuringGlobalParamsServiceTest.java @@ -24,22 +24,18 @@ import org.apache.dolphinscheduler.common.utils.JSONUtils; import org.apache.dolphinscheduler.plugin.task.api.enums.DataType; import org.apache.dolphinscheduler.plugin.task.api.enums.Direct; import org.apache.dolphinscheduler.plugin.task.api.model.Property; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import java.util.*; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class CuringGlobalParamsServiceTest { private static final String placeHolderName = "$[yyyy-MM-dd-1]"; @@ -58,7 +54,7 @@ public class CuringGlobalParamsServiceTest { private final Map globalParamMap = new HashMap<>(); - @Before + @BeforeEach public void init() { globalParamMap.put("globalParams1", "Params1"); } @@ -67,19 +63,19 @@ public class CuringGlobalParamsServiceTest { public void testConvertParameterPlaceholders() { Mockito.when(curingGlobalParamsService.convertParameterPlaceholders(placeHolderName, globalParamMap)).thenReturn("2022-06-26"); String result = curingGlobalParamsService.convertParameterPlaceholders(placeHolderName, globalParamMap); - Assert.assertNotNull(result); + Assertions.assertNotNull(result); } @Test public void testTimeFunctionNeedExpand() { boolean result = curingGlobalParamsService.timeFunctionNeedExpand(placeHolderName); - Assert.assertFalse(result); + Assertions.assertFalse(result); } @Test public void testTimeFunctionExtension() { String result = curingGlobalParamsService.timeFunctionExtension(1, "", placeHolderName); - Assert.assertNull(result); + Assertions.assertNull(result); } @Test @@ -96,22 +92,22 @@ public class CuringGlobalParamsServiceTest { //test globalParamList is null String result = dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, globalParamMap, globalParamList, CommandType.START_CURRENT_TASK_PROCESS, scheduleTime, null); - Assert.assertNull(result); - Assert.assertNull(dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, null, null, CommandType.START_CURRENT_TASK_PROCESS, null, null)); - Assert.assertNull(dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, globalParamMap, null, CommandType.START_CURRENT_TASK_PROCESS, scheduleTime, null)); + Assertions.assertNull(result); + Assertions.assertNull(dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, null, null, CommandType.START_CURRENT_TASK_PROCESS, null, null)); + Assertions.assertNull(dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, globalParamMap, null, CommandType.START_CURRENT_TASK_PROCESS, scheduleTime, null)); //test globalParamList is not null Property property = new Property("testGlobalParam", Direct.IN, DataType.VARCHAR, "testGlobalParam"); globalParamList.add(property); String result2 = dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, null, globalParamList, CommandType.START_CURRENT_TASK_PROCESS, scheduleTime, null); - Assert.assertEquals(result2, JSONUtils.toJsonString(globalParamList)); + Assertions.assertEquals(result2, JSONUtils.toJsonString(globalParamList)); String result3 = dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, globalParamMap, globalParamList, CommandType.START_CURRENT_TASK_PROCESS, null, null); - Assert.assertEquals(result3, JSONUtils.toJsonString(globalParamList)); + Assertions.assertEquals(result3, JSONUtils.toJsonString(globalParamList)); String result4 = dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, globalParamMap, globalParamList, CommandType.START_CURRENT_TASK_PROCESS, scheduleTime, null); - Assert.assertEquals(result4, JSONUtils.toJsonString(globalParamList)); + Assertions.assertEquals(result4, JSONUtils.toJsonString(globalParamList)); //test var $ startsWith globalParamMap.put("bizDate", "${system.biz.date}"); @@ -126,7 +122,7 @@ public class CuringGlobalParamsServiceTest { globalParamList.add(property4); String result5 = dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, globalParamMap, globalParamList, CommandType.START_CURRENT_TASK_PROCESS, scheduleTime, null); - Assert.assertEquals(result5, JSONUtils.toJsonString(globalParamList)); + Assertions.assertEquals(result5, JSONUtils.toJsonString(globalParamList)); Property testStartParamProperty = new Property("testStartParam", Direct.IN, DataType.VARCHAR, ""); globalParamList.add(testStartParamProperty); @@ -146,6 +142,6 @@ public class CuringGlobalParamsServiceTest { } String result6 = dolphinSchedulerCuringGlobalParams.curingGlobalParams(1, globalParamMap, globalParamList, CommandType.START_CURRENT_TASK_PROCESS, scheduleTime, null); - Assert.assertTrue(result6.contains("20191220")); + Assertions.assertTrue(result6.contains("20191220")); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/expand/TimePlaceholderResolverExpandServiceTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/expand/TimePlaceholderResolverExpandServiceTest.java index 08d04be5c5..025ed9f7cf 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/expand/TimePlaceholderResolverExpandServiceTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/expand/TimePlaceholderResolverExpandServiceTest.java @@ -18,14 +18,14 @@ package org.apache.dolphinscheduler.service.expand; import org.apache.commons.lang3.StringUtils; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class TimePlaceholderResolverExpandServiceTest { @Mock @@ -39,13 +39,13 @@ public class TimePlaceholderResolverExpandServiceTest { @Test public void testTimePlaceholderResolverExpandService() { boolean checkResult = timePlaceholderResolverExpandService.timeFunctionNeedExpand(placeHolderName); - Assert.assertFalse(checkResult); + Assertions.assertFalse(checkResult); String resultString = timePlaceholderResolverExpandService.timeFunctionExtension(1, "", placeHolderName); - Assert.assertTrue(StringUtils.isEmpty(resultString)); + Assertions.assertTrue(StringUtils.isEmpty(resultString)); boolean implCheckResult = timePlaceholderResolverExpandServiceImpl.timeFunctionNeedExpand(placeHolderName); - Assert.assertFalse(implCheckResult); + Assertions.assertFalse(implCheckResult); String implResultString = timePlaceholderResolverExpandServiceImpl.timeFunctionExtension(1, "", placeHolderName); - Assert.assertTrue(StringUtils.isEmpty(implResultString)); + Assertions.assertTrue(StringUtils.isEmpty(implResultString)); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/LogClientTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/LogClientTest.java index 3e0e73d595..1c48368211 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/LogClientTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/LogClientTest.java @@ -28,17 +28,16 @@ import org.apache.dolphinscheduler.remote.command.log.ViewLogResponseCommand; import org.apache.dolphinscheduler.remote.factory.NettyRemotingClientFactory; import org.apache.dolphinscheduler.remote.utils.Host; import org.apache.dolphinscheduler.service.utils.LoggerUtils; - -import java.nio.charset.StandardCharsets; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.nio.charset.StandardCharsets; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class LogClientTest { @Test @@ -56,7 +55,7 @@ public class LogClientTest { .thenReturn("application_xx_11"); LogClient logClient = new LogClient(); String log = logClient.viewLog(localMachine, port, path); - Assert.assertNotNull(log); + Assertions.assertNotNull(log); } } @@ -71,14 +70,14 @@ public class LogClientTest { .thenReturn(localMachine + "1"); LogClient logClient = new LogClient(); String log = logClient.viewLog(localMachine, port, path); - Assert.assertNotNull(log); + Assertions.assertNotNull(log); } Command command = new Command(); command.setBody(JSONUtils.toJsonString(new ViewLogResponseCommand("")).getBytes(StandardCharsets.UTF_8)); LogClient logClient = new LogClient(); String log = logClient.viewLog(localMachine, port, path); - Assert.assertNotNull(log); + Assertions.assertNotNull(log); } @Test @@ -110,7 +109,7 @@ public class LogClientTest { LogClient logClient = new LogClient(); String msg = logClient.rollViewLog("localhost", 1234, "/tmp/log", 0, 10); - Assert.assertNotNull(msg); + Assertions.assertNotNull(msg); } } @@ -131,7 +130,7 @@ public class LogClientTest { LogClient logClient = new LogClient(); byte[] logBytes = logClient.getLogBytes("localhost", 1234, "/tmp/log"); - Assert.assertNotNull(logBytes); + Assertions.assertNotNull(logBytes); } } @@ -152,7 +151,7 @@ public class LogClientTest { LogClient logClient = new LogClient(); Boolean status = logClient.removeTaskLog("localhost", 1234, "/log/path"); - Assert.assertTrue(status); + Assertions.assertTrue(status); } } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/LoggerRequestProcessorTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/LoggerRequestProcessorTest.java index 09626756fc..44b783a7be 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/LoggerRequestProcessorTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/LoggerRequestProcessorTest.java @@ -17,33 +17,32 @@ package org.apache.dolphinscheduler.service.log; +import io.netty.channel.Channel; import org.apache.dolphinscheduler.common.utils.JSONUtils; import org.apache.dolphinscheduler.remote.command.Command; import org.apache.dolphinscheduler.remote.command.CommandType; import org.apache.dolphinscheduler.remote.command.log.ViewLogRequestCommand; import org.apache.dolphinscheduler.service.utils.LoggerUtils; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -import io.netty.channel.Channel; - -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class LoggerRequestProcessorTest { private MockedStatic mockedStaticLoggerUtils; - @Before + @BeforeEach public void setUp() { mockedStaticLoggerUtils = Mockito.mockStatic(LoggerUtils.class); } - @After + @AfterEach public void after() { mockedStaticLoggerUtils.close(); } @@ -65,7 +64,7 @@ public class LoggerRequestProcessorTest { loggerRequestProcessor.process(channel, command); } - @Test(expected = IllegalArgumentException.class) + @Test public void testProcessViewWholeLogRequestError() { System.setProperty("DOLPHINSCHEDULER_WORKER_HOME", System.getProperty("user.dir")); Channel channel = Mockito.mock(Channel.class); @@ -78,10 +77,12 @@ public class LoggerRequestProcessorTest { command.setBody(JSONUtils.toJsonByteArray(logRequestCommand)); LoggerRequestProcessor loggerRequestProcessor = new LoggerRequestProcessor(); - loggerRequestProcessor.process(channel, command); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + loggerRequestProcessor.process(channel, command); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testProcessViewWholeLogRequestErrorRelativePath() { System.setProperty("DOLPHINSCHEDULER_WORKER_HOME", System.getProperty("user.dir")); Channel channel = Mockito.mock(Channel.class); @@ -94,10 +95,12 @@ public class LoggerRequestProcessorTest { command.setBody(JSONUtils.toJsonByteArray(logRequestCommand)); LoggerRequestProcessor loggerRequestProcessor = new LoggerRequestProcessor(); - loggerRequestProcessor.process(channel, command); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + loggerRequestProcessor.process(channel, command); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testProcessViewWholeLogRequestErrorStartWith() { System.setProperty("DOLPHINSCHEDULER_WORKER_HOME", System.getProperty("user.dir")); Channel channel = Mockito.mock(Channel.class); @@ -109,6 +112,8 @@ public class LoggerRequestProcessorTest { command.setBody(JSONUtils.toJsonByteArray(logRequestCommand)); LoggerRequestProcessor loggerRequestProcessor = new LoggerRequestProcessor(); - loggerRequestProcessor.process(channel, command); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + loggerRequestProcessor.process(channel, command); + }); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/MasterLogFilterTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/MasterLogFilterTest.java index 13fe5f0d39..ecc28cd8aa 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/MasterLogFilterTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/MasterLogFilterTest.java @@ -16,14 +16,12 @@ */ package org.apache.dolphinscheduler.service.log; -import org.apache.dolphinscheduler.common.Constants; - -import org.junit.Assert; -import org.junit.Test; - import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.spi.FilterReply; +import org.apache.dolphinscheduler.common.Constants; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class MasterLogFilterTest { @@ -50,7 +48,7 @@ public class MasterLogFilterTest { }); - Assert.assertEquals(FilterReply.ACCEPT, filterReply); + Assertions.assertEquals(FilterReply.ACCEPT, filterReply); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/SensitiveDataConverterTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/SensitiveDataConverterTest.java index 36b3b5e369..d4514ab95c 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/SensitiveDataConverterTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/SensitiveDataConverterTest.java @@ -17,16 +17,15 @@ package org.apache.dolphinscheduler.service.log; -import static org.apache.dolphinscheduler.service.log.SensitiveDataConverter.passwordHandler; - import org.apache.dolphinscheduler.common.Constants; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.regex.Pattern; -import org.junit.Assert; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import static org.apache.dolphinscheduler.service.log.SensitiveDataConverter.passwordHandler; public class SensitiveDataConverterTest { @@ -51,7 +50,7 @@ public class SensitiveDataConverterTest { @Test public void convert() { - Assert.assertEquals(maskLogMsg, passwordHandler(pwdPattern, logMsg)); + Assertions.assertEquals(maskLogMsg, passwordHandler(pwdPattern, logMsg)); } /** @@ -62,8 +61,8 @@ public class SensitiveDataConverterTest { logger.info("parameter : {}", logMsg); logger.info("parameter : {}", passwordHandler(pwdPattern, logMsg)); - Assert.assertNotEquals(logMsg, passwordHandler(pwdPattern, logMsg)); - Assert.assertEquals(maskLogMsg, passwordHandler(pwdPattern, logMsg)); + Assertions.assertNotEquals(logMsg, passwordHandler(pwdPattern, logMsg)); + Assertions.assertEquals(maskLogMsg, passwordHandler(pwdPattern, logMsg)); } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/TaskLogDiscriminatorTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/TaskLogDiscriminatorTest.java index a2c3b6aa7e..c8bec75d08 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/TaskLogDiscriminatorTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/TaskLogDiscriminatorTest.java @@ -16,14 +16,12 @@ */ package org.apache.dolphinscheduler.service.log; -import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.LoggingEvent; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TaskLogDiscriminatorTest { @@ -34,7 +32,7 @@ public class TaskLogDiscriminatorTest { TaskLogDiscriminator taskLogDiscriminator; - @Before + @BeforeEach public void before() { taskLogDiscriminator = new TaskLogDiscriminator(); taskLogDiscriminator.setLogBase("logs"); @@ -75,18 +73,18 @@ public class TaskLogDiscriminatorTest { return TaskConstants.TASK_LOG_LOGGER_NAME; } }); - Assert.assertEquals("20220105/101-1-1001", result); + Assertions.assertEquals("20220105/101-1-1001", result); } @Test public void start() { taskLogDiscriminator.start(); - Assert.assertEquals(true, taskLogDiscriminator.isStarted()); + Assertions.assertEquals(true, taskLogDiscriminator.isStarted()); } @Test public void getKey() { - Assert.assertEquals("123", taskLogDiscriminator.getKey()); + Assertions.assertEquals("123", taskLogDiscriminator.getKey()); } @Test @@ -97,7 +95,7 @@ public class TaskLogDiscriminatorTest { @Test public void getLogBase() { - Assert.assertEquals("logs", taskLogDiscriminator.getLogBase()); + Assertions.assertEquals("logs", taskLogDiscriminator.getLogBase()); } @Test diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/TaskLogFilterTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/TaskLogFilterTest.java index fe99768031..56a1023fa4 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/TaskLogFilterTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/TaskLogFilterTest.java @@ -16,14 +16,12 @@ */ package org.apache.dolphinscheduler.service.log; -import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; - -import org.junit.Assert; -import org.junit.Test; - import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.spi.FilterReply; +import org.apache.dolphinscheduler.plugin.task.api.TaskConstants; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class TaskLogFilterTest { @@ -64,7 +62,7 @@ public class TaskLogFilterTest { } }); - Assert.assertEquals(FilterReply.ACCEPT, filterReply); + Assertions.assertEquals(FilterReply.ACCEPT, filterReply); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/WorkerLogFilterTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/WorkerLogFilterTest.java index c7110d2501..d0d408f797 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/WorkerLogFilterTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/log/WorkerLogFilterTest.java @@ -16,14 +16,12 @@ */ package org.apache.dolphinscheduler.service.log; -import org.apache.dolphinscheduler.common.Constants; - -import org.junit.Assert; -import org.junit.Test; - import ch.qos.logback.classic.Level; import ch.qos.logback.classic.spi.LoggingEvent; import ch.qos.logback.core.spi.FilterReply; +import org.apache.dolphinscheduler.common.Constants; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class WorkerLogFilterTest { @@ -60,7 +58,7 @@ public class WorkerLogFilterTest { }); - Assert.assertEquals(FilterReply.ACCEPT, filterReply); + Assertions.assertEquals(FilterReply.ACCEPT, filterReply); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/process/ProcessServiceTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/process/ProcessServiceTest.java index 426942ebc5..bb47c74529 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/process/ProcessServiceTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/process/ProcessServiceTest.java @@ -17,65 +17,18 @@ package org.apache.dolphinscheduler.service.process; -import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_RECOVER_PROCESS_ID_STRING; -import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_START_PARAMS; -import static org.apache.dolphinscheduler.common.Constants.CMD_PARAM_SUB_PROCESS_DEFINE_CODE; -import static org.mockito.ArgumentMatchers.any; - +import com.fasterxml.jackson.databind.JsonNode; import org.apache.dolphinscheduler.common.Constants; -import org.apache.dolphinscheduler.common.enums.CommandType; -import org.apache.dolphinscheduler.common.enums.Flag; -import org.apache.dolphinscheduler.common.enums.ProcessExecutionTypeEnum; -import org.apache.dolphinscheduler.common.enums.TaskGroupQueueStatus; -import org.apache.dolphinscheduler.common.enums.UserType; -import org.apache.dolphinscheduler.common.enums.WarningType; +import org.apache.dolphinscheduler.common.enums.*; import org.apache.dolphinscheduler.common.graph.DAG; import org.apache.dolphinscheduler.common.model.TaskNodeRelation; import org.apache.dolphinscheduler.common.utils.CodeGenerateUtils; import org.apache.dolphinscheduler.common.utils.DateUtils; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.apache.dolphinscheduler.dao.entity.Command; -import org.apache.dolphinscheduler.dao.entity.DqExecuteResult; -import org.apache.dolphinscheduler.dao.entity.DqRule; -import org.apache.dolphinscheduler.dao.entity.DqRuleExecuteSql; -import org.apache.dolphinscheduler.dao.entity.DqRuleInputEntry; -import org.apache.dolphinscheduler.dao.entity.ProcessDefinition; -import org.apache.dolphinscheduler.dao.entity.ProcessDefinitionLog; -import org.apache.dolphinscheduler.dao.entity.ProcessInstance; -import org.apache.dolphinscheduler.dao.entity.ProcessInstanceMap; -import org.apache.dolphinscheduler.dao.entity.ProcessTaskRelationLog; -import org.apache.dolphinscheduler.dao.entity.Resource; -import org.apache.dolphinscheduler.dao.entity.TaskDefinitionLog; -import org.apache.dolphinscheduler.dao.entity.TaskGroupQueue; -import org.apache.dolphinscheduler.dao.entity.TaskInstance; -import org.apache.dolphinscheduler.dao.entity.User; -import org.apache.dolphinscheduler.dao.mapper.CommandMapper; -import org.apache.dolphinscheduler.dao.mapper.DataSourceMapper; -import org.apache.dolphinscheduler.dao.mapper.DqComparisonTypeMapper; -import org.apache.dolphinscheduler.dao.mapper.DqExecuteResultMapper; -import org.apache.dolphinscheduler.dao.mapper.DqRuleExecuteSqlMapper; -import org.apache.dolphinscheduler.dao.mapper.DqRuleInputEntryMapper; -import org.apache.dolphinscheduler.dao.mapper.DqRuleMapper; -import org.apache.dolphinscheduler.dao.mapper.ErrorCommandMapper; -import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionLogMapper; -import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper; -import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapper; -import org.apache.dolphinscheduler.dao.mapper.ProcessTaskRelationLogMapper; -import org.apache.dolphinscheduler.dao.mapper.ProcessTaskRelationMapper; -import org.apache.dolphinscheduler.dao.mapper.ResourceMapper; -import org.apache.dolphinscheduler.dao.mapper.ScheduleMapper; -import org.apache.dolphinscheduler.dao.mapper.TaskDefinitionLogMapper; -import org.apache.dolphinscheduler.dao.mapper.TaskDefinitionMapper; -import org.apache.dolphinscheduler.dao.mapper.TaskGroupMapper; -import org.apache.dolphinscheduler.dao.mapper.TaskGroupQueueMapper; -import org.apache.dolphinscheduler.dao.mapper.TaskInstanceMapper; -import org.apache.dolphinscheduler.dao.mapper.UserMapper; +import org.apache.dolphinscheduler.dao.entity.*; +import org.apache.dolphinscheduler.dao.mapper.*; import org.apache.dolphinscheduler.dao.repository.ProcessInstanceDao; -import org.apache.dolphinscheduler.plugin.task.api.enums.dp.DqTaskState; -import org.apache.dolphinscheduler.plugin.task.api.enums.dp.ExecuteSqlType; -import org.apache.dolphinscheduler.plugin.task.api.enums.dp.InputType; -import org.apache.dolphinscheduler.plugin.task.api.enums.dp.OptionSourceType; -import org.apache.dolphinscheduler.plugin.task.api.enums.dp.ValueType; +import org.apache.dolphinscheduler.plugin.task.api.enums.dp.*; import org.apache.dolphinscheduler.plugin.task.api.model.DateInterval; import org.apache.dolphinscheduler.plugin.task.api.model.ResourceInfo; import org.apache.dolphinscheduler.service.cron.CronUtilsTest; @@ -85,39 +38,31 @@ import org.apache.dolphinscheduler.service.expand.CuringParamsService; import org.apache.dolphinscheduler.service.model.TaskNode; import org.apache.dolphinscheduler.service.task.TaskPluginManager; import org.apache.dolphinscheduler.spi.params.base.FormType; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.fasterxml.jackson.databind.JsonNode; +import java.util.*; + +import static org.apache.dolphinscheduler.common.Constants.*; +import static org.mockito.ArgumentMatchers.any; /** * process service test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ProcessServiceTest { private static final Logger logger = LoggerFactory.getLogger(CronUtilsTest.class); - - @Rule - public final ExpectedException exception = ExpectedException.none(); - @InjectMocks private ProcessServiceImpl processService; @Mock @@ -203,19 +148,19 @@ public class ProcessServiceTest { Mockito.when(processDefineMapper.queryByDefineId(100)).thenReturn(processDefinition); Mockito.when(processDefineMapper.queryByCode(10L)).thenReturn(processDefinition); command = processService.createSubProcessCommand(parentInstance, childInstance, instanceMap, task); - Assert.assertEquals(CommandType.START_PROCESS, command.getCommandType()); + Assertions.assertEquals(CommandType.START_PROCESS, command.getCommandType()); // father history: start,start failure; child null == command type: start parentInstance.setCommandType(CommandType.START_FAILURE_TASK_PROCESS); parentInstance.setHistoryCmd("START_PROCESS,START_FAILURE_TASK_PROCESS"); command = processService.createSubProcessCommand(parentInstance, childInstance, instanceMap, task); - Assert.assertEquals(CommandType.START_PROCESS, command.getCommandType()); + Assertions.assertEquals(CommandType.START_PROCESS, command.getCommandType()); // father history: scheduler,start failure; child null == command type: scheduler parentInstance.setCommandType(CommandType.START_FAILURE_TASK_PROCESS); parentInstance.setHistoryCmd("SCHEDULER,START_FAILURE_TASK_PROCESS"); command = processService.createSubProcessCommand(parentInstance, childInstance, instanceMap, task); - Assert.assertEquals(CommandType.SCHEDULER, command.getCommandType()); + Assertions.assertEquals(CommandType.SCHEDULER, command.getCommandType()); // father history: complement,start failure; child null == command type: complement @@ -228,20 +173,20 @@ public class ProcessServiceTest { complementMap.put(Constants.CMDPARAM_COMPLEMENT_DATA_END_DATE, endString); parentInstance.setCommandParam(JSONUtils.toJsonString(complementMap)); command = processService.createSubProcessCommand(parentInstance, childInstance, instanceMap, task); - Assert.assertEquals(CommandType.COMPLEMENT_DATA, command.getCommandType()); + Assertions.assertEquals(CommandType.COMPLEMENT_DATA, command.getCommandType()); JsonNode complementDate = JSONUtils.parseObject(command.getCommandParam()); Date start = DateUtils.stringToDate(complementDate.get(Constants.CMDPARAM_COMPLEMENT_DATA_START_DATE).asText()); Date end = DateUtils.stringToDate(complementDate.get(Constants.CMDPARAM_COMPLEMENT_DATA_END_DATE).asText()); - Assert.assertEquals(startString, DateUtils.dateToString(start)); - Assert.assertEquals(endString, DateUtils.dateToString(end)); + Assertions.assertEquals(startString, DateUtils.dateToString(start)); + Assertions.assertEquals(endString, DateUtils.dateToString(end)); // father history: start,failure,start failure; child not null == command type: start failure childInstance = new ProcessInstance(); parentInstance.setCommandType(CommandType.START_FAILURE_TASK_PROCESS); parentInstance.setHistoryCmd("START_PROCESS,START_FAILURE_TASK_PROCESS"); command = processService.createSubProcessCommand(parentInstance, childInstance, instanceMap, task); - Assert.assertEquals(CommandType.START_FAILURE_TASK_PROCESS, command.getCommandType()); + Assertions.assertEquals(CommandType.START_FAILURE_TASK_PROCESS, command.getCommandType()); } @Test @@ -254,16 +199,16 @@ public class ProcessServiceTest { command.setCommandParam("{\"" + CMD_PARAM_RECOVER_PROCESS_ID_STRING + "\":\"111\"}"); commands.add(command); Mockito.when(commandMapper.selectList(null)).thenReturn(commands); - Assert.assertFalse(processService.verifyIsNeedCreateCommand(command)); + Assertions.assertFalse(processService.verifyIsNeedCreateCommand(command)); Command command1 = new Command(); command1.setCommandType(CommandType.REPEAT_RUNNING); command1.setCommandParam("{\"" + CMD_PARAM_RECOVER_PROCESS_ID_STRING + "\":\"222\"}"); - Assert.assertTrue(processService.verifyIsNeedCreateCommand(command1)); + Assertions.assertTrue(processService.verifyIsNeedCreateCommand(command1)); Command command2 = new Command(); command2.setCommandType(CommandType.PAUSE); - Assert.assertTrue(processService.verifyIsNeedCreateCommand(command2)); + Assertions.assertTrue(processService.verifyIsNeedCreateCommand(command2)); } @Test @@ -308,10 +253,10 @@ public class ProcessServiceTest { + CMD_PARAM_SUB_PROCESS_DEFINE_CODE + "\":\"222\"}"); try { - Assert.assertNull(processService.handleCommand(host, command)); + Assertions.assertNull(processService.handleCommand(host, command)); } catch (IllegalArgumentException illegalArgumentException) { // assert throw illegalArgumentException here since the definition is null - Assert.assertTrue(true); + Assertions.assertTrue(true); } int definitionVersion = 1; @@ -349,7 +294,7 @@ public class ProcessServiceTest { Mockito.when(processDefineLogMapper.queryByDefinitionCodeAndVersion(processInstance.getProcessDefinitionCode(), processInstance.getProcessDefinitionVersion())).thenReturn(new ProcessDefinitionLog(processDefinition)); Mockito.when(processInstanceMapper.queryDetailById(222)).thenReturn(processInstance); - Assert.assertNotNull(processService.handleCommand(host, command1)); + Assertions.assertNotNull(processService.handleCommand(host, command1)); Command command2 = new Command(); command2.setId(2); @@ -359,7 +304,7 @@ public class ProcessServiceTest { command2.setCommandType(CommandType.RECOVER_SUSPENDED_PROCESS); command2.setProcessInstanceId(processInstanceId); Mockito.when(commandMapper.deleteById(2)).thenReturn(1); - Assert.assertNotNull(processService.handleCommand(host, command2)); + Assertions.assertNotNull(processService.handleCommand(host, command2)); Command command3 = new Command(); command3.setId(3); @@ -369,7 +314,7 @@ public class ProcessServiceTest { command3.setCommandParam("{\"WaitingThreadInstanceId\":222}"); command3.setCommandType(CommandType.START_FAILURE_TASK_PROCESS); Mockito.when(commandMapper.deleteById(3)).thenReturn(1); - Assert.assertNotNull(processService.handleCommand(host, command3)); + Assertions.assertNotNull(processService.handleCommand(host, command3)); Command command4 = new Command(); command4.setId(4); @@ -379,7 +324,7 @@ public class ProcessServiceTest { command4.setCommandType(CommandType.REPEAT_RUNNING); command4.setProcessInstanceId(processInstanceId); Mockito.when(commandMapper.deleteById(4)).thenReturn(1); - Assert.assertNotNull(processService.handleCommand(host, command4)); + Assertions.assertNotNull(processService.handleCommand(host, command4)); Command command5 = new Command(); command5.setId(5); @@ -399,7 +344,7 @@ public class ProcessServiceTest { CommandType.START_PROCESS, processInstance.getScheduleTime(), null)).thenReturn("\"testStartParam1\""); ProcessInstance processInstance1 = processService.handleCommand(host, command5); - Assert.assertTrue(processInstance1.getGlobalParams().contains("\"testStartParam1\"")); + Assertions.assertTrue(processInstance1.getGlobalParams().contains("\"testStartParam1\"")); ProcessDefinition processDefinition1 = new ProcessDefinition(); processDefinition1.setId(123); @@ -423,7 +368,7 @@ public class ProcessServiceTest { Mockito.when(processInstanceMapper.queryDetailById(223)).thenReturn(processInstance2); Mockito.when(processDefineMapper.queryByCode(11L)).thenReturn(processDefinition1); Mockito.when(commandMapper.deleteById(1)).thenReturn(1); - Assert.assertNotNull(processService.handleCommand(host, command1)); + Assertions.assertNotNull(processService.handleCommand(host, command1)); Command command6 = new Command(); command6.setId(6); @@ -436,7 +381,7 @@ public class ProcessServiceTest { Mockito.when(processInstanceMapper.updateNextProcessIdById(223, 222)).thenReturn(true); Mockito.when(commandMapper.deleteById(6)).thenReturn(1); ProcessInstance processInstance6 = processService.handleCommand(host, command6); - Assert.assertTrue(processInstance6 != null); + Assertions.assertNotNull(processInstance6); processDefinition1.setExecutionType(ProcessExecutionTypeEnum.SERIAL_DISCARD); Mockito.when(processDefineMapper.queryByCode(11L)).thenReturn(processDefinition1); @@ -456,7 +401,7 @@ public class ProcessServiceTest { Mockito.when(processInstanceMapper.queryByProcessDefineCodeAndProcessDefinitionVersionAndStatusAndNextId(11L, 1, org.apache.dolphinscheduler.service.utils.Constants.RUNNING_PROCESS_STATE, 224)).thenReturn(null); ProcessInstance processInstance8 = processService.handleCommand(host, command7); - Assert.assertTrue(processInstance8 != null); + Assertions.assertNotNull(processInstance8); ProcessDefinition processDefinition2 = new ProcessDefinition(); processDefinition2.setId(123); @@ -481,10 +426,10 @@ public class ProcessServiceTest { Mockito.when(processInstanceMapper.updateById(processInstance)).thenReturn(1); Mockito.when(commandMapper.deleteById(9)).thenReturn(1); ProcessInstance processInstance10 = processService.handleCommand(host, command9); - Assert.assertTrue(processInstance10 != null); + Assertions.assertNotNull(processInstance10); } - @Test(expected = ServiceException.class) + @Test public void testDeleteNotExistCommand() throws CronParseException, CodeGenerateUtils.CodeGenerateException { String host = "127.0.0.1"; int definitionVersion = 1; @@ -522,8 +467,10 @@ public class ProcessServiceTest { processInstance.getProcessDefinitionVersion())).thenReturn(new ProcessDefinitionLog(processDefinition)); Mockito.when(processInstanceMapper.queryDetailById(222)).thenReturn(processInstance); - // will throw exception when command id is 0 and delete fail - processService.handleCommand(host, command1); + Assertions.assertThrows(ServiceException.class, () -> { + // will throw exception when command id is 0 and delete fail + processService.handleCommand(host, command1); + }); } @Test @@ -531,7 +478,7 @@ public class ProcessServiceTest { User user = new User(); user.setId(123); Mockito.when(userMapper.selectById(123)).thenReturn(user); - Assert.assertEquals(user, processService.getUserById(123)); + Assertions.assertEquals(user, processService.getUserById(123)); } @Test @@ -540,7 +487,7 @@ public class ProcessServiceTest { taskInstance.setId(333); taskInstance.setProcessInstanceId(222); Mockito.when(processService.findProcessInstanceById(taskInstance.getProcessInstanceId())).thenReturn(null); - Assert.assertEquals("", processService.formatTaskAppId(taskInstance)); + Assertions.assertEquals("", processService.formatTaskAppId(taskInstance)); ProcessDefinition processDefinition = new ProcessDefinition(); processDefinition.setId(111); @@ -550,7 +497,7 @@ public class ProcessServiceTest { processInstance.setProcessDefinitionCode(1L); Mockito.when(processService.findProcessInstanceById(taskInstance.getProcessInstanceId())) .thenReturn(processInstance); - Assert.assertEquals("", processService.formatTaskAppId(taskInstance)); + Assertions.assertEquals("", processService.formatTaskAppId(taskInstance)); } @Test @@ -584,7 +531,7 @@ public class ProcessServiceTest { List ids = new ArrayList<>(); processService.recurseFindSubProcess(parentProcessDefineCode, ids); - Assert.assertEquals(0, ids.size()); + Assertions.assertEquals(0, ids.size()); } @Test @@ -599,25 +546,25 @@ public class ProcessServiceTest { ProcessDefinitionLog processDefinitionLog = new ProcessDefinitionLog(); processDefinitionLog.setCode(1L); processDefinitionLog.setVersion(2); - Assert.assertEquals(0, processService.switchVersion(processDefinition, processDefinitionLog)); + Assertions.assertEquals(0, processService.switchVersion(processDefinition, processDefinitionLog)); } @Test public void getDqRule() { Mockito.when(dqRuleMapper.selectById(1)).thenReturn(new DqRule()); - Assert.assertNotNull(processService.getDqRule(1)); + Assertions.assertNotNull(processService.getDqRule(1)); } @Test public void getRuleInputEntry() { Mockito.when(dqRuleInputEntryMapper.getRuleInputEntryList(1)).thenReturn(getRuleInputEntryList()); - Assert.assertNotNull(processService.getRuleInputEntry(1)); + Assertions.assertNotNull(processService.getRuleInputEntry(1)); } @Test public void getDqExecuteSql() { Mockito.when(dqRuleExecuteSqlMapper.getExecuteSqlList(1)).thenReturn(getRuleExecuteSqlList()); - Assert.assertNotNull(processService.getDqExecuteSql(1)); + Assertions.assertNotNull(processService.getDqExecuteSql(1)); } private List getRuleInputEntryList() { @@ -733,7 +680,7 @@ public class ProcessServiceTest { Mockito.when(taskDefinitionMapper.queryByCodeList(Collections.singletonList(taskDefinition.getCode()))) .thenReturn(Collections.singletonList(taskDefinition)); int result = processService.saveTaskDefine(operator, projectCode, taskDefinitionLogs, Boolean.TRUE); - Assert.assertEquals(0, result); + Assertions.assertEquals(0, result); } @Test @@ -787,7 +734,7 @@ public class ProcessServiceTest { DAG stringTaskNodeTaskNodeRelationDAG = processService.genDagGraph(processDefinition); - Assert.assertEquals(1, stringTaskNodeTaskNodeRelationDAG.getNodesCount()); + Assertions.assertEquals(1, stringTaskNodeTaskNodeRelationDAG.getNodesCount()); } @Test @@ -799,7 +746,7 @@ public class ProcessServiceTest { int mockResult = 1; Mockito.when(commandMapper.insert(command)).thenReturn(mockResult); int exeMethodResult = processService.createCommand(command); - Assert.assertEquals(mockResult, exeMethodResult); + Assertions.assertEquals(mockResult, exeMethodResult); Mockito.verify(commandMapper, Mockito.times(1)).insert(command); } @@ -823,12 +770,12 @@ public class ProcessServiceTest { // test if input is null ResourceInfo resourceInfoNull = null; ResourceInfo updatedResourceInfo1 = processService.updateResourceInfo(resourceInfoNull); - Assert.assertNull(updatedResourceInfo1); + Assertions.assertNull(updatedResourceInfo1); // test if resource id less than 1 ResourceInfo resourceInfoVoid = new ResourceInfo(); ResourceInfo updatedResourceInfo2 = processService.updateResourceInfo(resourceInfoVoid); - Assert.assertNull(updatedResourceInfo2); + Assertions.assertNull(updatedResourceInfo2); // test normal situation ResourceInfo resourceInfoNormal = new ResourceInfo(); @@ -841,9 +788,9 @@ public class ProcessServiceTest { ResourceInfo updatedResourceInfo3 = processService.updateResourceInfo(resourceInfoNormal); - Assert.assertEquals(1, updatedResourceInfo3.getId().intValue()); - Assert.assertEquals("test.txt", updatedResourceInfo3.getRes()); - Assert.assertEquals("/test.txt", updatedResourceInfo3.getResourceName()); + Assertions.assertEquals(1, updatedResourceInfo3.getId().intValue()); + Assertions.assertEquals("test.txt", updatedResourceInfo3.getRes()); + Assertions.assertEquals("/test.txt", updatedResourceInfo3.getResourceName()); } @@ -852,7 +799,7 @@ public class ProcessServiceTest { Mockito.when(taskGroupQueueMapper.insert(Mockito.any(TaskGroupQueue.class))).thenReturn(1); TaskGroupQueue taskGroupQueue = processService.insertIntoTaskGroupQueue(1, "task name", 1, 1, 1, TaskGroupQueueStatus.WAIT_QUEUE); - Assert.assertNotNull(taskGroupQueue); + Assertions.assertNotNull(taskGroupQueue); } @Test @@ -875,7 +822,7 @@ public class ProcessServiceTest { public void testFindTaskInstanceByIdList() { List emptyList = new ArrayList<>(); Mockito.when(taskInstanceMapper.selectBatchIds(emptyList)).thenReturn(new ArrayList<>()); - Assert.assertEquals(0, processService.findTaskInstanceByIdList(emptyList).size()); + Assertions.assertEquals(0, processService.findTaskInstanceByIdList(emptyList).size()); List idList = Collections.singletonList(1); TaskInstance instance = new TaskInstance(); @@ -884,8 +831,8 @@ public class ProcessServiceTest { Mockito.when(taskInstanceMapper.selectBatchIds(idList)).thenReturn(Collections.singletonList(instance)); List taskInstanceByIdList = processService.findTaskInstanceByIdList(idList); - Assert.assertEquals(1, taskInstanceByIdList.size()); - Assert.assertEquals(instance.getId(), taskInstanceByIdList.get(0).getId()); + Assertions.assertEquals(1, taskInstanceByIdList.size()); + Assertions.assertEquals(instance.getId(), taskInstanceByIdList.get(0).getId()); } @Test @@ -896,7 +843,7 @@ public class ProcessServiceTest { int thisMasterSlot = 2; List commandList = processService.findCommandPageBySlot(pageSize, pageNumber, masterCount, thisMasterSlot); - Assert.assertEquals(0, commandList.size()); + Assertions.assertEquals(0, commandList.size()); } @Test @@ -908,13 +855,13 @@ public class ProcessServiceTest { // find test lastManualProcessInterval ProcessInstance lastManualProcessInterval = processService.findLastManualProcessInterval(definitionCode, dateInterval, testFlag); - Assert.assertEquals(null, lastManualProcessInterval); + Assertions.assertNull(lastManualProcessInterval); // find online lastManualProcessInterval testFlag = 0; lastManualProcessInterval = processService.findLastManualProcessInterval(definitionCode, dateInterval, testFlag); - Assert.assertEquals(null, lastManualProcessInterval); + Assertions.assertNull(lastManualProcessInterval); } @Test @@ -924,13 +871,13 @@ public class ProcessServiceTest { // unbound testDataSourceId Mockito.when(dataSourceMapper.queryTestDataSourceId(any(Integer.class))).thenReturn(null); Integer result = processService.queryTestDataSourceId(onlineDataSourceId); - Assert.assertNull(result); + Assertions.assertNull(result); // bound testDataSourceId Integer testDataSourceId = 2; Mockito.when(dataSourceMapper.queryTestDataSourceId(any(Integer.class))).thenReturn(testDataSourceId); result = processService.queryTestDataSourceId(onlineDataSourceId); - Assert.assertNotNull(result); + Assertions.assertNotNull(result); } private TaskGroupQueue getTaskGroupQueue() { TaskGroupQueue taskGroupQueue = new TaskGroupQueue(); diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/queue/PeerTaskInstancePriorityQueueTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/queue/PeerTaskInstancePriorityQueueTest.java index 0daf8bf66a..3abe0db486 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/queue/PeerTaskInstancePriorityQueueTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/queue/PeerTaskInstancePriorityQueueTest.java @@ -20,12 +20,11 @@ package org.apache.dolphinscheduler.service.queue; import org.apache.dolphinscheduler.common.enums.Priority; import org.apache.dolphinscheduler.dao.entity.TaskInstance; import org.apache.dolphinscheduler.service.exceptions.TaskPriorityQueueException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Test; - public class PeerTaskInstancePriorityQueueTest { @Test @@ -35,9 +34,9 @@ public class PeerTaskInstancePriorityQueueTest { TaskInstance taskInstanceMediumPriority = createTaskInstance("medium", Priority.MEDIUM, 1); queue.put(taskInstanceHigPriority); queue.put(taskInstanceMediumPriority); - Assert.assertEquals(2, queue.size()); - Assert.assertTrue(queue.contains(taskInstanceHigPriority)); - Assert.assertTrue(queue.contains(taskInstanceMediumPriority)); + Assertions.assertEquals(2, queue.size()); + Assertions.assertTrue(queue.contains(taskInstanceHigPriority)); + Assertions.assertTrue(queue.contains(taskInstanceMediumPriority)); } @Test @@ -45,21 +44,23 @@ public class PeerTaskInstancePriorityQueueTest { PeerTaskInstancePriorityQueue queue = getPeerTaskInstancePriorityQueue(); int peekBeforeLength = queue.size(); queue.take(); - Assert.assertTrue(queue.size() < peekBeforeLength); + Assertions.assertTrue(queue.size() < peekBeforeLength); } - @Test(expected = TaskPriorityQueueException.class) + @Test public void poll() throws Exception { PeerTaskInstancePriorityQueue queue = getPeerTaskInstancePriorityQueue(); - queue.poll(1000, TimeUnit.MILLISECONDS); + Assertions.assertThrows(TaskPriorityQueueException.class, () -> { + queue.poll(1000, TimeUnit.MILLISECONDS); + }); } @Test public void peek() throws Exception { PeerTaskInstancePriorityQueue queue = getPeerTaskInstancePriorityQueue(); int peekBeforeLength = queue.size(); - Assert.assertEquals(peekBeforeLength, queue.size()); + Assertions.assertEquals(peekBeforeLength, queue.size()); } @Test @@ -71,7 +72,7 @@ public class PeerTaskInstancePriorityQueueTest { queue.put(taskInstanceHigPriority); TaskInstance taskInstance = queue.peek(); queue.clear(); - Assert.assertEquals(taskInstance.getName(), "high"); + Assertions.assertEquals(taskInstance.getName(), "high"); taskInstanceHigPriority = createTaskInstance("high", Priority.HIGH, 1); taskInstanceMediumPriority = createTaskInstance("medium", Priority.HIGH, 2); @@ -79,7 +80,7 @@ public class PeerTaskInstancePriorityQueueTest { queue.put(taskInstanceHigPriority); taskInstance = queue.peek(); queue.clear(); - Assert.assertEquals(taskInstance.getName(), "medium"); + Assertions.assertEquals(taskInstance.getName(), "medium"); taskInstanceHigPriority = createTaskInstance("high", Priority.HIGH, 1); taskInstanceMediumPriority = createTaskInstance("medium", Priority.MEDIUM, 2); @@ -87,7 +88,7 @@ public class PeerTaskInstancePriorityQueueTest { queue.put(taskInstanceHigPriority); taskInstance = queue.peek(); queue.clear(); - Assert.assertEquals(taskInstance.getName(), "high"); + Assertions.assertEquals(taskInstance.getName(), "high"); taskInstanceHigPriority = createTaskInstance("high", Priority.HIGH, 1); taskInstanceMediumPriority = createTaskInstance("medium", Priority.MEDIUM, 1); @@ -95,13 +96,13 @@ public class PeerTaskInstancePriorityQueueTest { queue.put(taskInstanceHigPriority); taskInstance = queue.peek(); queue.clear(); - Assert.assertEquals(taskInstance.getName(), "high"); + Assertions.assertEquals(taskInstance.getName(), "high"); } @Test public void size() throws Exception { - Assert.assertEquals(2, getPeerTaskInstancePriorityQueue().size()); + Assertions.assertEquals(2, getPeerTaskInstancePriorityQueue().size()); } @Test @@ -109,10 +110,10 @@ public class PeerTaskInstancePriorityQueueTest { PeerTaskInstancePriorityQueue queue = new PeerTaskInstancePriorityQueue(); TaskInstance taskInstanceMediumPriority = createTaskInstance("medium", Priority.MEDIUM, 1); queue.put(taskInstanceMediumPriority); - Assert.assertTrue(queue.contains(taskInstanceMediumPriority)); + Assertions.assertTrue(queue.contains(taskInstanceMediumPriority)); TaskInstance taskInstance2 = createTaskInstance("medium2", Priority.MEDIUM, 1); taskInstance2.setProcessInstanceId(2); - Assert.assertFalse(queue.contains(taskInstance2)); + Assertions.assertFalse(queue.contains(taskInstance2)); } @Test @@ -122,8 +123,8 @@ public class PeerTaskInstancePriorityQueueTest { queue.put(taskInstanceMediumPriority); int peekBeforeLength = queue.size(); queue.remove(taskInstanceMediumPriority); - Assert.assertNotEquals(peekBeforeLength, queue.size()); - Assert.assertFalse(queue.contains(taskInstanceMediumPriority)); + Assertions.assertNotEquals(peekBeforeLength, queue.size()); + Assertions.assertFalse(queue.contains(taskInstanceMediumPriority)); } /** diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/queue/TaskPriorityQueueImplTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/queue/TaskPriorityQueueImplTest.java index c2fb14acfa..a78cc959a0 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/queue/TaskPriorityQueueImplTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/queue/TaskPriorityQueueImplTest.java @@ -18,15 +18,14 @@ package org.apache.dolphinscheduler.service.queue; import org.apache.dolphinscheduler.common.enums.Priority; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; -import org.junit.Assert; -import org.junit.Test; - public class TaskPriorityQueueImplTest { @Test @@ -34,88 +33,88 @@ public class TaskPriorityQueueImplTest { TaskPriority priorityOne = new TaskPriority(1, 0, 0, 0, 1, "default"); TaskPriority priorityTwo = new TaskPriority(2, 0, 0, 0, 1, "default"); TaskPriority priorityThree = new TaskPriority(3, 0, 0, 0, 1, "default"); - List taskPrioritys = Arrays.asList(priorityOne, priorityThree, priorityTwo); - Collections.sort(taskPrioritys); - Assert.assertEquals( + List taskPriorities = Arrays.asList(priorityOne, priorityThree, priorityTwo); + Collections.sort(taskPriorities); + Assertions.assertEquals( Arrays.asList(priorityOne, priorityTwo, priorityThree), - taskPrioritys + taskPriorities ); priorityOne = new TaskPriority(0, 1, 0, 0, 1, "default"); priorityTwo = new TaskPriority(0, 2, 0, 0, 1, "default"); priorityThree = new TaskPriority(0, 3, 0, 0, 1, "default"); - taskPrioritys = Arrays.asList(priorityOne, priorityThree, priorityTwo); - Collections.sort(taskPrioritys); - Assert.assertEquals( + taskPriorities = Arrays.asList(priorityOne, priorityThree, priorityTwo); + Collections.sort(taskPriorities); + Assertions.assertEquals( Arrays.asList(priorityOne, priorityTwo, priorityThree), - taskPrioritys + taskPriorities ); priorityOne = new TaskPriority(0, 0, 1, 0, 1, "default"); priorityTwo = new TaskPriority(0, 0, 2, 0, 1, "default"); priorityThree = new TaskPriority(0, 0, 3, 0, 1, "default"); - taskPrioritys = Arrays.asList(priorityOne, priorityThree, priorityTwo); - Collections.sort(taskPrioritys); - Assert.assertEquals( + taskPriorities = Arrays.asList(priorityOne, priorityThree, priorityTwo); + Collections.sort(taskPriorities); + Assertions.assertEquals( Arrays.asList(priorityOne, priorityTwo, priorityThree), - taskPrioritys + taskPriorities ); priorityOne = new TaskPriority(0, 0, 0, 1, 1, "default"); priorityTwo = new TaskPriority(0, 0, 0, 2, 1, "default"); priorityThree = new TaskPriority(0, 0, 0, 3, 1, "default"); - taskPrioritys = Arrays.asList(priorityOne, priorityThree, priorityTwo); - Collections.sort(taskPrioritys); - Assert.assertEquals( + taskPriorities = Arrays.asList(priorityOne, priorityThree, priorityTwo); + Collections.sort(taskPriorities); + Assertions.assertEquals( Arrays.asList(priorityOne, priorityTwo, priorityThree), - taskPrioritys + taskPriorities ); priorityOne = new TaskPriority(0, 0, 0, 0, 1, "default_1"); priorityTwo = new TaskPriority(0, 0, 0, 0, 1,"default_2"); priorityThree = new TaskPriority(0, 0, 0, 0, 1, "default_3"); - taskPrioritys = Arrays.asList(priorityOne, priorityThree, priorityTwo); - Collections.sort(taskPrioritys); - Assert.assertEquals( + taskPriorities = Arrays.asList(priorityOne, priorityThree, priorityTwo); + Collections.sort(taskPriorities); + Assertions.assertEquals( Arrays.asList(priorityOne, priorityTwo, priorityThree), - taskPrioritys + taskPriorities ); priorityOne = new TaskPriority(0, 0, 0, 0, 2, "default_1"); priorityTwo = new TaskPriority(0, 0, 0, 0, 1,"default_2"); priorityThree = new TaskPriority(0, 0, 0, 0, 3, "default_3"); - taskPrioritys = Arrays.asList(priorityOne, priorityThree, priorityTwo); - Collections.sort(taskPrioritys); - Assert.assertEquals( + taskPriorities = Arrays.asList(priorityOne, priorityThree, priorityTwo); + Collections.sort(taskPriorities); + Assertions.assertEquals( Arrays.asList(priorityThree, priorityOne, priorityTwo), - taskPrioritys + taskPriorities ); priorityOne = new TaskPriority(0, 0, 0, 0, 1, "default_1"); priorityTwo = new TaskPriority(0, 0, 0, 0, 1,"default_2"); priorityThree = new TaskPriority(0, 0, 0, 0, 3, "default_3"); - taskPrioritys = Arrays.asList(priorityOne, priorityThree, priorityTwo); - Collections.sort(taskPrioritys); - Assert.assertEquals( + taskPriorities = Arrays.asList(priorityOne, priorityThree, priorityTwo); + Collections.sort(taskPriorities); + Assertions.assertEquals( Arrays.asList(priorityThree, priorityOne, priorityTwo), - taskPrioritys + taskPriorities ); priorityTwo = new TaskPriority(0, 0, 0, 0, 1,"default_1"); priorityOne = new TaskPriority(0, 0, 0, 0, 1, "default_1"); priorityThree = new TaskPriority(0, 0, 0, 0, 3, "default_1"); - taskPrioritys = Arrays.asList(priorityTwo, priorityOne, priorityThree); - Collections.sort(taskPrioritys); - Assert.assertEquals( + taskPriorities = Arrays.asList(priorityTwo, priorityOne, priorityThree); + Collections.sort(taskPriorities); + Assertions.assertEquals( Arrays.asList(priorityThree, priorityTwo, priorityOne), - taskPrioritys + taskPriorities ); } @Test public void put() throws Exception { TaskPriorityQueue queue = getPriorityQueue(); - Assert.assertEquals(2, queue.size()); + Assertions.assertEquals(2, queue.size()); } @Test @@ -123,7 +122,7 @@ public class TaskPriorityQueueImplTest { TaskPriorityQueue queue = getPriorityQueue(); int peekBeforeLength = queue.size(); queue.take(); - Assert.assertTrue(queue.size() < peekBeforeLength); + Assertions.assertTrue(queue.size() < peekBeforeLength); } @Test @@ -132,13 +131,13 @@ public class TaskPriorityQueueImplTest { int peekBeforeLength = queue.size(); queue.poll(1000, TimeUnit.MILLISECONDS); queue.poll(1000, TimeUnit.MILLISECONDS); - Assert.assertTrue(queue.size() == 0); + Assertions.assertEquals(0, queue.size()); queue.poll(1000, TimeUnit.MILLISECONDS); } @Test public void size() throws Exception { - Assert.assertTrue(getPriorityQueue().size() == 2); + Assertions.assertEquals(2, getPriorityQueue().size()); } /** diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/storage/impl/HadoopUtilsTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/storage/impl/HadoopUtilsTest.java index 5bf5c55b83..d9d70172c5 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/storage/impl/HadoopUtilsTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/storage/impl/HadoopUtilsTest.java @@ -19,20 +19,19 @@ package org.apache.dolphinscheduler.service.storage.impl; import org.apache.dolphinscheduler.common.utils.HttpUtils; import org.apache.dolphinscheduler.spi.enums.ResourceType; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * hadoop utils test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class HadoopUtilsTest { private static final Logger logger = LoggerFactory.getLogger(HadoopUtilsTest.class); @@ -40,25 +39,25 @@ public class HadoopUtilsTest { @Test public void getHdfsTenantDir() { logger.info(HadoopUtils.getHdfsTenantDir("1234")); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test public void getHdfsUdfFileName() { logger.info(HadoopUtils.getHdfsUdfFileName("admin", "file_name")); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test public void getHdfsResourceFileName() { logger.info(HadoopUtils.getHdfsResourceFileName("admin", "file_name")); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test public void getHdfsFileName() { logger.info(HadoopUtils.getHdfsFileName(ResourceType.FILE, "admin", "file_name")); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test @@ -67,7 +66,7 @@ public class HadoopUtilsTest { mockedHttpUtils.when(() -> HttpUtils.get("http://ds1:8088/ws/v1/cluster/info")) .thenReturn("{\"clusterInfo\":{\"state\":\"STARTED\",\"haState\":\"ACTIVE\"}}"); logger.info(HadoopUtils.getAppAddress("http://ds1:8088/ws/v1/cluster/apps/%s", "ds1,ds2")); - Assert.assertTrue(true); + Assertions.assertTrue(true); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/storage/impl/OssOperatorTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/storage/impl/OssOperatorTest.java index f9132b2732..384a0139d1 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/storage/impl/OssOperatorTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/storage/impl/OssOperatorTest.java @@ -17,33 +17,24 @@ package org.apache.dolphinscheduler.service.storage.impl; -import static org.apache.dolphinscheduler.common.Constants.FOLDER_SEPARATOR; -import static org.apache.dolphinscheduler.common.Constants.FORMAT_S_S; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import org.apache.dolphinscheduler.service.storage.impl.OssOperator; +import com.aliyun.oss.OSS; import org.apache.dolphinscheduler.spi.enums.ResourceType; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import java.io.IOException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import com.aliyun.oss.OSS; +import static org.apache.dolphinscheduler.common.Constants.FOLDER_SEPARATOR; +import static org.apache.dolphinscheduler.common.Constants.FORMAT_S_S; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class OssOperatorTest { private static final String ACCESS_KEY_ID_MOCK = "ACCESS_KEY_ID_MOCK"; @@ -61,7 +52,7 @@ public class OssOperatorTest { private OssOperator ossOperator; - @Before + @BeforeEach public void setUp() throws Exception { ossOperator = spy(new OssOperator()); doReturn(ACCESS_KEY_ID_MOCK).when(ossOperator) @@ -81,10 +72,10 @@ public class OssOperatorTest { @Test public void initOssOperator() { verify(ossOperator, times(1)).buildOssClient(); - Assert.assertEquals(ACCESS_KEY_ID_MOCK, ossOperator.getAccessKeyId()); - Assert.assertEquals(ACCESS_KEY_SECRET_MOCK, ossOperator.getAccessKeySecret()); - Assert.assertEquals(REGION_MOCK, ossOperator.getRegion()); - Assert.assertEquals(BUCKET_NAME_MOCK, ossOperator.getBucketName()); + Assertions.assertEquals(ACCESS_KEY_ID_MOCK, ossOperator.getAccessKeyId()); + Assertions.assertEquals(ACCESS_KEY_SECRET_MOCK, ossOperator.getAccessKeySecret()); + Assertions.assertEquals(REGION_MOCK, ossOperator.getRegion()); + Assertions.assertEquals(BUCKET_NAME_MOCK, ossOperator.getBucketName()); } @Test @@ -107,14 +98,14 @@ public class OssOperatorTest { public void getResDir() { final String expectedResourceDir = String.format("dolphinscheduler/%s/resources/", TENANT_CODE_MOCK); final String dir = ossOperator.getResDir(TENANT_CODE_MOCK); - Assert.assertEquals(expectedResourceDir, dir); + Assertions.assertEquals(expectedResourceDir, dir); } @Test public void getUdfDir() { final String expectedUdfDir = String.format("dolphinscheduler/%s/udfs/", TENANT_CODE_MOCK); final String dir = ossOperator.getUdfDir(TENANT_CODE_MOCK); - Assert.assertEquals(expectedUdfDir, dir); + Assertions.assertEquals(expectedUdfDir, dir); } @Test @@ -127,10 +118,10 @@ public class OssOperatorTest { verify(ossClientMock, times(1)).doesObjectExist(BUCKET_NAME_MOCK, key); } catch (IOException e) { - fail("test failed due to unexpected IO exception"); + Assertions.fail("test failed due to unexpected IO exception"); } - Assert.assertEquals(true, isSuccess); + Assertions.assertTrue(isSuccess); } @Test @@ -145,10 +136,10 @@ public class OssOperatorTest { verify(ossOperator, times(1)).createOssPrefix(BUCKET_NAME_MOCK, key); } catch (IOException e) { - fail("test failed due to unexpected IO exception"); + Assertions.fail("test failed due to unexpected IO exception"); } - Assert.assertEquals(true, isSuccess); + Assertions.assertTrue(isSuccess); } @Test @@ -156,7 +147,7 @@ public class OssOperatorTest { final String expectedResourceFileName = String.format("dolphinscheduler/%s/resources/%s", TENANT_CODE_MOCK, FILE_NAME_MOCK); final String resourceFileName = ossOperator.getResourceFileName(TENANT_CODE_MOCK, FILE_NAME_MOCK); - assertEquals(expectedResourceFileName, resourceFileName); + Assertions.assertEquals(expectedResourceFileName, resourceFileName); } @Test @@ -164,7 +155,7 @@ public class OssOperatorTest { final String expectedFileName = String.format("dolphinscheduler/%s/resources/%s", TENANT_CODE_MOCK, FILE_NAME_MOCK); final String fileName = ossOperator.getFileName(ResourceType.FILE, TENANT_CODE_MOCK, FILE_NAME_MOCK); - assertEquals(expectedFileName, fileName); + Assertions.assertEquals(expectedFileName, fileName); } @Test @@ -174,10 +165,10 @@ public class OssOperatorTest { try { doesExist = ossOperator.exists(TENANT_CODE_MOCK, FILE_NAME_MOCK); } catch (IOException e) { - fail("unexpected IO exception in unit test"); + Assertions.fail("unexpected IO exception in unit test"); } - Assert.assertEquals(true, doesExist); + Assertions.assertTrue(doesExist); verify(ossClientMock, times(1)).doesObjectExist(BUCKET_NAME_MOCK, FILE_NAME_MOCK); } @@ -188,10 +179,10 @@ public class OssOperatorTest { try { isDeleted = ossOperator.delete(TENANT_CODE_MOCK, FILE_NAME_MOCK, true); } catch (IOException e) { - fail("unexpected IO exception in unit test"); + Assertions.fail("unexpected IO exception in unit test"); } - Assert.assertEquals(true, isDeleted); + Assertions.assertTrue(isDeleted); verify(ossClientMock, times(1)).deleteObject(anyString(), anyString()); } @@ -203,10 +194,10 @@ public class OssOperatorTest { try { isSuccess = ossOperator.copy(FILE_PATH_MOCK, FILE_PATH_MOCK, false, false); } catch (IOException e) { - fail("unexpected IO exception in unit test"); + Assertions.fail("unexpected IO exception in unit test"); } - Assert.assertEquals(true, isSuccess); + Assertions.assertTrue(isSuccess); verify(ossClientMock, times(1)).copyObject(anyString(), anyString(), anyString(), anyString()); verify(ossClientMock, times(1)).deleteObject(anyString(), anyString()); } @@ -217,7 +208,7 @@ public class OssOperatorTest { try { ossOperator.deleteTenant(TENANT_CODE_MOCK); } catch (Exception e) { - fail("unexpected exception caught in unit test"); + Assertions.fail("unexpected exception caught in unit test"); } verify(ossOperator, times(1)).deleteTenantCode(anyString()); @@ -227,14 +218,14 @@ public class OssOperatorTest { public void getOssResDir() { final String expectedOssResDir = String.format("dolphinscheduler/%s/resources", TENANT_CODE_MOCK); final String ossResDir = ossOperator.getOssResDir(TENANT_CODE_MOCK); - Assert.assertEquals(expectedOssResDir, ossResDir); + Assertions.assertEquals(expectedOssResDir, ossResDir); } @Test public void getOssUdfDir() { final String expectedOssUdfDir = String.format("dolphinscheduler/%s/udfs", TENANT_CODE_MOCK); final String ossUdfDir = ossOperator.getOssUdfDir(TENANT_CODE_MOCK); - Assert.assertEquals(expectedOssUdfDir, ossUdfDir); + Assertions.assertEquals(expectedOssUdfDir, ossUdfDir); } @Test @@ -242,7 +233,7 @@ public class OssOperatorTest { final String expectedOssTenantDir = String.format(FORMAT_S_S, DIR_MOCK, TENANT_CODE_MOCK); doReturn(DIR_MOCK).when(ossOperator).getOssDataBasePath(); final String ossTenantDir = ossOperator.getOssTenantDir(TENANT_CODE_MOCK); - Assert.assertEquals(expectedOssTenantDir, ossTenantDir); + Assertions.assertEquals(expectedOssTenantDir, ossTenantDir); } @Test diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/CommonUtilsTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/CommonUtilsTest.java index 3c93031883..98ca251fd6 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/CommonUtilsTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/CommonUtilsTest.java @@ -19,21 +19,20 @@ package org.apache.dolphinscheduler.service.utils; import org.apache.dolphinscheduler.common.utils.FileUtils; import org.apache.dolphinscheduler.service.storage.impl.HadoopUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.net.InetAddress; import java.net.UnknownHostException; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.junit.MockitoJUnitRunner; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * configuration test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class CommonUtilsTest { private static final Logger logger = LoggerFactory.getLogger(CommonUtilsTest.class); @@ -42,37 +41,37 @@ public class CommonUtilsTest { public void getSystemEnvPath() { String envPath; envPath = CommonUtils.getSystemEnvPath(); - Assert.assertEquals("/etc/profile", envPath); + Assertions.assertEquals("/etc/profile", envPath); } @Test public void isDevelopMode() { logger.info("develop mode: {}", CommonUtils.isDevelopMode()); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test public void getHdfsDataBasePath() { logger.info(HadoopUtils.getHdfsDataBasePath()); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test public void getDownloadFilename() { logger.info(FileUtils.getDownloadFilename("a.txt")); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test public void getUploadFilename() { logger.info(FileUtils.getUploadFilename("1234", "a.txt")); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test public void getHdfsDir() { logger.info(HadoopUtils.getHdfsResDir("1234")); - Assert.assertTrue(true); + Assertions.assertTrue(true); } @Test @@ -84,7 +83,7 @@ public class CommonUtilsTest { } catch (UnknownHostException e) { e.printStackTrace(); } - Assert.assertTrue(true); + Assertions.assertTrue(true); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/LogUtilsTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/LogUtilsTest.java index c0a1c70a44..4635e9b4ef 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/LogUtilsTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/LogUtilsTest.java @@ -17,26 +17,24 @@ package org.apache.dolphinscheduler.service.utils; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.sift.SiftingAppender; import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.utils.DateUtils; import org.apache.dolphinscheduler.plugin.task.api.TaskExecutionContext; import org.apache.dolphinscheduler.service.log.TaskLogDiscriminator; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.slf4j.LoggerFactory; - -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.sift.SiftingAppender; - -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class LogUtilsTest { @Test @@ -50,7 +48,7 @@ public class LogUtilsTest { taskExecutionContext.setFirstSubmitTime(firstSubmitTime.getTime()); Logger rootLogger = (Logger) LoggerFactory.getILoggerFactory().getLogger("ROOT"); - Assert.assertNotNull(rootLogger); + Assertions.assertNotNull(rootLogger); SiftingAppender appender = Mockito.mock(SiftingAppender.class); // it's a trick to mock logger.getAppend("TASKLOGFILE") @@ -67,7 +65,7 @@ public class LogUtilsTest { .resolve(logBase) .resolve(DateUtils.format(firstSubmitTime, Constants.YYYYMMDD, null)) .resolve("1_1-100-1000.log"); - Assert.assertEquals(logPath.toString(), LogUtils.getTaskLogPath(taskExecutionContext)); + Assertions.assertEquals(logPath.toString(), LogUtils.getTaskLogPath(taskExecutionContext)); } } diff --git a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/ProcessUtilsTest.java b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/ProcessUtilsTest.java index dba655fb36..bec60332da 100644 --- a/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/ProcessUtilsTest.java +++ b/dolphinscheduler-service/src/test/java/org/apache/dolphinscheduler/service/utils/ProcessUtilsTest.java @@ -17,34 +17,33 @@ package org.apache.dolphinscheduler.service.utils; -import static org.mockito.ArgumentMatchers.anyString; - import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.utils.OSUtils; import org.apache.dolphinscheduler.common.utils.PropertyUtils; import org.apache.dolphinscheduler.plugin.task.api.enums.TaskExecutionStatus; import org.apache.dolphinscheduler.service.storage.impl.HadoopUtils; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@RunWith(MockitoJUnitRunner.class) +import java.util.ArrayList; +import java.util.List; + +import static org.mockito.ArgumentMatchers.anyString; + +@ExtendWith(MockitoExtension.class) public class ProcessUtilsTest { private static final Logger logger = LoggerFactory.getLogger(ProcessUtils.class); - @Before + @BeforeEach public void setUp() { MockitoAnnotations.initMocks(this); } @@ -56,7 +55,7 @@ public class ProcessUtilsTest { try (MockedStatic mockedStaticOSUtils = Mockito.mockStatic(OSUtils.class)) { mockedStaticOSUtils.when(() -> OSUtils.exeCmd(anyString())).thenReturn(null); String pidList = ProcessUtils.getPidsStr(processId); - Assert.assertEquals("", pidList); + Assertions.assertEquals("", pidList); } } @@ -72,11 +71,11 @@ public class ProcessUtilsTest { .thenReturn("/etc/krb5.keytab"); mockedStaticPropertyUtils.when(() -> PropertyUtils.getString(Constants.LOGIN_USER_KEY_TAB_USERNAME)) .thenReturn("test@DS.COM"); - Assert.assertNotEquals("", ProcessUtils.getKerberosInitCommand()); + Assertions.assertNotEquals("", ProcessUtils.getKerberosInitCommand()); mockedStaticPropertyUtils .when(() -> PropertyUtils.getBoolean(Constants.HADOOP_SECURITY_AUTHENTICATION_STARTUP_STATE, false)) .thenReturn(false); - Assert.assertEquals("", ProcessUtils.getKerberosInitCommand()); + Assertions.assertEquals("", ProcessUtils.getKerberosInitCommand()); } } @@ -100,7 +99,7 @@ public class ProcessUtilsTest { ProcessUtils.cancelApplication(appIds, logger, tenantCode, executePath); } - Assert.assertNotNull(appIds); + Assertions.assertNotNull(appIds); } } } diff --git a/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/params/PluginParamsTransferTest.java b/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/params/PluginParamsTransferTest.java index c9cbda319f..1bc3c3157a 100644 --- a/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/params/PluginParamsTransferTest.java +++ b/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/params/PluginParamsTransferTest.java @@ -23,25 +23,24 @@ import org.apache.dolphinscheduler.spi.params.base.PluginParams; import org.apache.dolphinscheduler.spi.params.base.Validate; import org.apache.dolphinscheduler.spi.params.input.InputParam; import org.apache.dolphinscheduler.spi.params.radio.RadioParam; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - /** * PluginParamsTransfer Tester. */ public class PluginParamsTransferTest { - @Before + @BeforeEach public void before() throws Exception { } - @After + @AfterEach public void after() throws Exception { } @@ -178,7 +177,7 @@ public class PluginParamsTransferTest { + ",\"disabled\":false},{\"label\":\"text\",\"value\":\"text\",\"disabled\":false},{\"label\"" + ":\"attachment\",\"value\":\"attachment\",\"disabled\":false},{\"label\":\"tableattachment\"" + ",\"value\":\"tableattachment\",\"disabled\":false}]}]"; - Assert.assertEquals(paramsJsonAssert, paramsJson); + Assertions.assertEquals(paramsJsonAssert, paramsJson); } @Test @@ -213,10 +212,10 @@ public class PluginParamsTransferTest { + "{\"label\":\"attachment\",\"value\":\"attachment\",\"disabled\":false},{\"label\":\"tableattachment\",\"value\":\"tableattachment\",\"disabled\":false}]}]"; List pluginParams = PluginParamsTransfer.transferJsonToParamsList(paramsJsonAssert); String[] results = new String[]{"v1", "v2", "v3", "v4", "v5", "true", "v6", "v7", "false", "false", "*", "table", "v1"}; - Assert.assertEquals(12, pluginParams.size()); + Assertions.assertEquals(12, pluginParams.size()); for (int i = 0; i < pluginParams.size(); i++) { PluginParams param = pluginParams.get(i); - Assert.assertEquals(param.getValue().toString(), results[i]); + Assertions.assertEquals(param.getValue().toString(), results[i]); } } } diff --git a/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/plugin/PrioritySPIFactoryTest.java b/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/plugin/PrioritySPIFactoryTest.java index 4ed3519a6d..71d3b8c868 100644 --- a/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/plugin/PrioritySPIFactoryTest.java +++ b/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/plugin/PrioritySPIFactoryTest.java @@ -18,8 +18,8 @@ package org.apache.dolphinscheduler.spi.plugin; import com.google.auto.service.AutoService; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.util.Map; @@ -29,14 +29,14 @@ public class PrioritySPIFactoryTest { public void loadHighPriority() { PrioritySPIFactory factory = new PrioritySPIFactory<>(LoadHighPriorityConflictTestSPI.class); Map spiMap = factory.getSPIMap(); - Assert.assertEquals(1, spiMap.get("A").getIdentify().getPriority()); + Assertions.assertEquals(1, spiMap.get("A").getIdentify().getPriority()); } - @Test(expected = IllegalArgumentException.class) + @Test public void throwExceptionWhenPriorityIsSame() { - PrioritySPIFactory factory = new PrioritySPIFactory<>(ThrowExceptionConflictTestSPI.class); - Map spiMap = factory.getSPIMap(); - Assert.assertEquals(0, spiMap.get("B").getIdentify().getPriority()); + Assertions.assertThrows(IllegalArgumentException.class, () -> { + new PrioritySPIFactory<>(ThrowExceptionConflictTestSPI.class); + }); } diff --git a/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/utils/JSONUtilsTest.java b/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/utils/JSONUtilsTest.java index fd9c75ee80..b06e3a3237 100644 --- a/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/utils/JSONUtilsTest.java +++ b/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/utils/JSONUtilsTest.java @@ -21,18 +21,12 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import java.time.LocalDateTime; import java.time.ZoneId; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; +import java.util.*; public class JSONUtilsTest { @@ -45,7 +39,7 @@ public class JSONUtilsTest { objectNode.put("a", "b"); objectNode.put("b", "d"); String s = JSONUtils.toJsonString(objectNode); - Assert.assertEquals(s, jsonStr); + Assertions.assertEquals(s, jsonStr); } @Test @@ -54,8 +48,8 @@ public class JSONUtilsTest { String jsonStr = "{\"id\":\"1001\",\"name\":\"Jobs\"}"; Map models = JSONUtils.toMap(jsonStr); - Assert.assertEquals("1001", models.get("id")); - Assert.assertEquals("Jobs", models.get("name")); + Assertions.assertEquals("1001", models.get("id")); + Assertions.assertEquals("Jobs", models.get("name")); } @@ -67,12 +61,12 @@ public class JSONUtilsTest { List maps = JSONUtils.toList(str, LinkedHashMap.class); - Assert.assertEquals(1, maps.size()); - Assert.assertEquals("mysql200", maps.get(0).get("mysql service name")); - Assert.assertEquals("192.168.xx.xx", maps.get(0).get("mysql address")); - Assert.assertEquals("3306", maps.get(0).get("port")); - Assert.assertEquals("80", maps.get(0).get("no index of number")); - Assert.assertEquals("190", maps.get(0).get("database client connections")); + Assertions.assertEquals(1, maps.size()); + Assertions.assertEquals("mysql200", maps.get(0).get("mysql service name")); + Assertions.assertEquals("192.168.xx.xx", maps.get(0).get("mysql address")); + Assertions.assertEquals("3306", maps.get(0).get("port")); + Assertions.assertEquals("80", maps.get(0).get("no index of number")); + Assertions.assertEquals("190", maps.get(0).get("database client connections")); } public String list2String() { @@ -92,8 +86,8 @@ public class JSONUtilsTest { @Test public void testParseObject() { - Assert.assertNull(JSONUtils.parseObject("")); - Assert.assertNull(JSONUtils.parseObject("foo", String.class)); + Assertions.assertNull(JSONUtils.parseObject("")); + Assertions.assertNull(JSONUtils.parseObject("foo", String.class)); } @@ -102,18 +96,18 @@ public class JSONUtilsTest { String str = "foo"; byte[] serializeByte = JSONUtils.toJsonByteArray(str); String deserialize = JSONUtils.parseObject(serializeByte, String.class); - Assert.assertEquals(str, deserialize); + Assertions.assertEquals(str, deserialize); str = null; serializeByte = JSONUtils.toJsonByteArray(str); deserialize = JSONUtils.parseObject(serializeByte, String.class); - Assert.assertNull(deserialize); + Assertions.assertNull(deserialize); } @Test public void testToList() { - Assert.assertEquals(new ArrayList(), + Assertions.assertEquals(new ArrayList(), JSONUtils.toList("A1B2C3", null)); - Assert.assertEquals(new ArrayList(), + Assertions.assertEquals(new ArrayList(), JSONUtils.toList("", null)); } @@ -122,18 +116,18 @@ public class JSONUtilsTest { Map map = new HashMap<>(); map.put("foo", "bar"); - Assert.assertTrue(map.equals(JSONUtils.toMap( - "{\n" + "\"foo\": \"bar\"\n" + "}"))); + Assertions.assertEquals(map, JSONUtils.toMap( + "{\n" + "\"foo\": \"bar\"\n" + "}")); - Assert.assertFalse(map.equals(JSONUtils.toMap( - "{\n" + "\"bar\": \"foo\"\n" + "}"))); + Assertions.assertNotEquals(map, JSONUtils.toMap( + "{\n" + "\"bar\": \"foo\"\n" + "}")); - Assert.assertNull(JSONUtils.toMap("3")); - Assert.assertNull(JSONUtils.toMap(null)); + Assertions.assertNull(JSONUtils.toMap("3")); + Assertions.assertNull(JSONUtils.toMap(null)); String str = "{\"resourceList\":[],\"localParams\":[],\"rawScript\":\"#!/bin/bash\\necho \\\"shell-1\\\"\"}"; Map m = JSONUtils.toMap(str); - Assert.assertNotNull(m); + Assertions.assertNotNull(m); } @Test @@ -141,12 +135,12 @@ public class JSONUtilsTest { Map map = new HashMap<>(); map.put("foo", "bar"); - Assert.assertEquals("{\"foo\":\"bar\"}", + Assertions.assertEquals("{\"foo\":\"bar\"}", JSONUtils.toJsonString(map)); - Assert.assertEquals(String.valueOf((Object) null), + Assertions.assertEquals(String.valueOf((Object) null), JSONUtils.toJsonString(null)); - Assert.assertEquals("{\"foo\":\"bar\"}", + Assertions.assertEquals("{\"foo\":\"bar\"}", JSONUtils.toJsonString(map, SerializationFeature.WRITE_NULL_MAP_VALUES)); } @@ -155,13 +149,13 @@ public class JSONUtilsTest { String str = "{\"color\":\"yellow\",\"type\":\"renault\"}"; ObjectNode node = JSONUtils.parseObject(str); - Assert.assertEquals("yellow", node.path("color").asText()); + Assertions.assertEquals("yellow", node.path("color").asText()); node.put("price", 100); - Assert.assertEquals(100, node.path("price").asInt()); + Assertions.assertEquals(100, node.path("price").asInt()); node.put("color", "red"); - Assert.assertEquals("red", node.path("color").asText()); + Assertions.assertEquals("red", node.path("color").asText()); } @Test @@ -169,7 +163,7 @@ public class JSONUtilsTest { String str = "[{\"color\":\"yellow\",\"type\":\"renault\"}]"; ArrayNode node = JSONUtils.parseArray(str); - Assert.assertEquals("yellow", node.path(0).path("color").asText()); + Assertions.assertEquals("yellow", node.path(0).path("color").asText()); } @Test @@ -179,7 +173,7 @@ public class JSONUtilsTest { Date date = DateUtils.stringToDate(time); LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); String json = JSONUtils.toJsonString(localDateTime); - Assert.assertEquals("\"" + time + "\"", json); + Assertions.assertEquals("\"" + time + "\"", json); } @Test @@ -189,9 +183,9 @@ public class JSONUtilsTest { Date date = DateUtils.stringToDate(time); LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); List timeList = JSONUtils.parseObject("[\"2022-02-22 13:38:24\"]", new TypeReference>(){}); - Assert.assertNotNull(timeList); - Assert.assertEquals(1, timeList.size()); - Assert.assertEquals(localDateTime, timeList.get(0)); + Assertions.assertNotNull(timeList); + Assertions.assertEquals(1, timeList.size()); + Assertions.assertEquals(localDateTime, timeList.get(0)); } } diff --git a/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/utils/StringUtilsTest.java b/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/utils/StringUtilsTest.java index 45e9e35f49..28e457f70a 100644 --- a/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/utils/StringUtilsTest.java +++ b/dolphinscheduler-spi/src/test/java/org/apache/dolphinscheduler/spi/utils/StringUtilsTest.java @@ -17,75 +17,72 @@ package org.apache.dolphinscheduler.spi.utils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import java.util.ArrayList; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class StringUtilsTest { @Test public void testIsEmpty() { - assertTrue(StringUtils.isEmpty("")); + Assertions.assertTrue(StringUtils.isEmpty("")); } @Test public void testIsEmpty2() { - assertFalse(StringUtils.isEmpty("123")); + Assertions.assertFalse(StringUtils.isEmpty("123")); } @Test public void testIsNotEmpty() { - assertTrue(StringUtils.isNotEmpty("cs")); + Assertions.assertTrue(StringUtils.isNotEmpty("cs")); } @Test public void testIsNotEmpty2() { - assertFalse(StringUtils.isNotEmpty("")); + Assertions.assertFalse(StringUtils.isNotEmpty("")); } @Test public void testIsBlank() { - assertTrue(StringUtils.isBlank("")); + Assertions.assertTrue(StringUtils.isBlank("")); } @Test public void testIsBlank2() { - assertFalse(StringUtils.isBlank("123")); + Assertions.assertFalse(StringUtils.isBlank("123")); } @Test public void testIsNotBlank() { - assertTrue(StringUtils.isNotBlank("cs")); + Assertions.assertTrue(StringUtils.isNotBlank("cs")); } @Test public void testIsNotBlank2() { - assertFalse(StringUtils.isNotBlank("")); + Assertions.assertFalse(StringUtils.isNotBlank("")); } @Test public void testTrim() { - assertEquals("result", StringUtils.trim(" result ")); + Assertions.assertEquals("result", StringUtils.trim(" result ")); } @Test public void testTrim2() { - assertEquals("", StringUtils.trim("")); + Assertions.assertEquals("", StringUtils.trim("")); } @Test public void testEqualsIgnoreCase() { - assertTrue(StringUtils.equalsIgnoreCase("Str1", "str1")); + Assertions.assertTrue(StringUtils.equalsIgnoreCase("Str1", "str1")); } @Test public void testEqualsIgnoreCase2() { - assertFalse(StringUtils.equalsIgnoreCase("str1", null)); + Assertions.assertFalse(StringUtils.equalsIgnoreCase("str1", null)); } @Test @@ -99,16 +96,16 @@ public class StringUtilsTest { final String result = StringUtils.join(collection, "_"); // Verify the results - assertEquals("1_2", result); + Assertions.assertEquals("1_2", result); } @Test public void testEscapeJava() { - assertEquals("str", StringUtils.escapeJava("str")); + Assertions.assertEquals("str", StringUtils.escapeJava("str")); } @Test public void testReplaceDoubleBrackets() { - assertEquals("{ {a} }", StringUtils.replaceDoubleBrackets("{{a}}")); + Assertions.assertEquals("{ {a} }", StringUtils.replaceDoubleBrackets("{{a}}")); } }