diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkAlertChannelFactoryTest.java index ea1cd1a0b9..8341a88b59 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkAlertChannelFactoryTest.java @@ -23,22 +23,23 @@ import org.apache.dolphinscheduler.spi.utils.JSONUtils; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class DingTalkAlertChannelFactoryTest { + @Test public void testGetParams() { DingTalkAlertChannelFactory dingTalkAlertChannelFactory = new DingTalkAlertChannelFactory(); List params = dingTalkAlertChannelFactory.params(); JSONUtils.toJsonString(params); - Assert.assertEquals(12, params.size()); + Assertions.assertEquals(12, params.size()); } @Test public void testCreate() { DingTalkAlertChannelFactory dingTalkAlertChannelFactory = new DingTalkAlertChannelFactory(); AlertChannel alertChannel = dingTalkAlertChannelFactory.create(); - Assert.assertNotNull(alertChannel); + Assertions.assertNotNull(alertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkSenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkSenderTest.java index 791a96f2f5..7a8df0549c 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkSenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkSenderTest.java @@ -22,20 +22,21 @@ import org.apache.dolphinscheduler.alert.api.AlertResult; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class DingTalkSenderTest { private static final Map dingTalkConfig = new HashMap<>(); - @Before + @BeforeEach public void initDingTalkConfig() { dingTalkConfig.put(DingTalkParamsConstants.NAME_DING_TALK_KEYWORD, "keyword"); dingTalkConfig.put(DingTalkParamsConstants.NAME_DING_TALK_WEB_HOOK, "url"); - dingTalkConfig.put(DingTalkParamsConstants.NAME_DING_TALK_MSG_TYPE, DingTalkParamsConstants.DING_TALK_MSG_TYPE_MARKDOWN); + dingTalkConfig.put(DingTalkParamsConstants.NAME_DING_TALK_MSG_TYPE, + DingTalkParamsConstants.DING_TALK_MSG_TYPE_MARKDOWN); dingTalkConfig.put(DingTalkParamsConstants.NAME_DING_TALK_PROXY_ENABLE, "false"); dingTalkConfig.put(DingTalkParamsConstants.NAME_DING_TALK_PASSWORD, "password"); @@ -50,7 +51,7 @@ public class DingTalkSenderTest { dingTalkConfig.put(DingTalkParamsConstants.NAME_DING_TALK_PROXY_ENABLE, "true"); dingTalkSender = new DingTalkSender(dingTalkConfig); AlertResult alertResult = dingTalkSender.sendDingTalkMsg("title", "content test"); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertEquals("false", alertResult.getStatus()); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelFactoryTest.java index 5bb7c1d504..64edc5f0c5 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelFactoryTest.java @@ -22,22 +22,23 @@ import org.apache.dolphinscheduler.spi.params.base.PluginParams; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class EmailAlertChannelFactoryTest { + @Test public void testGetParams() { EmailAlertChannelFactory emailAlertChannelFactory = new EmailAlertChannelFactory(); List params = emailAlertChannelFactory.params(); - Assert.assertEquals(12, params.size()); + Assertions.assertEquals(12, params.size()); } @Test public void testCreate() { EmailAlertChannelFactory emailAlertChannelFactory = new EmailAlertChannelFactory(); AlertChannel alertChannel = emailAlertChannelFactory.create(); - Assert.assertNotNull(alertChannel); + Assertions.assertNotNull(alertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelTest.java index 6a123eedcc..fd892fe281 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelTest.java @@ -36,10 +36,11 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class EmailAlertChannelTest { + @Test public void testProcess() { EmailAlertChannel emailAlertChannel = new EmailAlertChannel(); @@ -65,80 +66,83 @@ public class EmailAlertChannelTest { alertInfo.setAlertParams(paramsMap); AlertResult alertResult = emailAlertChannel.process(alertInfo); - Assert.assertNotNull(alertResult); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertNotNull(alertResult); + Assertions.assertEquals("false", alertResult.getStatus()); } public String getEmailAlertParams() { List paramsList = new ArrayList<>(); - InputParam receivesParam = InputParam.newBuilder(MailParamsConstants.NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERS, "receivers") - .setValue("540957506@qq.com") - .addValidate(Validate.newBuilder().setRequired(true).build()) - .build(); + InputParam receivesParam = + InputParam.newBuilder(MailParamsConstants.NAME_PLUGIN_DEFAULT_EMAIL_RECEIVERS, "receivers") + .setValue("540957506@qq.com") + .addValidate(Validate.newBuilder().setRequired(true).build()) + .build(); InputParam mailSmtpHost = InputParam.newBuilder(MailParamsConstants.NAME_MAIL_SMTP_HOST, "smtp.host") - .addValidate(Validate.newBuilder().setRequired(true).build()) - .setValue("smtp.126.com") - .build(); + .addValidate(Validate.newBuilder().setRequired(true).build()) + .setValue("smtp.126.com") + .build(); InputParam mailSmtpPort = InputParam.newBuilder(MailParamsConstants.NAME_MAIL_SMTP_PORT, "smtp.port") - .addValidate(Validate.newBuilder() - .setRequired(true) - .build()) - .setValue("25") - .build(); + .addValidate(Validate.newBuilder() + .setRequired(true) + .build()) + .setValue("25") + .build(); InputParam mailSender = InputParam.newBuilder(MailParamsConstants.NAME_MAIL_SENDER, "sender") - .addValidate(Validate.newBuilder().setRequired(true).build()) - .setValue("dolphinscheduler@126.com") - .build(); + .addValidate(Validate.newBuilder().setRequired(true).build()) + .setValue("dolphinscheduler@126.com") + .build(); RadioParam enableSmtpAuth = RadioParam.newBuilder(MailParamsConstants.NAME_MAIL_SMTP_AUTH, "smtp.auth") - .addParamsOptions(new ParamsOptions("YES", "true", false)) - .addParamsOptions(new ParamsOptions("NO", "false", false)) - .addValidate(Validate.newBuilder().setRequired(true).build()) - .setValue("false") - .build(); + .addParamsOptions(new ParamsOptions("YES", "true", false)) + .addParamsOptions(new ParamsOptions("NO", "false", false)) + .addValidate(Validate.newBuilder().setRequired(true).build()) + .setValue("false") + .build(); InputParam mailUser = InputParam.newBuilder(MailParamsConstants.NAME_MAIL_USER, "user") - .setPlaceholder("if enable use authentication, you need input user") - .setValue("dolphinscheduler@126.com") - .build(); + .setPlaceholder("if enable use authentication, you need input user") + .setValue("dolphinscheduler@126.com") + .build(); PasswordParam mailPassword = PasswordParam.newBuilder(MailParamsConstants.NAME_MAIL_PASSWD, "passwd") - .setPlaceholder("if enable use authentication, you need input password") - .setValue("escheduler123") - .build(); + .setPlaceholder("if enable use authentication, you need input password") + .setValue("escheduler123") + .build(); - RadioParam enableTls = RadioParam.newBuilder(MailParamsConstants.NAME_MAIL_SMTP_STARTTLS_ENABLE, "starttls.enable") - .addParamsOptions(new ParamsOptions("YES", "true", false)) - .addParamsOptions(new ParamsOptions("NO", "false", false)) - .addValidate(Validate.newBuilder().setRequired(true).build()) - .setValue("true") - .build(); + RadioParam enableTls = + RadioParam.newBuilder(MailParamsConstants.NAME_MAIL_SMTP_STARTTLS_ENABLE, "starttls.enable") + .addParamsOptions(new ParamsOptions("YES", "true", false)) + .addParamsOptions(new ParamsOptions("NO", "false", false)) + .addValidate(Validate.newBuilder().setRequired(true).build()) + .setValue("true") + .build(); RadioParam enableSsl = RadioParam.newBuilder(MailParamsConstants.NAME_MAIL_SMTP_SSL_ENABLE, "smtp.ssl.enable") - .addParamsOptions(new ParamsOptions("YES", "true", false)) - .addParamsOptions(new ParamsOptions("NO", "false", false)) - .addValidate(Validate.newBuilder().setRequired(true).build()) - .setValue("true") - .build(); + .addParamsOptions(new ParamsOptions("YES", "true", false)) + .addParamsOptions(new ParamsOptions("NO", "false", false)) + .addValidate(Validate.newBuilder().setRequired(true).build()) + .setValue("true") + .build(); InputParam sslTrust = InputParam.newBuilder(MailParamsConstants.NAME_MAIL_SMTP_SSL_TRUST, "smtp.ssl.trust") - .addValidate(Validate.newBuilder().setRequired(true).build()) - .setValue("smtp.126.com") - .build(); + .addValidate(Validate.newBuilder().setRequired(true).build()) + .setValue("smtp.126.com") + .build(); List emailShowTypeList = new ArrayList<>(); emailShowTypeList.add(new ParamsOptions(ShowType.TABLE.getDescp(), ShowType.TABLE.getDescp(), false)); emailShowTypeList.add(new ParamsOptions(ShowType.TEXT.getDescp(), ShowType.TEXT.getDescp(), false)); emailShowTypeList.add(new ParamsOptions(ShowType.ATTACHMENT.getDescp(), ShowType.ATTACHMENT.getDescp(), false)); - emailShowTypeList.add(new ParamsOptions(ShowType.TABLE_ATTACHMENT.getDescp(), ShowType.TABLE_ATTACHMENT.getDescp(), false)); + emailShowTypeList.add( + new ParamsOptions(ShowType.TABLE_ATTACHMENT.getDescp(), ShowType.TABLE_ATTACHMENT.getDescp(), false)); RadioParam showType = RadioParam.newBuilder(AlertConstants.NAME_SHOW_TYPE, "showType") - .setOptions(emailShowTypeList) - .setValue(ShowType.TABLE.getDescp()) - .addValidate(Validate.newBuilder().setRequired(true).build()) - .build(); + .setOptions(emailShowTypeList) + .setValue(ShowType.TABLE.getDescp()) + .addValidate(Validate.newBuilder().setRequired(true).build()) + .build(); paramsList.add(receivesParam); paramsList.add(mailSmtpHost); diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtilsTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtilsTest.java index f3455a36b4..f428a16d92 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtilsTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtilsTest.java @@ -17,88 +17,57 @@ package org.apache.dolphinscheduler.plugin.alert.email; -import static org.junit.Assert.assertTrue; +import org.apache.dolphinscheduler.plugin.alert.email.exception.AlertEmailException; import java.io.File; +import java.nio.file.Path; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class ExcelUtilsTest { - private static final Logger logger = LoggerFactory.getLogger(ExcelUtilsTest.class); + @TempDir + public Path testFolder; - @Rule - public ExpectedException expectedException = ExpectedException.none(); + private String xlsFilePath; - @Rule - public TemporaryFolder folder = new TemporaryFolder(); - - private String rootPath = null; - - @Before + @BeforeEach public void setUp() throws Exception { - - folder.create(); - rootPath = folder.getRoot().getAbsolutePath(); - } - - @After - public void tearDown() throws Exception { - - folder.delete(); + xlsFilePath = testFolder.toString(); } - /** - * Test GenExcelFile - */ @Test public void testGenExcelFile() { - - //Define dest file path - String xlsFilePath = rootPath + System.getProperty("file.separator"); - logger.info("xlsFilePath: " + xlsFilePath); - - //Define correctContent + // Define correctContent String correctContent = "[{\"name\":\"ds name\",\"value\":\"ds value\"}]"; - //Define incorrectContent + // Define incorrectContent String incorrectContent1 = "{\"name\":\"ds name\",\"value\":\"ds value\"}"; - //Define title + // Define title String title = "test report"; - //Invoke genExcelFile with correctContent + // Invoke genExcelFile with correctContent ExcelUtils.genExcelFile(correctContent, title, xlsFilePath); - //Test file exists + // Test file exists File xlsFile = new File(xlsFilePath + EmailConstants.SINGLE_SLASH + title + EmailConstants.EXCEL_SUFFIX_XLSX); - assertTrue(xlsFile.exists()); - - //Expected RuntimeException - expectedException.expect(RuntimeException.class); - - //Expected error message - expectedException.expectMessage("itemsList is null"); + Assertions.assertTrue(xlsFile.exists()); - //Invoke genExcelFile with incorrectContent, will cause RuntimeException - ExcelUtils.genExcelFile(incorrectContent1, title, xlsFilePath); + // Invoke genExcelFile with incorrectContent, will cause RuntimeException + Assertions.assertThrows(AlertEmailException.class, () -> { + ExcelUtils.genExcelFile(incorrectContent1, title, xlsFilePath); + }); } - /** - * Test GenExcelFile (check directory) - */ @Test public void testGenExcelFileByCheckDir() { ExcelUtils.genExcelFile("[{\"a\": \"a\"},{\"a\": \"a\"}]", "t", "/tmp/xls"); File file = new File("/tmp/xls" + EmailConstants.SINGLE_SLASH + "t" + EmailConstants.EXCEL_SUFFIX_XLSX); file.delete(); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/MailUtilsTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/MailUtilsTest.java index e4bb76dd27..4472f22920 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/MailUtilsTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/MailUtilsTest.java @@ -29,20 +29,21 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -@Ignore("The test case makes no sense") +@Disabled("The test case makes no sense") public class MailUtilsTest { + private static final Logger logger = LoggerFactory.getLogger(MailUtilsTest.class); static MailSender mailSender; private static Map emailConfig = new HashMap<>(); private static AlertTemplate alertTemplate; - @BeforeClass + @BeforeAll public static void initEmailConfig() { emailConfig.put(MailParamsConstants.NAME_MAIL_PROTOCOL, "smtp"); emailConfig.put(MailParamsConstants.NAME_MAIL_SMTP_HOST, "xxx.xxx.com"); @@ -65,19 +66,19 @@ public class MailUtilsTest { public void testSendMails() { String content = "[\"id:69\"," - + "\"name:UserBehavior-0--1193959466\"," - + "\"Job name: Start workflow\"," - + "\"State: SUCCESS\"," - + "\"Recovery:NO\"," - + "\"Run time: 1\"," - + "\"Start time: 2018-08-06 10:31:34.0\"," - + "\"End time: 2018-08-06 10:31:49.0\"," - + "\"Host: 192.168.xx.xx\"," - + "\"Notify group :4\"]"; + + "\"name:UserBehavior-0--1193959466\"," + + "\"Job name: Start workflow\"," + + "\"State: SUCCESS\"," + + "\"Recovery:NO\"," + + "\"Run time: 1\"," + + "\"Start time: 2018-08-06 10:31:34.0\"," + + "\"End time: 2018-08-06 10:31:49.0\"," + + "\"Host: 192.168.xx.xx\"," + + "\"Notify group :4\"]"; mailSender.sendMails( - "Mysql Exception", - content); + "Mysql Exception", + content); } public String list2String() { diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/template/DefaultHTMLTemplateTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/template/DefaultHTMLTemplateTest.java index 37fe97857c..43ae1bc073 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/template/DefaultHTMLTemplateTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/template/DefaultHTMLTemplateTest.java @@ -17,8 +17,6 @@ package org.apache.dolphinscheduler.plugin.alert.email.template; -import static org.junit.Assert.assertEquals; - import org.apache.dolphinscheduler.alert.api.ShowType; import org.apache.dolphinscheduler.plugin.alert.email.EmailConstants; import org.apache.dolphinscheduler.spi.utils.JSONUtils; @@ -27,7 +25,8 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,11 +40,11 @@ public class DefaultHTMLTemplateTest { String tableTypeMessage = template.getMessageFromTemplate(list2String(), ShowType.TABLE, true); - assertEquals(tableTypeMessage, generateMockTableTypeResultByHand()); + Assertions.assertEquals(tableTypeMessage, generateMockTableTypeResultByHand()); String textTypeMessage = template.getMessageFromTemplate(list2String(), ShowType.TEXT, true); - assertEquals(textTypeMessage, generateMockTextTypeResultByHand()); + Assertions.assertEquals(textTypeMessage, generateMockTextTypeResultByHand()); String mapjson = "{\"taskInstanceId\":94,\"taskName\":\"000\",\"taskType\":\"DATA_QUALITY\"," + "\"processDefinitionId\":0,\"processInstanceId\":58,\"state\":\"RUNNING_EXECUTION\"," @@ -53,7 +52,7 @@ public class DefaultHTMLTemplateTest { + "\"logPath\":\"/Users/mac/学习/dolphinscheduler/dolphinscheduler/logs/20220717/6222644042400_1-58-94.log\"}"; textTypeMessage = template.getMessageFromTemplate(mapjson, ShowType.TEXT, true); String result = textTypeMessage; - assertEquals(textTypeMessage, result); + Assertions.assertEquals(textTypeMessage, result); } private String list2String() { @@ -82,19 +81,19 @@ public class DefaultHTMLTemplateTest { private String generateMockTableTypeResultByHand() { return EmailConstants.HTML_HEADER_PREFIX - + "" - + "mysql service namemysql addressdatabase client connectionsportno index of number" - + ""+System.getProperty("line.separator") - + "mysql200192.168.xx.xx190330680" - + "mysql210192.168.xx.xx90330610" - + EmailConstants.TABLE_BODY_HTML_TAIL; + + "" + + "mysql service namemysql addressdatabase client connectionsportno index of number" + + "" + System.getProperty("line.separator") + + "mysql200192.168.xx.xx190330680" + + "mysql210192.168.xx.xx90330610" + + EmailConstants.TABLE_BODY_HTML_TAIL; } private String generateMockTextTypeResultByHand() { return EmailConstants.HTML_HEADER_PREFIX - + "{\"mysql service name\":\"mysql200\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"190\",\"port\":\"3306\",\"no index of number\":\"80\"}" - + "{\"mysql service name\":\"mysql210\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"90\",\"port\":\"3306\",\"no index of number\":\"10\"}" - + EmailConstants.TABLE_BODY_HTML_TAIL; + + "{\"mysql service name\":\"mysql200\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"190\",\"port\":\"3306\",\"no index of number\":\"80\"}" + + "{\"mysql service name\":\"mysql210\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"90\",\"port\":\"3306\",\"no index of number\":\"10\"}" + + EmailConstants.TABLE_BODY_HTML_TAIL; } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuAlertChannelFactoryTest.java index ce51e00474..5ec2726817 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuAlertChannelFactoryTest.java @@ -23,8 +23,8 @@ import org.apache.dolphinscheduler.spi.utils.JSONUtils; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class FeiShuAlertChannelFactoryTest { @@ -33,13 +33,13 @@ public class FeiShuAlertChannelFactoryTest { FeiShuAlertChannelFactory feiShuAlertChannelFactory = new FeiShuAlertChannelFactory(); List params = feiShuAlertChannelFactory.params(); JSONUtils.toJsonString(params); - Assert.assertEquals(6, params.size()); + Assertions.assertEquals(6, params.size()); } @Test public void testCreate() { FeiShuAlertChannelFactory feiShuAlertChannelFactory = new FeiShuAlertChannelFactory(); AlertChannel alertChannel = feiShuAlertChannelFactory.create(); - Assert.assertNotNull(alertChannel); + Assertions.assertNotNull(alertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuSenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuSenderTest.java index 8d5dfdbc6a..41f372b85c 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuSenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuSenderTest.java @@ -23,16 +23,15 @@ import org.apache.dolphinscheduler.alert.api.AlertResult; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class FeiShuSenderTest { - private static Map feiShuConfig = new HashMap<>(); - @Before + @BeforeEach public void initFeiShuConfig() { feiShuConfig.put(FeiShuParamsConstants.WEB_HOOK, "https://open.feishu.cn/open-apis/bot/v2/hook/xxxxx"); } @@ -44,33 +43,33 @@ public class FeiShuSenderTest { alertData.setContent("feishu test content"); FeiShuSender feiShuSender = new FeiShuSender(feiShuConfig); AlertResult alertResult = feiShuSender.sendFeiShuMsg(alertData); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertEquals("false", alertResult.getStatus()); } @Test public void testFormatContent() { String alertMsg = "[\n" - + " {\n" - + " \"owner\": \"dolphinscheduler\",\n" - + " \"processEndTime\": \"2021-01-29 19:01:11\",\n" - + " \"processHost\": \"10.81.129.4:5678\",\n" - + " \"processId\": 2926,\n" - + " \"processName\": \"3-20210129190038108\",\n" - + " \"processStartTime\": \"2021-01-29 19:00:38\",\n" - + " \"processState\": \"SUCCESS\",\n" - + " \"processType\": \"START_PROCESS\",\n" - + " \"projectId\": 2,\n" - + " \"projectName\": \"testdelproject\",\n" - + " \"recovery\": \"NO\",\n" - + " \"retryTimes\": 0,\n" - + " \"runTimes\": 1,\n" - + " \"taskId\": 0\n" - + " }\n" - + "]"; + + " {\n" + + " \"owner\": \"dolphinscheduler\",\n" + + " \"processEndTime\": \"2021-01-29 19:01:11\",\n" + + " \"processHost\": \"10.81.129.4:5678\",\n" + + " \"processId\": 2926,\n" + + " \"processName\": \"3-20210129190038108\",\n" + + " \"processStartTime\": \"2021-01-29 19:00:38\",\n" + + " \"processState\": \"SUCCESS\",\n" + + " \"processType\": \"START_PROCESS\",\n" + + " \"projectId\": 2,\n" + + " \"projectName\": \"testdelproject\",\n" + + " \"recovery\": \"NO\",\n" + + " \"retryTimes\": 0,\n" + + " \"runTimes\": 1,\n" + + " \"taskId\": 0\n" + + " }\n" + + "]"; AlertData alertData = new AlertData(); alertData.setTitle(""); alertData.setContent(alertMsg); - Assert.assertNotNull(FeiShuSender.formatContent(alertData)); + Assertions.assertNotNull(FeiShuSender.formatContent(alertData)); } @Test @@ -80,7 +79,7 @@ public class FeiShuSenderTest { alertData.setContent("feishu test content"); FeiShuSender feiShuSender = new FeiShuSender(feiShuConfig); String alertResult = feiShuSender.formatContent(alertData); - Assert.assertEquals(alertResult, alertData.getTitle() + alertData.getContent()); + Assertions.assertEquals(alertResult, alertData.getTitle() + alertData.getContent()); } @Test @@ -88,12 +87,12 @@ public class FeiShuSenderTest { FeiShuSender feiShuSender = new FeiShuSender(feiShuConfig); AlertResult alertResult = feiShuSender.checkSendFeiShuSendMsgResult(""); - Assert.assertFalse(Boolean.valueOf(alertResult.getStatus())); + Assertions.assertFalse(Boolean.valueOf(alertResult.getStatus())); AlertResult alertResult2 = feiShuSender.checkSendFeiShuSendMsgResult("123"); - Assert.assertEquals("send fei shu msg fail", alertResult2.getMessage()); + Assertions.assertEquals("send fei shu msg fail", alertResult2.getMessage()); String response = "{\"StatusCode\":\"0\",\"extra\":\"extra\",\"StatusMessage\":\"StatusMessage\"}"; AlertResult alertResult3 = feiShuSender.checkSendFeiShuSendMsgResult(response); - Assert.assertTrue(Boolean.valueOf(alertResult3.getStatus())); + Assertions.assertTrue(Boolean.valueOf(alertResult3.getStatus())); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelFactoryTest.java index 089f78f3af..462060867e 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelFactoryTest.java @@ -22,15 +22,15 @@ import org.apache.dolphinscheduler.spi.params.base.PluginParams; import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class HttpAlertChannelFactoryTest { private HttpAlertChannelFactory httpAlertChannelFactory; - @Before + @BeforeEach public void init() { httpAlertChannelFactory = new HttpAlertChannelFactory(); } @@ -39,13 +39,13 @@ public class HttpAlertChannelFactoryTest { public void getParamsTest() { List pluginParamsList = httpAlertChannelFactory.params(); - Assert.assertEquals(5, pluginParamsList.size()); + Assertions.assertEquals(5, pluginParamsList.size()); } @Test public void createTest() { AlertChannel alertChannel = httpAlertChannelFactory.create(); - Assert.assertNotNull(alertChannel); + Assertions.assertNotNull(alertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelTest.java index fa0caf295d..632ea36207 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelTest.java @@ -34,8 +34,8 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class HttpAlertChannelTest { @@ -47,7 +47,7 @@ public class HttpAlertChannelTest { alertData.setContent("Fault tolerance warning"); alertInfo.setAlertData(alertData); AlertResult alertResult = alertChannel.process(alertInfo); - Assert.assertEquals("http params is null", alertResult.getMessage()); + Assertions.assertEquals("http params is null", alertResult.getMessage()); } @Test @@ -64,7 +64,7 @@ public class HttpAlertChannelTest { // it doReturn(new AlertResult("true", "success")).when(alertChannel).process(any()); AlertResult alertResult = alertChannel.process(alertInfo); - Assert.assertEquals("true", alertResult.getStatus()); + Assertions.assertEquals("true", alertResult.getStatus()); } /** diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpSenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpSenderTest.java index 3326803c50..73473876f6 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpSenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpSenderTest.java @@ -27,8 +27,8 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class HttpSenderTest { @@ -44,6 +44,6 @@ public class HttpSenderTest { HttpSender httpSender = spy(new HttpSender(paramsMap)); doReturn("success").when(httpSender).getResponseString(any()); AlertResult alertResult = httpSender.send("Fault tolerance warning"); - Assert.assertEquals("true", alertResult.getStatus()); + Assertions.assertEquals("true", alertResult.getStatus()); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutyAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutyAlertChannelFactoryTest.java index 1f3315cb4f..bb6ad67e52 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutyAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutyAlertChannelFactoryTest.java @@ -20,9 +20,11 @@ package org.apache.dolphinscheduler.plugin.alert.pagerduty; import org.apache.dolphinscheduler.alert.api.AlertChannel; import org.apache.dolphinscheduler.spi.params.base.PluginParams; import org.apache.dolphinscheduler.spi.utils.JSONUtils; + import java.util.List; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class PagerDutyAlertChannelFactoryTest { @@ -31,13 +33,13 @@ public class PagerDutyAlertChannelFactoryTest { PagerDutyAlertChannelFactory pagerDutyAlertChannelFactory = new PagerDutyAlertChannelFactory(); List params = pagerDutyAlertChannelFactory.params(); JSONUtils.toJsonString(params); - Assert.assertEquals(1, params.size()); + Assertions.assertEquals(1, params.size()); } @Test public void testCreate() { PagerDutyAlertChannelFactory pagerDutyAlertChannelFactory = new PagerDutyAlertChannelFactory(); AlertChannel alertChannel = pagerDutyAlertChannelFactory.create(); - Assert.assertNotNull(alertChannel); + Assertions.assertNotNull(alertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutySenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutySenderTest.java index 2f16c1a436..16cf16f62f 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutySenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutySenderTest.java @@ -18,16 +18,19 @@ package org.apache.dolphinscheduler.plugin.alert.pagerduty; import org.apache.dolphinscheduler.alert.api.AlertResult; + import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class PagerDutySenderTest { + private static final Map pagerDutyConfig = new HashMap<>(); - @Before + @BeforeEach public void initDingTalkConfig() { pagerDutyConfig.put(PagerDutyParamsConstants.NAME_PAGER_DUTY_INTEGRATION_KEY_NAME, "test"); } @@ -36,6 +39,6 @@ public class PagerDutySenderTest { public void testSend() { PagerDutySender pagerDutySender = new PagerDutySender(pagerDutyConfig); AlertResult alertResult = pagerDutySender.sendPagerDutyAlter("pagerduty test title", "pagerduty test content"); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertEquals("false", alertResult.getStatus()); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ProcessUtilsTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ProcessUtilsTest.java index 7ee473e9a7..a34f062264 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ProcessUtilsTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ProcessUtilsTest.java @@ -17,7 +17,7 @@ package org.apache.dolphinscheduler.plugin.alert.script; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * ProcessUtilsTest @@ -26,7 +26,8 @@ public class ProcessUtilsTest { private static final String rootPath = System.getProperty("user.dir"); - private static final String shellFilPath = rootPath + "/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/script/shell/test.sh"; + private static final String shellFilPath = + rootPath + "/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/script/shell/test.sh"; private String[] cmd = {"/bin/sh", "-c", shellFilPath + " -t 1"}; diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptAlertChannelFactoryTest.java index ca45cf7aed..f9b7e338f6 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptAlertChannelFactoryTest.java @@ -22,8 +22,8 @@ import org.apache.dolphinscheduler.spi.params.base.PluginParams; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * ScriptAlertChannelFactoryTest @@ -34,13 +34,13 @@ public class ScriptAlertChannelFactoryTest { public void testGetParams() { ScriptAlertChannelFactory scriptAlertChannelFactory = new ScriptAlertChannelFactory(); List params = scriptAlertChannelFactory.params(); - Assert.assertEquals(3, params.size()); + Assertions.assertEquals(3, params.size()); } @Test public void testCreate() { ScriptAlertChannelFactory scriptAlertChannelFactory = new ScriptAlertChannelFactory(); AlertChannel alertChannel = scriptAlertChannelFactory.create(); - Assert.assertNotNull(alertChannel); + Assertions.assertNotNull(alertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptSenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptSenderTest.java index 64a811d474..ad33bbe6a3 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptSenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptSenderTest.java @@ -22,9 +22,9 @@ import org.apache.dolphinscheduler.alert.api.AlertResult; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * ScriptSenderTest @@ -35,7 +35,7 @@ public class ScriptSenderTest { private static final String shellFilPath = rootPath + "/src/test/script/shell/scriptExample.sh"; private static Map scriptConfig = new HashMap<>(); - @Before + @BeforeEach public void initScriptConfig() { scriptConfig.put(ScriptParamsConstants.NAME_SCRIPT_TYPE, String.valueOf(ScriptType.SHELL.getDescp())); @@ -48,9 +48,9 @@ public class ScriptSenderTest { ScriptSender scriptSender = new ScriptSender(scriptConfig); AlertResult alertResult; alertResult = scriptSender.sendScriptAlert("test title Kris", "test content"); - Assert.assertEquals("true", alertResult.getStatus()); + Assertions.assertEquals("true", alertResult.getStatus()); alertResult = scriptSender.sendScriptAlert("error msg title", "test content"); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertEquals("false", alertResult.getStatus()); } @Test @@ -58,7 +58,7 @@ public class ScriptSenderTest { scriptConfig.put(ScriptParamsConstants.NAME_SCRIPT_USER_PARAMS, "' ; calc.exe ; '"); ScriptSender scriptSender = new ScriptSender(scriptConfig); AlertResult alertResult = scriptSender.sendScriptAlert("test title Kris", "test content"); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertEquals("false", alertResult.getStatus()); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackAlertChannelFactoryTest.java index 21ba907ee7..3c60247573 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackAlertChannelFactoryTest.java @@ -22,8 +22,8 @@ import org.apache.dolphinscheduler.spi.params.base.PluginParams; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class SlackAlertChannelFactoryTest { @@ -31,18 +31,18 @@ public class SlackAlertChannelFactoryTest { @Test public void testTestGetName() { - Assert.assertEquals("Slack", slackAlertChannelFactory.name()); + Assertions.assertEquals("Slack", slackAlertChannelFactory.name()); } @Test public void testGetParams() { List params = slackAlertChannelFactory.params(); - Assert.assertEquals(2, params.size()); + Assertions.assertEquals(2, params.size()); } @Test public void testCreate() { AlertChannel alertChannel = slackAlertChannelFactory.create(); - Assert.assertTrue(alertChannel instanceof SlackAlertChannel); + Assertions.assertTrue(alertChannel instanceof SlackAlertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackSenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackSenderTest.java index 7e261309b7..dc92f9cc6a 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackSenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackSenderTest.java @@ -20,8 +20,8 @@ package org.apache.dolphinscheduler.plugin.alert.slack; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class SlackSenderTest { @@ -29,11 +29,11 @@ public class SlackSenderTest { public void testSendMessage() { Map alertparam = new HashMap<>(); alertparam.put(SlackParamsConstants.SLACK_WEB_HOOK_URL_NAME, - "https://hooks.slack.com/services/123456"); + "https://hooks.slack.com/services/123456"); alertparam.put(SlackParamsConstants.SLACK_BOT_NAME, "Dolphinscheduler"); SlackSender slackSender = new SlackSender(alertparam); String response = slackSender.sendMessage("test title", "test content"); - Assert.assertNotEquals("ok", response); + Assertions.assertNotEquals("ok", response); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramAlertChannelFactoryTest.java index 0ffe062bf4..c7b2d412ba 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramAlertChannelFactoryTest.java @@ -19,29 +19,30 @@ package org.apache.dolphinscheduler.plugin.alert.telegram; import org.apache.dolphinscheduler.alert.api.AlertChannel; import org.apache.dolphinscheduler.spi.params.base.PluginParams; -import org.junit.Assert; -import org.junit.Test; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class TelegramAlertChannelFactoryTest { private TelegramAlertChannelFactory telegramAlertChannelFactory = new TelegramAlertChannelFactory(); @Test public void testTestGetName() { - Assert.assertEquals("Telegram", telegramAlertChannelFactory.name()); + Assertions.assertEquals("Telegram", telegramAlertChannelFactory.name()); } @Test public void testGetParams() { List params = telegramAlertChannelFactory.params(); - Assert.assertEquals(9, params.size()); + Assertions.assertEquals(9, params.size()); } @Test public void testCreate() { AlertChannel alertChannel = telegramAlertChannelFactory.create(); - Assert.assertTrue(alertChannel instanceof TelegramAlertChannel); + Assertions.assertTrue(alertChannel instanceof TelegramAlertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramSenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramSenderTest.java index 8ebd6fcd9d..a57de30219 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramSenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramSenderTest.java @@ -19,18 +19,19 @@ package org.apache.dolphinscheduler.plugin.alert.telegram; import org.apache.dolphinscheduler.alert.api.AlertData; import org.apache.dolphinscheduler.alert.api.AlertResult; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import java.util.HashMap; import java.util.Map; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + public class TelegramSenderTest { private static Map telegramConfig = new HashMap<>(); - @Before + @BeforeEach public void initConfig() { telegramConfig.put(TelegramParamsConstants.NAME_TELEGRAM_WEB_HOOK, "https://api.telegram.org/bot{botToken}/sendMessage"); @@ -42,7 +43,6 @@ public class TelegramSenderTest { TelegramParamsConstants.NAME_TELEGRAM_PARSE_MODE, TelegramAlertConstants.PARSE_MODE_TXT); } - @Test public void testSendMessageFailByParamToken() { AlertData alertData = new AlertData(); @@ -52,7 +52,7 @@ public class TelegramSenderTest { TelegramParamsConstants.NAME_TELEGRAM_BOT_TOKEN, "XXXXXXX"); TelegramSender telegramSender = new TelegramSender(telegramConfig); AlertResult result = telegramSender.sendMessage(alertData); - Assert.assertEquals("false", result.getStatus()); + Assertions.assertEquals("false", result.getStatus()); } @@ -65,11 +65,9 @@ public class TelegramSenderTest { TelegramParamsConstants.NAME_TELEGRAM_CHAT_ID, "-XXXXXXX"); TelegramSender telegramSender = new TelegramSender(telegramConfig); AlertResult result = telegramSender.sendMessage(alertData); - Assert.assertEquals("false", result.getStatus()); + Assertions.assertEquals("false", result.getStatus()); } - - @Test public void testSendMessage() { AlertData alertData = new AlertData(); @@ -77,7 +75,7 @@ public class TelegramSenderTest { alertData.setContent("telegram test content"); TelegramSender telegramSender = new TelegramSender(telegramConfig); AlertResult result = telegramSender.sendMessage(alertData); - Assert.assertEquals("false", result.getStatus()); + Assertions.assertEquals("false", result.getStatus()); } @@ -85,12 +83,13 @@ public class TelegramSenderTest { public void testSendMessageByMarkdown() { AlertData alertData = new AlertData(); alertData.setTitle("[telegram alert]test markdown"); - alertData.setContent("```python \npre-formatted fixed-width code block written in the Python programming language```"); + alertData.setContent( + "```python \npre-formatted fixed-width code block written in the Python programming language```"); telegramConfig.put( TelegramParamsConstants.NAME_TELEGRAM_PARSE_MODE, TelegramAlertConstants.PARSE_MODE_MARKDOWN); TelegramSender telegramSender = new TelegramSender(telegramConfig); AlertResult result = telegramSender.sendMessage(alertData); - Assert.assertEquals("false", result.getStatus()); + Assertions.assertEquals("false", result.getStatus()); } @@ -103,9 +102,8 @@ public class TelegramSenderTest { TelegramParamsConstants.NAME_TELEGRAM_PARSE_MODE, TelegramAlertConstants.PARSE_MODE_HTML); TelegramSender telegramSender = new TelegramSender(telegramConfig); AlertResult result = telegramSender.sendMessage(alertData); - Assert.assertEquals("false", result.getStatus()); + Assertions.assertEquals("false", result.getStatus()); } - } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsAlertChannelFactoryTest.java index ce00602f1d..0ce0a3b9c6 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsAlertChannelFactoryTest.java @@ -20,9 +20,11 @@ package org.apache.dolphinscheduler.plugin.alert.webexteams; import org.apache.dolphinscheduler.alert.api.AlertChannel; import org.apache.dolphinscheduler.spi.params.base.PluginParams; import org.apache.dolphinscheduler.spi.utils.JSONUtils; + import java.util.List; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class WebexTeamsAlertChannelFactoryTest { @@ -31,13 +33,13 @@ public class WebexTeamsAlertChannelFactoryTest { WebexTeamsAlertChannelFactory webexTeamsAlertChannelFactory = new WebexTeamsAlertChannelFactory(); List params = webexTeamsAlertChannelFactory.params(); JSONUtils.toJsonString(params); - Assert.assertEquals(6, params.size()); + Assertions.assertEquals(6, params.size()); } @Test public void testCreate() { WebexTeamsAlertChannelFactory webexTeamsAlertChannelFactory = new WebexTeamsAlertChannelFactory(); AlertChannel alertChannel = webexTeamsAlertChannelFactory.create(); - Assert.assertNotNull(alertChannel); + Assertions.assertNotNull(alertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsSenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsSenderTest.java index 4b9c552b71..1d3070cb55 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsSenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsSenderTest.java @@ -23,32 +23,33 @@ import org.apache.dolphinscheduler.alert.api.AlertResult; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class WebexTeamsSenderTest { + private static final Map webexTeamsConfig = new HashMap<>(); private AlertData alertData; private String content = "[{" + - "\"projectId\":90001," + - "\"projectName\":\"test-k8s\"," + - "\"owner\":\"test@cisco.com\"," + - "\"processId\":90019," + - "\"processDefinitionCode\":1111111," + - "\"processName\":\"test-name\"," + - "\"taskCode\":2222222," + - "\"taskName\":\"test\"," + - "\"taskType\":\"SQL\"," + - "\"taskState\":\"FAILURE\"," + - "\"taskStartTime\":\"2022-01-12 11:05:27\"," + - "\"taskEndTime\":\"2022-01-12 11:05:28\"," + - "\"taskHost\":\"dolphinscheduler-test\"," + - "\"logPath\":\"test.log\"}]"; + "\"projectId\":90001," + + "\"projectName\":\"test-k8s\"," + + "\"owner\":\"test@cisco.com\"," + + "\"processId\":90019," + + "\"processDefinitionCode\":1111111," + + "\"processName\":\"test-name\"," + + "\"taskCode\":2222222," + + "\"taskName\":\"test\"," + + "\"taskType\":\"SQL\"," + + "\"taskState\":\"FAILURE\"," + + "\"taskStartTime\":\"2022-01-12 11:05:27\"," + + "\"taskEndTime\":\"2022-01-12 11:05:28\"," + + "\"taskHost\":\"dolphinscheduler-test\"," + + "\"logPath\":\"test.log\"}]"; - @Before + @BeforeEach public void initDingTalkConfig() { webexTeamsConfig.put(WebexTeamsParamsConstants.NAME_WEBEX_TEAMS_BOT_ACCESS_TOKEN, "accessToken"); webexTeamsConfig.put(WebexTeamsParamsConstants.NAME_WEBEX_TEAMS_ROOM_ID, "roomId"); @@ -62,25 +63,28 @@ public class WebexTeamsSenderTest { @Test public void testSendToRoomId() { - webexTeamsConfig.put(WebexTeamsParamsConstants.NAME_WEBEX_TEAMS_DESTINATION, WebexTeamsDestination.ROOM_ID.getDescp()); + webexTeamsConfig.put(WebexTeamsParamsConstants.NAME_WEBEX_TEAMS_DESTINATION, + WebexTeamsDestination.ROOM_ID.getDescp()); testSend(); } @Test public void testSendToPersonEmail() { - webexTeamsConfig.put(WebexTeamsParamsConstants.NAME_WEBEX_TEAMS_DESTINATION, WebexTeamsDestination.PERSON_EMAIL.getDescp()); + webexTeamsConfig.put(WebexTeamsParamsConstants.NAME_WEBEX_TEAMS_DESTINATION, + WebexTeamsDestination.PERSON_EMAIL.getDescp()); testSend(); } @Test public void testSendToPersonId() { - webexTeamsConfig.put(WebexTeamsParamsConstants.NAME_WEBEX_TEAMS_DESTINATION, WebexTeamsDestination.PERSON_ID.getDescp()); + webexTeamsConfig.put(WebexTeamsParamsConstants.NAME_WEBEX_TEAMS_DESTINATION, + WebexTeamsDestination.PERSON_ID.getDescp()); testSend(); } - public void testSend(){ + public void testSend() { WebexTeamsSender webexTeamsSender = new WebexTeamsSender(webexTeamsConfig); AlertResult alertResult = webexTeamsSender.sendWebexTeamsAlter(alertData); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertEquals("false", alertResult.getStatus()); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatAlertChannelFactoryTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatAlertChannelFactoryTest.java index 04ecc36482..15cbcb77d7 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatAlertChannelFactoryTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatAlertChannelFactoryTest.java @@ -23,8 +23,8 @@ import org.apache.dolphinscheduler.spi.utils.JSONUtils; import java.util.List; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * WeChatAlertChannelFactoryTest @@ -36,13 +36,13 @@ public class WeChatAlertChannelFactoryTest { WeChatAlertChannelFactory weChatAlertChannelFactory = new WeChatAlertChannelFactory(); List params = weChatAlertChannelFactory.params(); JSONUtils.toJsonString(params); - Assert.assertEquals(6, params.size()); + Assertions.assertEquals(6, params.size()); } @Test public void testCreate() { WeChatAlertChannelFactory dingTalkAlertChannelFactory = new WeChatAlertChannelFactory(); AlertChannel alertChannel = dingTalkAlertChannelFactory.create(); - Assert.assertNotNull(alertChannel); + Assertions.assertNotNull(alertChannel); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatSenderTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatSenderTest.java index 77ee0c2dbe..e0c934f436 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatSenderTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatSenderTest.java @@ -24,9 +24,9 @@ import org.apache.dolphinscheduler.alert.api.ShowType; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; /** * WeChatSenderTest @@ -36,26 +36,26 @@ public class WeChatSenderTest { private static Map weChatConfig = new HashMap<>(); private String content = "[{\"id\":\"69\"," - + - "\"name\":\"UserBehavior-0--1193959466\"," - + - "\"Job name\":\"Start workflow\"," - + - "\"State\":\"SUCCESS\"," - + - "\"Recovery\":\"NO\"," - + - "\"Run time\":\"1\"," - + - "\"Start time\": \"2018-08-06 10:31:34.0\"," - + - "\"End time\": \"2018-08-06 10:31:49.0\"," - + - "\"Host\": \"192.168.xx.xx\"," - + - "\"Notify group\" :\"4\"}]"; + + + "\"name\":\"UserBehavior-0--1193959466\"," + + + "\"Job name\":\"Start workflow\"," + + + "\"State\":\"SUCCESS\"," + + + "\"Recovery\":\"NO\"," + + + "\"Run time\":\"1\"," + + + "\"Start time\": \"2018-08-06 10:31:34.0\"," + + + "\"End time\": \"2018-08-06 10:31:49.0\"," + + + "\"Host\": \"192.168.xx.xx\"," + + + "\"Notify group\" :\"4\"}]"; - @Before + @BeforeEach public void initDingTalkConfig() { // Just for this test, I will delete these configurations before this PR is merged weChatConfig.put(WeChatAlertParamsConstants.NAME_ENTERPRISE_WE_CHAT_AGENT_ID, "100000"); @@ -71,7 +71,7 @@ public class WeChatSenderTest { WeChatSender weChatSender = new WeChatSender(weChatConfig); AlertResult alertResult = weChatSender.sendEnterpriseWeChat("test", content); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertEquals("false", alertResult.getStatus()); } @Test @@ -79,7 +79,7 @@ public class WeChatSenderTest { weChatConfig.put(AlertConstants.NAME_SHOW_TYPE, ShowType.TEXT.getDescp()); WeChatSender weChatSender = new WeChatSender(weChatConfig); AlertResult alertResult = weChatSender.sendEnterpriseWeChat("test", content); - Assert.assertEquals("false", alertResult.getStatus()); + Assertions.assertEquals("false", alertResult.getStatus()); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/AlertPluginManagerTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/AlertPluginManagerTest.java index 912c959c84..aa505e1e68 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/AlertPluginManagerTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/AlertPluginManagerTest.java @@ -17,34 +17,35 @@ package org.apache.dolphinscheduler.alert; -import junit.framework.TestCase; +import static org.mockito.ArgumentMatchers.any; + import org.apache.dolphinscheduler.dao.PluginDao; -import org.apache.dolphinscheduler.dao.entity.PluginDefine; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +public class AlertPluginManagerTest { -@RunWith(MockitoJUnitRunner.class) -public class AlertPluginManagerTest extends TestCase { - - @InjectMocks - private AlertPluginManager alertPluginManager; - @Mock private PluginDao pluginDao; - + + @InjectMocks + private AlertPluginManager alertPluginManager; + @Test public void testAlertPluginManager() { - Mockito.when(pluginDao.addOrUpdatePluginDefine(Mockito.any(PluginDefine.class))).thenReturn(0); - + Mockito.when(pluginDao.addOrUpdatePluginDefine(any())).thenReturn(0); + alertPluginManager.installPlugin(null); - - Assert.assertEquals(1, alertPluginManager.size()); - - Assert.assertNotNull(alertPluginManager.getAlertChannel(0)); + + Assertions.assertEquals(1, alertPluginManager.size()); + + Assertions.assertNotNull(alertPluginManager.getAlertChannel(0)); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessorTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessorTest.java index 41277fad50..5ad6e26cdf 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessorTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessorTest.java @@ -25,34 +25,36 @@ import org.apache.dolphinscheduler.common.enums.WarningType; import org.apache.dolphinscheduler.remote.command.Command; import org.apache.dolphinscheduler.remote.command.CommandType; import org.apache.dolphinscheduler.remote.command.alert.AlertSendRequestCommand; - import org.apache.dolphinscheduler.remote.command.alert.AlertSendResponseCommand; -import org.junit.Assert; -import org.junit.Test; -import io.netty.channel.Channel; -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 io.netty.channel.Channel; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class AlertRequestProcessorTest { + @InjectMocks private AlertRequestProcessor alertRequestProcessor; @Mock private AlertSenderService alertSenderService; - @Test public void testProcess() { - Mockito.when(alertSenderService.syncHandler(1, "title", "content", WarningType.FAILURE.getCode())).thenReturn(new AlertSendResponseCommand()); + Mockito.when(alertSenderService.syncHandler(1, "title", "content", WarningType.FAILURE.getCode())) + .thenReturn(new AlertSendResponseCommand()); Channel channel = mock(Channel.class); - AlertSendRequestCommand alertSendRequestCommand = new AlertSendRequestCommand(1, "title", "content", WarningType.FAILURE.getCode()); + AlertSendRequestCommand alertSendRequestCommand = + new AlertSendRequestCommand(1, "title", "content", WarningType.FAILURE.getCode()); Command reqCommand = alertSendRequestCommand.convert2Command(); - Assert.assertEquals(CommandType.ALERT_SEND_REQUEST, reqCommand.getType()); + Assertions.assertEquals(CommandType.ALERT_SEND_REQUEST, reqCommand.getType()); alertRequestProcessor.process(channel, reqCommand); } } diff --git a/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/runner/AlertSenderServiceTest.java b/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/runner/AlertSenderServiceTest.java index 095cf2f758..371ea71f16 100644 --- a/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/runner/AlertSenderServiceTest.java +++ b/dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/runner/AlertSenderServiceTest.java @@ -37,9 +37,9 @@ import java.util.ArrayList; import java.util.List; import java.util.Optional; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; @@ -63,7 +63,7 @@ public class AlertSenderServiceTest { @InjectMocks private AlertSenderService alertSenderService; - @Before + @BeforeEach public void before() { MockitoAnnotations.initMocks(this); } @@ -81,7 +81,7 @@ public class AlertSenderServiceTest { AlertSendResponseCommand alertSendResponseCommand = alertSenderService.syncHandler(alertGroupId, title, content, WarningType.ALL.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())); @@ -102,7 +102,7 @@ public class AlertSenderServiceTest { alertSendResponseCommand = alertSenderService.syncHandler(alertGroupId, title, content, WarningType.ALL.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())); @@ -114,7 +114,7 @@ public class AlertSenderServiceTest { alertSendResponseCommand = alertSenderService.syncHandler(alertGroupId, title, content, WarningType.ALL.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 +127,7 @@ public class AlertSenderServiceTest { alertSendResponseCommand = alertSenderService.syncHandler(alertGroupId, title, content, WarningType.ALL.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())); @@ -141,7 +141,7 @@ public class AlertSenderServiceTest { alertSendResponseCommand = alertSenderService.syncHandler(alertGroupId, title, content, WarningType.ALL.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())); @@ -182,7 +182,7 @@ public class AlertSenderServiceTest { AlertChannel alertChannelMock = mock(AlertChannel.class); when(alertChannelMock.process(Mockito.any())).thenReturn(alertResult); when(alertPluginManager.getAlertChannel(1)).thenReturn(Optional.of(alertChannelMock)); - Assert.assertTrue(Boolean.parseBoolean(alertResult.getStatus())); + Assertions.assertTrue(Boolean.parseBoolean(alertResult.getStatus())); when(alertDao.listInstanceByAlertGroupId(1)).thenReturn(new ArrayList<>()); alertSenderService.send(alertList); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/aspect/AccessLogAspectTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/aspect/AccessLogAspectTest.java index b9f4cb5a17..44ddae818d 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/aspect/AccessLogAspectTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/aspect/AccessLogAspectTest.java @@ -17,7 +17,7 @@ package org.apache.dolphinscheduler.api.aspect; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** @@ -30,12 +30,14 @@ public class AccessLogAspectTest { @Test public void testHandleSensitiveData() { - String data = "userPassword='7ad2410b2f4c074479a8937a28a22b8f', email='xxx@qq.com', database='null', userName='root', password='root', other='null'"; - String expected = "userPassword='********************************', email='xxx@qq.com', database='null', userName='root', password='****', other='null'"; + String data = + "userPassword='7ad2410b2f4c074479a8937a28a22b8f', email='xxx@qq.com', database='null', userName='root', password='root', other='null'"; + String expected = + "userPassword='********************************', email='xxx@qq.com', database='null', userName='root', password='****', other='null'"; String actual = accessLogAspect.handleSensitiveData(data); - Assert.assertEquals(expected, actual); + Assertions.assertEquals(expected, actual); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/audit/AuditSubscriberTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/audit/AuditSubscriberTest.java index 5b0387bc78..fe8e5303f5 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/audit/AuditSubscriberTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/audit/AuditSubscriberTest.java @@ -25,14 +25,14 @@ import org.apache.dolphinscheduler.dao.mapper.AuditLogMapper; import java.util.Date; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class AuditSubscriberTest { @Mock @@ -44,6 +44,7 @@ public class AuditSubscriberTest { @Test public void testExecute() { Mockito.when(logMapper.insert(Mockito.any(AuditLog.class))).thenReturn(1); - auditSubscriber.execute(new AuditMessage(new User(), new Date(), AuditResourceType.USER_MODULE, AuditOperationType.CREATE, 1)); + auditSubscriber.execute( + new AuditMessage(new User(), new Date(), AuditResourceType.USER_MODULE, AuditOperationType.CREATE, 1)); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/AuditConfigurationTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/AuditConfigurationTest.java index daedffd03f..a2a3759c04 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/AuditConfigurationTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/AuditConfigurationTest.java @@ -17,16 +17,13 @@ package org.apache.dolphinscheduler.api.configuration; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles("audit") -@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuditConfiguration.class) public class AuditConfigurationTest { @@ -35,6 +32,6 @@ public class AuditConfigurationTest { @Test public void isAuditGlobalControlSwitch() { - Assert.assertTrue(auditConfiguration.getEnabled()); + Assertions.assertTrue(auditConfiguration.getEnabled()); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/TrafficConfigurationTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/TrafficConfigurationTest.java index a0c3d8a5a7..6b3671518f 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/TrafficConfigurationTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/TrafficConfigurationTest.java @@ -21,8 +21,8 @@ import org.apache.dolphinscheduler.api.controller.AbstractControllerTest; import org.apache.commons.collections.MapUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; public class TrafficConfigurationTest extends AbstractControllerTest { @@ -32,26 +32,26 @@ public class TrafficConfigurationTest extends AbstractControllerTest { @Test public void isTrafficGlobalControlSwitch() { - Assert.assertFalse(trafficConfiguration.isGlobalSwitch()); + Assertions.assertFalse(trafficConfiguration.isGlobalSwitch()); } @Test public void getMaxGlobalQpsLimit() { - Assert.assertEquals(300, (int) trafficConfiguration.getMaxGlobalQpsRate()); + Assertions.assertEquals(300, (int) trafficConfiguration.getMaxGlobalQpsRate()); } @Test public void isTrafficTenantControlSwitch() { - Assert.assertFalse(trafficConfiguration.isTenantSwitch()); + Assertions.assertFalse(trafficConfiguration.isTenantSwitch()); } @Test public void getDefaultTenantQpsLimit() { - Assert.assertEquals(10, (int) trafficConfiguration.getDefaultTenantQpsRate()); + Assertions.assertEquals(10, (int) trafficConfiguration.getDefaultTenantQpsRate()); } @Test public void getCustomizeTenantQpsRate() { - Assert.assertTrue(MapUtils.isEmpty(trafficConfiguration.getCustomizeTenantQpsRate())); + Assertions.assertTrue(MapUtils.isEmpty(trafficConfiguration.getCustomizeTenantQpsRate())); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AbstractControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AbstractControllerTest.java index 2e912f5508..6ce21a8071 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AbstractControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AbstractControllerTest.java @@ -36,22 +36,19 @@ import java.util.Map; import javax.annotation.PostConstruct; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -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.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; /** * abstract controller test */ -@RunWith(SpringRunner.class) @SpringBootTest(classes = {ApiApplicationServer.class, DaoConfiguration.class, RegistryServer.class}) @AutoConfigureMockMvc @DirtiesContext @@ -72,13 +69,13 @@ public abstract class AbstractControllerTest { protected String sessionId; - @Before + @BeforeEach public void setUp() { user = usersService.queryUser(1); createSession(user); } - @After + @AfterEach public void after() throws Exception { sessionService.signOut("127.0.0.1", user); } @@ -90,7 +87,7 @@ public abstract class AbstractControllerTest { String session = sessionService.createSession(loginUser, "127.0.0.1"); sessionId = session; - Assert.assertFalse(StringUtils.isEmpty(session)); + Assertions.assertFalse(StringUtils.isEmpty(session)); } public Map success() { @@ -119,6 +116,7 @@ public abstract class AbstractControllerTest { @Configuration public static class RegistryServer { + @PostConstruct public void startEmbedRegistryServer() throws Exception { final TestingServer server = new TestingServer(true); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenControllerTest.java index 24570f588b..86e382d238 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenControllerTest.java @@ -28,8 +28,8 @@ import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -41,6 +41,7 @@ import org.springframework.util.MultiValueMap; * access token controller test */ public class AccessTokenControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(AccessTokenControllerTest.class); @Test @@ -56,7 +57,7 @@ public class AccessTokenControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -69,14 +70,14 @@ public class AccessTokenControllerTest extends AbstractControllerTest { MvcResult mvcResult = this.mockMvc .perform(post("/access-tokens") - .header("sessionId", this.sessionId) - .params(paramsMap)) + .header("sessionId", this.sessionId) + .params(paramsMap)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -93,7 +94,7 @@ public class AccessTokenControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -109,7 +110,7 @@ public class AccessTokenControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -126,7 +127,7 @@ public class AccessTokenControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -134,12 +135,12 @@ public class AccessTokenControllerTest extends AbstractControllerTest { public void testQueryAccessTokenByUser() throws Exception { MvcResult mvcResult = this.mockMvc .perform(get("/access-tokens/user/1") - .header("sessionId", this.sessionId)) + .header("sessionId", this.sessionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -152,7 +153,7 @@ public class AccessTokenControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -170,7 +171,7 @@ public class AccessTokenControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -185,15 +186,15 @@ public class AccessTokenControllerTest extends AbstractControllerTest { MvcResult mvcResult = this.mockMvc .perform(put("/access-tokens/2") - .header("sessionId", this.sessionId) - .params(paramsMap)) + .header("sessionId", this.sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); - Assert.assertNotNull(result.getData()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result.getData()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenV2ControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenV2ControllerTest.java index 205a136db4..7ade90985a 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenV2ControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenV2ControllerTest.java @@ -17,29 +17,29 @@ package org.apache.dolphinscheduler.api.controller; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.MediaType; -import org.springframework.test.web.servlet.MvcResult; -import org.springframework.util.LinkedMultiValueMap; -import org.springframework.util.MultiValueMap; import java.util.HashMap; import java.util.Map; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MvcResult; /** * access token v2 controller test */ public class AccessTokenV2ControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(AccessTokenV2ControllerTest.class); @Test @@ -56,7 +56,7 @@ public class AccessTokenV2ControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -72,12 +72,12 @@ public class AccessTokenV2ControllerTest extends AbstractControllerTest { .header("sessionId", this.sessionId) .contentType(MediaType.APPLICATION_JSON) .content(JSONUtils.toJsonString(paramsMap))) - .andExpect(status().isCreated()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isCreated()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -95,7 +95,7 @@ public class AccessTokenV2ControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertGroupControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertGroupControllerTest.java index a40ec4996d..f0bbd09cb6 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertGroupControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertGroupControllerTest.java @@ -32,9 +32,9 @@ import org.apache.dolphinscheduler.dao.mapper.AlertGroupMapper; import java.util.Date; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -49,6 +49,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; * alert group controller test */ public class AlertGroupControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(AlertGroupController.class); private static final String defaultTestAlertGroupName = "cxc test group name"; @@ -65,9 +66,10 @@ public class AlertGroupControllerTest extends AbstractControllerTest { return alertGroup.getId(); } - @After + @AfterEach public void clear() { - alertGroupMapper.delete(new QueryWrapper().lambda().eq(AlertGroup::getGroupName, defaultTestAlertGroupName)); + alertGroupMapper.delete( + new QueryWrapper().lambda().eq(AlertGroup::getGroupName, defaultTestAlertGroupName)); } @Test @@ -84,7 +86,7 @@ public class AlertGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -99,7 +101,7 @@ public class AlertGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -118,7 +120,7 @@ public class AlertGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -134,7 +136,7 @@ public class AlertGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -153,7 +155,7 @@ public class AlertGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -168,7 +170,7 @@ public class AlertGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -183,7 +185,7 @@ public class AlertGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -198,7 +200,7 @@ public class AlertGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -206,13 +208,13 @@ public class AlertGroupControllerTest extends AbstractControllerTest { public void test090DelAlertGroupById() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); MvcResult mvcResult = mockMvc.perform(delete("/alert-groups/1") - .header("sessionId", sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header("sessionId", sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.NOT_ALLOW_TO_DELETE_DEFAULT_ALARM_GROUP.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.NOT_ALLOW_TO_DELETE_DEFAULT_ALARM_GROUP.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertPluginInstanceControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertPluginInstanceControllerTest.java index 6aa8d2bc80..f0ebecff78 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertPluginInstanceControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertPluginInstanceControllerTest.java @@ -35,7 +35,7 @@ import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.utils.JSONUtils; import org.apache.dolphinscheduler.dao.entity.User; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; @@ -48,230 +48,246 @@ import com.google.common.collect.ImmutableMap; * alert plugin instance controller test */ public class AlertPluginInstanceControllerTest extends AbstractControllerTest { + private static final int pluginDefineId = 1; private static final String instanceName = "instanceName"; private static final String pluginInstanceParams = "pluginInstanceParams"; private static final Result expectResponseContent = JSONUtils.parseObject( - "{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}" - , Result.class); + "{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}", Result.class); private static final ImmutableMap alertPluginInstanceServiceResult = ImmutableMap.of(Constants.STATUS, Status.SUCCESS, Constants.DATA_LIST, "Test Data"); - + @MockBean(name = "alertPluginInstanceServiceImpl") private AlertPluginInstanceService alertPluginInstanceService; - + @Test public void testCreateAlertPluginInstance() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginDefineId", String.valueOf(pluginDefineId)); paramsMap.add("instanceName", instanceName); paramsMap.add("pluginInstanceParams", pluginInstanceParams); - - when(alertPluginInstanceService.create(any(User.class), eq(pluginDefineId), eq(instanceName), eq(pluginInstanceParams))) - .thenReturn(alertPluginInstanceServiceResult); - - //When + + when(alertPluginInstanceService.create(any(User.class), eq(pluginDefineId), eq(instanceName), + eq(pluginInstanceParams))) + .thenReturn(alertPluginInstanceServiceResult); + + // When final MvcResult mvcResult = mockMvc.perform(post("/alert-plugin-instances") - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testUpdateAlertPluginInstance() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginDefineId", String.valueOf(pluginDefineId)); paramsMap.add("instanceName", instanceName); paramsMap.add("pluginInstanceParams", pluginInstanceParams); - - when(alertPluginInstanceService.update(any(User.class), eq(pluginDefineId), eq(instanceName), eq(pluginInstanceParams))) - .thenReturn(alertPluginInstanceServiceResult); - - //When + + when(alertPluginInstanceService.update(any(User.class), eq(pluginDefineId), eq(instanceName), + eq(pluginInstanceParams))) + .thenReturn(alertPluginInstanceServiceResult); + + // When final MvcResult mvcResult = mockMvc.perform(put("/alert-plugin-instances/{id}", pluginDefineId) - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testDeleteAlertPluginInstance() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginDefineId", String.valueOf(pluginDefineId)); paramsMap.add("instanceName", instanceName); paramsMap.add("pluginInstanceParams", pluginInstanceParams); - + when(alertPluginInstanceService.delete(any(User.class), eq(pluginDefineId))) .thenReturn(alertPluginInstanceServiceResult); - - //When + + // When final MvcResult mvcResult = mockMvc.perform(delete("/alert-plugin-instances/{id}", pluginDefineId) - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testGetAlertPluginInstance() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginDefineId", String.valueOf(pluginDefineId)); - + when(alertPluginInstanceService.get(any(User.class), eq(pluginDefineId))) .thenReturn(alertPluginInstanceServiceResult); - - //When + + // When final MvcResult mvcResult = mockMvc.perform(get("/alert-plugin-instances/{id}", pluginDefineId) - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testGetAlertPluginInstanceList() throws Exception { - //Given + // Given when(alertPluginInstanceService.queryAll()) .thenReturn(alertPluginInstanceServiceResult); - - //When + + // When final MvcResult mvcResult = mockMvc.perform(get("/alert-plugin-instances/list") - .header(SESSION_ID, sessionId)) + .header(SESSION_ID, sessionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testVerifyGroupName() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginDefineId", String.valueOf(pluginDefineId)); paramsMap.add("alertInstanceName", instanceName); - + when(alertPluginInstanceService.checkExistPluginInstanceName(eq(instanceName))) .thenReturn(false); - - Result expectResponseContent = JSONUtils.parseObject("{\"code\":0,\"msg\":\"success\",\"data\":null,\"failed\":false,\"success\":true}" - , Result.class); - - //When + + Result expectResponseContent = JSONUtils.parseObject( + "{\"code\":0,\"msg\":\"success\",\"data\":null,\"failed\":false,\"success\":true}", Result.class); + + // When final MvcResult mvcResult = mockMvc.perform(get("/alert-plugin-instances/verify-name") - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testVerifyGroupNamePluginInstanceNameExist() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginDefineId", String.valueOf(pluginDefineId)); paramsMap.add("alertInstanceName", instanceName); - + when(alertPluginInstanceService.checkExistPluginInstanceName(eq(instanceName))) .thenReturn(true); - - Result expectResponseContent = JSONUtils.parseObject("{\"code\":110010,\"msg\":\"plugin instance already exit\",\"data\":null,\"failed\":true,\"success\":false}" - , Result.class); - - //When + + Result expectResponseContent = JSONUtils.parseObject( + "{\"code\":110010,\"msg\":\"plugin instance already exit\",\"data\":null,\"failed\":true,\"success\":false}", + Result.class); + + // When final MvcResult mvcResult = mockMvc.perform(get("/alert-plugin-instances/verify-name") - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testListPaging() throws Exception { - //Given - Result result = JSONUtils.parseObject("{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}", Result.class); - + // Given + Result result = JSONUtils.parseObject( + "{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}", + Result.class); + final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginDefineId", String.valueOf(pluginDefineId)); paramsMap.add("searchVal", "searchVal"); paramsMap.add("pageNo", String.valueOf(1)); paramsMap.add("pageSize", String.valueOf(10)); - + when(alertPluginInstanceService.listPaging(eq(user), eq("searchVal"), eq(1), eq(10))) .thenReturn(result); - - //When + + // When final MvcResult mvcResult = mockMvc.perform(get("/alert-plugin-instances") - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testListPagingResultFalse() throws Exception { - //Given - final Result expectResponseContent = JSONUtils.parseObject("{\"code\":10001,\"msg\":\"request parameter pageNo is not valid\",\"data\":null,\"success\":false,\"failed\":true}", Result.class); - + // Given + final Result expectResponseContent = JSONUtils.parseObject( + "{\"code\":10001,\"msg\":\"request parameter pageNo is not valid\",\"data\":null,\"success\":false,\"failed\":true}", + Result.class); + final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginDefineId", String.valueOf(pluginDefineId)); paramsMap.add("searchVal", "searchVal"); paramsMap.add("pageNo", String.valueOf(0)); paramsMap.add("pageSize", String.valueOf(0)); - - //When + + // When final MvcResult mvcResult = mockMvc.perform(get("/alert-plugin-instances") - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - //Then - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + // Then + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AuditLogControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AuditLogControllerTest.java index 76ec2f77f8..c5eb6c9eef 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AuditLogControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AuditLogControllerTest.java @@ -25,8 +25,8 @@ import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -55,7 +55,7 @@ public class AuditLogControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ClusterControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ClusterControllerTest.java index 8ee52f8664..5c6088d649 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ClusterControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ClusterControllerTest.java @@ -26,10 +26,10 @@ import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.After; -import org.junit.Assert; -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; import org.springframework.http.MediaType; @@ -41,19 +41,20 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Preconditions; public class ClusterControllerTest extends AbstractControllerTest { + public static final String clusterName = "Cluster1"; public static final String config = "{\"k8s\":\"apiVersion: v1\"}"; public static final String desc = "this is cluster description"; private static final Logger logger = LoggerFactory.getLogger(ClusterControllerTest.class); private String clusterCode; - @Before + @BeforeEach public void before() throws Exception { testCreateCluster(); } @Override - @After + @AfterEach public void after() throws Exception { testDeleteCluster(); } @@ -66,17 +67,18 @@ public class ClusterControllerTest extends AbstractControllerTest { paramsMap.add("description", desc); MvcResult mvcResult = mockMvc.perform(post("/cluster/create") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isCreated()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); - - Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference>() { - }); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isCreated()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); + + Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), + new TypeReference>() { + }); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); - Assert.assertNotNull(result.getData()); + Assertions.assertTrue(result != null && result.isSuccess()); + Assertions.assertNotNull(result.getData()); logger.info("create cluster return result:{}", mvcResult.getResponse().getContentAsString()); clusterCode = (String) result.getData(); @@ -91,15 +93,15 @@ public class ClusterControllerTest extends AbstractControllerTest { paramsMap.add("desc", "the test cluster update"); MvcResult mvcResult = mockMvc.perform(post("/cluster/update") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("update cluster return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -110,17 +112,18 @@ public class ClusterControllerTest extends AbstractControllerTest { paramsMap.add("clusterCode", clusterCode); MvcResult mvcResult = mockMvc.perform(get("/cluster/query-by-code") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info(mvcResult.getResponse().getContentAsString()); - logger.info("query cluster by id :{}, return result:{}", clusterCode, mvcResult.getResponse().getContentAsString()); + logger.info("query cluster by id :{}, return result:{}", clusterCode, + mvcResult.getResponse().getContentAsString()); } @@ -132,15 +135,15 @@ public class ClusterControllerTest extends AbstractControllerTest { paramsMap.add("pageNo", "2"); MvcResult mvcResult = mockMvc.perform(get("/cluster/list-paging") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("query list-paging cluster return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -149,15 +152,15 @@ public class ClusterControllerTest extends AbstractControllerTest { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); MvcResult mvcResult = mockMvc.perform(get("/cluster/query-cluster-list") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("query all cluster return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -168,15 +171,15 @@ public class ClusterControllerTest extends AbstractControllerTest { paramsMap.add("clusterName", clusterName); MvcResult mvcResult = mockMvc.perform(post("/cluster/verify-cluster") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result.isStatus(Status.CLUSTER_NAME_EXISTS)); + Assertions.assertTrue(result.isStatus(Status.CLUSTER_NAME_EXISTS)); logger.info("verify cluster return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -188,15 +191,15 @@ public class ClusterControllerTest extends AbstractControllerTest { paramsMap.add("clusterCode", clusterCode); MvcResult mvcResult = mockMvc.perform(post("/cluster/delete") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("delete cluster return result:{}", mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java index 66e9b9ce0b..ca59107c14 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java @@ -30,7 +30,7 @@ import org.apache.dolphinscheduler.dao.mapper.ProjectMapper; import java.util.Date; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataQualityControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataQualityControllerTest.java index 3b285a6206..ea18a7f7da 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataQualityControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataQualityControllerTest.java @@ -37,19 +37,19 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -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; /** * process definition controller test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) public class DataQualityControllerTest { @InjectMocks @@ -63,7 +63,7 @@ public class DataQualityControllerTest { protected User user; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -83,7 +83,7 @@ public class DataQualityControllerTest { Mockito.when(dqRuleService.getRuleFormCreateJsonById(1)).thenReturn(result); Result response = dataQualityController.getRuleFormCreateJsonById(1); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } private void putMsg(Map result, Status status, Object... statusParams) { @@ -128,7 +128,7 @@ public class DataQualityControllerTest { String start = "2020-01-01 00:00:00"; String end = "2020-01-02 00:00:00"; - PageInfo pageInfo = new PageInfo<>(1,10); + PageInfo pageInfo = new PageInfo<>(1, 10); pageInfo.setTotal(10); pageInfo.setTotalList(getRuleList()); @@ -137,10 +137,10 @@ public class DataQualityControllerTest { putMsg(result, Status.SUCCESS); when(dqRuleService.queryRuleListPaging( - user, searchVal, ruleType, start, end,1, 10)).thenReturn(result); + user, searchVal, ruleType, start, end, 1, 10)).thenReturn(result); - Result response = dataQualityController.queryRuleListPaging(user, searchVal, ruleType,start,end,1,10); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Result response = dataQualityController.queryRuleListPaging(user, searchVal, ruleType, start, end, 1, 10); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -153,7 +153,7 @@ public class DataQualityControllerTest { when(dqRuleService.queryAllRuleList()).thenReturn(result); Result response = dataQualityController.queryRuleList(); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -164,7 +164,7 @@ public class DataQualityControllerTest { String start = "2020-01-01 00:00:00"; String end = "2020-01-02 00:00:00"; - PageInfo pageInfo = new PageInfo<>(1,10); + PageInfo pageInfo = new PageInfo<>(1, 10); pageInfo.setTotal(10); Result result = new Result(); @@ -172,9 +172,10 @@ public class DataQualityControllerTest { putMsg(result, Status.SUCCESS); when(dqExecuteResultService.queryResultListPaging( - user, searchVal, 0,ruleType, start, end,1, 10)).thenReturn(result); + user, searchVal, 0, ruleType, start, end, 1, 10)).thenReturn(result); - Result response = dataQualityController.queryExecuteResultListPaging(user, searchVal, ruleType,0,start,end,1,10); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Result response = + dataQualityController.queryExecuteResultListPaging(user, searchVal, ruleType, 0, start, end, 1, 10); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataSourceControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataSourceControllerTest.java index d5aa55333c..b620c2745a 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataSourceControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataSourceControllerTest.java @@ -30,11 +30,11 @@ import org.apache.dolphinscheduler.common.utils.JSONUtils; import java.util.HashMap; -import org.junit.Assert; -import org.junit.Ignore; -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.Disabled; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.slf4j.Logger; @@ -48,6 +48,7 @@ import org.springframework.util.MultiValueMap; * data source controller test */ public class DataSourceControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(DataSourceControllerTest.class); @BeforeEach @@ -60,193 +61,193 @@ public class DataSourceControllerTest extends AbstractControllerTest { after(); } - @Ignore("unknown yourself connection information") + @Disabled("unknown yourself connection information") @Test public void testCreateDataSource() throws Exception { HashMap paramsMap = new HashMap<>(); - paramsMap.put("name","mysql"); - paramsMap.put("node","mysql data source test"); - paramsMap.put("type","mysql"); - paramsMap.put("host","127.0.0.1"); - paramsMap.put("port",3306); - paramsMap.put("database","mysql"); - paramsMap.put("userName","root"); - paramsMap.put("password","123456"); - paramsMap.put("other",new HashMap<>()); - paramsMap.put("testFlag",1); - paramsMap.put("bindTestId",null); + paramsMap.put("name", "mysql"); + paramsMap.put("node", "mysql data source test"); + paramsMap.put("type", "mysql"); + paramsMap.put("host", "127.0.0.1"); + paramsMap.put("port", 3306); + paramsMap.put("database", "mysql"); + paramsMap.put("userName", "root"); + paramsMap.put("password", "123456"); + paramsMap.put("other", new HashMap<>()); + paramsMap.put("testFlag", 1); + paramsMap.put("bindTestId", null); MvcResult mvcResult = mockMvc.perform(post("/datasources") .header("sessionId", sessionId) .contentType(MediaType.APPLICATION_JSON) .content(JSONUtils.toJsonString(paramsMap))) - .andExpect(status().isCreated()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isCreated()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } - @Ignore("unknown yourself connection information") + @Disabled("unknown yourself connection information") @Test public void testUpdateDataSource() throws Exception { HashMap paramsMap = new HashMap<>(); - paramsMap.put("id",2); - paramsMap.put("name","mysql"); - paramsMap.put("node","mysql data source test"); - paramsMap.put("type","mysql"); - paramsMap.put("host","192.168.xxxx.xx"); - paramsMap.put("port",3306); - paramsMap.put("principal",""); - paramsMap.put("database","dolphinscheduler"); - paramsMap.put("userName","root"); - paramsMap.put("password","root@123"); - paramsMap.put("other",new HashMap<>()); - paramsMap.put("testFlag",0); - paramsMap.put("bindTestId",1); + paramsMap.put("id", 2); + paramsMap.put("name", "mysql"); + paramsMap.put("node", "mysql data source test"); + paramsMap.put("type", "mysql"); + paramsMap.put("host", "192.168.xxxx.xx"); + paramsMap.put("port", 3306); + paramsMap.put("principal", ""); + paramsMap.put("database", "dolphinscheduler"); + paramsMap.put("userName", "root"); + paramsMap.put("password", "root@123"); + paramsMap.put("other", new HashMap<>()); + paramsMap.put("testFlag", 0); + paramsMap.put("bindTestId", 1); MvcResult mvcResult = mockMvc.perform(put("/datasources/2") .header("sessionId", sessionId) .content(JSONUtils.toJsonString(paramsMap))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } - @Ignore("unknown you datasources id") + @Disabled("unknown you datasources id") @Test public void testQueryDataSource() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/datasources/2") .header("sessionId", sessionId)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @ParameterizedTest @CsvSource({ - "type, MYSQL" + "type, MYSQL" }) public void testQueryDataSourceList(String key, String dbType) throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add(key,dbType); + paramsMap.add(key, dbType); paramsMap.add("testFlag", "0"); MvcResult mvcResult = mockMvc.perform(get("/datasources/list") .header("sessionId", sessionId) .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @Test public void testQueryDataSourceListPaging() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("searchVal","mysql"); - paramsMap.add("pageNo","1"); - paramsMap.add("pageSize","1"); + paramsMap.add("searchVal", "mysql"); + paramsMap.add("pageNo", "1"); + paramsMap.add("pageSize", "1"); MvcResult mvcResult = mockMvc.perform(get("/datasources") .header("sessionId", sessionId) .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } - @Ignore("unknown yourself connection information") + @Disabled("unknown yourself connection information") @Test public void testConnectDataSource() throws Exception { HashMap paramsMap = new HashMap<>(); - paramsMap.put("name","mysql data source"); - paramsMap.put("type","mysql"); - paramsMap.put("host","127.0.0.1"); - paramsMap.put("port",3306); - paramsMap.put("database","mysql"); - paramsMap.put("userName","root"); - paramsMap.put("password","123456"); - paramsMap.put("other",null); - paramsMap.put("testFlag",1); - paramsMap.put("bindTestId",null); + paramsMap.put("name", "mysql data source"); + paramsMap.put("type", "mysql"); + paramsMap.put("host", "127.0.0.1"); + paramsMap.put("port", 3306); + paramsMap.put("database", "mysql"); + paramsMap.put("userName", "root"); + paramsMap.put("password", "123456"); + paramsMap.put("other", null); + paramsMap.put("testFlag", 1); + paramsMap.put("bindTestId", null); MvcResult mvcResult = mockMvc.perform(post("/datasources/connect") .header("sessionId", sessionId) .content(JSONUtils.toJsonString(paramsMap))) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } - @Ignore("unknown your datasource id") + @Disabled("unknown your datasource id") @Test public void testConnectionTest() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/datasources/2/connect-test") .header("sessionId", sessionId)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @ParameterizedTest @CsvSource({ - "name, sourceName" + "name, sourceName" }) public void testVerifyDataSourceName(String key, String dbType) throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add(key,dbType); + paramsMap.add(key, dbType); MvcResult mvcResult = mockMvc.perform(get("/datasources/verify-name") .header("sessionId", sessionId) .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @Test public void testAuthedDatasource() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("userId","2"); + paramsMap.add("userId", "2"); MvcResult mvcResult = mockMvc.perform(get("/datasources/authed-datasource") .header("sessionId", sessionId) .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @Test public void testUnauthDatasource() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("userId","2"); + paramsMap.add("userId", "2"); MvcResult mvcResult = mockMvc.perform(get("/datasources/unauth-datasource") .header("sessionId", sessionId) .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -254,24 +255,24 @@ public class DataSourceControllerTest extends AbstractControllerTest { public void testGetKerberosStartupState() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/datasources/kerberos-startup-state") .header("sessionId", sessionId)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } - @Ignore("unknown your datasource id") + @Disabled("unknown your datasource id") @Test public void testDelete() throws Exception { MvcResult mvcResult = mockMvc.perform(delete("/datasources/2") .header("sessionId", sessionId)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/EnvironmentControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/EnvironmentControllerTest.java index c6d20f6f24..4d74765773 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/EnvironmentControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/EnvironmentControllerTest.java @@ -26,10 +26,10 @@ import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.After; -import org.junit.Assert; -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; import org.springframework.http.MediaType; @@ -41,6 +41,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.google.common.base.Preconditions; public class EnvironmentControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(EnvironmentControllerTest.class); private String environmentCode; @@ -51,13 +52,13 @@ public class EnvironmentControllerTest extends AbstractControllerTest { public static final String desc = "this is environment description"; - @Before + @BeforeEach public void before() throws Exception { testCreateEnvironment(); } @Override - @After + @AfterEach public void after() throws Exception { testDeleteEnvironment(); } @@ -65,9 +66,9 @@ public class EnvironmentControllerTest extends AbstractControllerTest { public void testCreateEnvironment() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("name",environmentName); - paramsMap.add("config",config); - paramsMap.add("description",desc); + paramsMap.add("name", environmentName); + paramsMap.add("config", config); + paramsMap.add("description", desc); MvcResult mvcResult = mockMvc.perform(post("/environment/create") .header(SESSION_ID, sessionId) @@ -76,22 +77,24 @@ public class EnvironmentControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference>() {}); + Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), + new TypeReference>() { + }); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); - Assert.assertNotNull(result.getData()); + Assertions.assertTrue(result != null && result.isSuccess()); + Assertions.assertNotNull(result.getData()); logger.info("create environment return result:{}", mvcResult.getResponse().getContentAsString()); - environmentCode = (String)result.getData(); + environmentCode = (String) result.getData(); } @Test public void testUpdateEnvironment() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("code", environmentCode); - paramsMap.add("name","environment_test_update"); - paramsMap.add("config","this is config content"); - paramsMap.add("desc","the test environment update"); + paramsMap.add("name", "environment_test_update"); + paramsMap.add("config", "this is config content"); + paramsMap.add("desc", "the test environment update"); MvcResult mvcResult = mockMvc.perform(post("/environment/update") .header(SESSION_ID, sessionId) @@ -102,7 +105,7 @@ public class EnvironmentControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("update environment return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -121,18 +124,19 @@ public class EnvironmentControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info(mvcResult.getResponse().getContentAsString()); - logger.info("query environment by id :{}, return result:{}", environmentCode, mvcResult.getResponse().getContentAsString()); + logger.info("query environment by id :{}, return result:{}", environmentCode, + mvcResult.getResponse().getContentAsString()); } @Test public void testQueryEnvironmentListPaging() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("searchVal","test"); - paramsMap.add("pageSize","2"); - paramsMap.add("pageNo","2"); + paramsMap.add("searchVal", "test"); + paramsMap.add("pageSize", "2"); + paramsMap.add("pageNo", "2"); MvcResult mvcResult = mockMvc.perform(get("/environment/list-paging") .header(SESSION_ID, sessionId) @@ -143,7 +147,7 @@ public class EnvironmentControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("query list-paging environment return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -160,7 +164,7 @@ public class EnvironmentControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("query all environment return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -168,7 +172,7 @@ public class EnvironmentControllerTest extends AbstractControllerTest { @Test public void testVerifyEnvironment() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("environmentName",environmentName); + paramsMap.add("environmentName", environmentName); MvcResult mvcResult = mockMvc.perform(post("/environment/verify-environment") .header(SESSION_ID, sessionId) @@ -179,7 +183,7 @@ public class EnvironmentControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result.isStatus(Status.ENVIRONMENT_NAME_EXISTS)); + Assertions.assertTrue(result.isStatus(Status.ENVIRONMENT_NAME_EXISTS)); logger.info("verify environment return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -199,7 +203,7 @@ public class EnvironmentControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info(result.toString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("delete environment return result:{}", mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ExecutorControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ExecutorControllerTest.java index fcfa068ae4..eb23031f5a 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ExecutorControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ExecutorControllerTest.java @@ -17,37 +17,46 @@ package org.apache.dolphinscheduler.api.controller; -import com.google.common.collect.ImmutableMap; -import com.google.gson.Gson; -import com.google.gson.JsonObject; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.apache.dolphinscheduler.api.enums.ExecuteType; import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.service.ExecutorService; import org.apache.dolphinscheduler.common.Constants; -import org.apache.dolphinscheduler.common.enums.*; +import org.apache.dolphinscheduler.common.enums.CommandType; +import org.apache.dolphinscheduler.common.enums.ComplementDependentMode; +import org.apache.dolphinscheduler.common.enums.FailureStrategy; +import org.apache.dolphinscheduler.common.enums.Priority; +import org.apache.dolphinscheduler.common.enums.RunMode; +import org.apache.dolphinscheduler.common.enums.TaskDependType; +import org.apache.dolphinscheduler.common.enums.WarningType; import org.apache.dolphinscheduler.dao.entity.User; -import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import java.util.HashMap; -import java.util.Map; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.google.common.collect.ImmutableMap; +import com.google.gson.Gson; +import com.google.gson.JsonObject; /** * executor controller test */ public class ExecutorControllerTest extends AbstractControllerTest { + final Gson gson = new Gson(); final long projectCode = 1L; final long processDefinitionCode = 2L; @@ -70,8 +79,8 @@ public class ExecutorControllerTest extends AbstractControllerTest { final ComplementDependentMode complementDependentMode = ComplementDependentMode.OFF_MODE; final JsonObject expectResponseContent = gson - .fromJson("{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}" - , JsonObject.class); + .fromJson("{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}", + JsonObject.class); final ImmutableMap executeServiceResult = ImmutableMap.of(Constants.STATUS, Status.SUCCESS, Constants.DATA_LIST, "Test Data"); @@ -81,7 +90,7 @@ public class ExecutorControllerTest extends AbstractControllerTest { @Test public void testStartProcessInstanceWithFullParams() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("processDefinitionCode", String.valueOf(processDefinitionCode)); paramsMap.add("scheduleTime", scheduleTime); @@ -102,19 +111,22 @@ public class ExecutorControllerTest extends AbstractControllerTest { paramsMap.add("testFlag", String.valueOf(testFlag)); when(executorService.execProcessInstance(any(User.class), eq(projectCode), eq(processDefinitionCode), - eq(scheduleTime), eq(execType), eq(failureStrategy), eq(startNodeList), eq(taskDependType), eq(warningType), + eq(scheduleTime), eq(execType), eq(failureStrategy), eq(startNodeList), eq(taskDependType), + eq(warningType), eq(warningGroupId), eq(runMode), eq(processInstancePriority), eq(workerGroup), eq(environmentCode), - eq(timeout), eq(startParams), eq(expectedParallelismNumber), eq(dryRun), eq(testFlag), eq(complementDependentMode))) - .thenReturn(executeServiceResult); + eq(timeout), eq(startParams), eq(expectedParallelismNumber), eq(dryRun), eq(testFlag), + eq(complementDependentMode))) + .thenReturn(executeServiceResult); - //When - final MvcResult mvcResult = mockMvc.perform(post("/projects/{projectCode}/executors/start-process-instance", projectCode) + // When + final MvcResult mvcResult = mockMvc + .perform(post("/projects/{projectCode}/executors/start-process-instance", projectCode) .header("sessionId", sessionId) .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - //Then + // Then final JsonObject actualResponseContent = gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); assertThat(actualResponseContent).isEqualTo(expectResponseContent); @@ -122,7 +134,7 @@ public class ExecutorControllerTest extends AbstractControllerTest { @Test public void testStartProcessInstanceWithoutTimeout() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("processDefinitionCode", String.valueOf(processDefinitionCode)); paramsMap.add("scheduleTime", scheduleTime); @@ -142,26 +154,30 @@ public class ExecutorControllerTest extends AbstractControllerTest { paramsMap.add("testFlag", String.valueOf(testFlag)); when(executorService.execProcessInstance(any(User.class), eq(projectCode), eq(processDefinitionCode), - eq(scheduleTime), eq(execType), eq(failureStrategy), eq(startNodeList), eq(taskDependType), eq(warningType), + eq(scheduleTime), eq(execType), eq(failureStrategy), eq(startNodeList), eq(taskDependType), + eq(warningType), eq(warningGroupId), eq(runMode), eq(processInstancePriority), eq(workerGroup), eq(environmentCode), - eq(Constants.MAX_TASK_TIMEOUT), eq(startParams), eq(expectedParallelismNumber), eq(dryRun), eq(testFlag), + eq(Constants.MAX_TASK_TIMEOUT), eq(startParams), eq(expectedParallelismNumber), eq(dryRun), + eq(testFlag), eq(complementDependentMode))).thenReturn(executeServiceResult); - //When - final MvcResult mvcResult = mockMvc.perform(post("/projects/{projectCode}/executors/start-process-instance", projectCode) + // When + final MvcResult mvcResult = mockMvc + .perform(post("/projects/{projectCode}/executors/start-process-instance", projectCode) .header("sessionId", sessionId) .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - //Then - final JsonObject actualResponseContent = gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); + // Then + final JsonObject actualResponseContent = + gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); assertThat(actualResponseContent).isEqualTo(expectResponseContent); } @Test public void testStartProcessInstanceWithoutStartParams() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("processDefinitionCode", String.valueOf(processDefinitionCode)); paramsMap.add("scheduleTime", scheduleTime); @@ -181,26 +197,29 @@ public class ExecutorControllerTest extends AbstractControllerTest { paramsMap.add("testFlag", String.valueOf(testFlag)); when(executorService.execProcessInstance(any(User.class), eq(projectCode), eq(processDefinitionCode), - eq(scheduleTime), eq(execType), eq(failureStrategy), eq(startNodeList), eq(taskDependType), eq(warningType), + eq(scheduleTime), eq(execType), eq(failureStrategy), eq(startNodeList), eq(taskDependType), + eq(warningType), eq(warningGroupId), eq(runMode), eq(processInstancePriority), eq(workerGroup), eq(environmentCode), eq(timeout), eq(null), eq(expectedParallelismNumber), eq(dryRun), eq(testFlag), eq(complementDependentMode))).thenReturn(executeServiceResult); - //When - final MvcResult mvcResult = mockMvc.perform(post("/projects/{projectCode}/executors/start-process-instance", projectCode) + // When + final MvcResult mvcResult = mockMvc + .perform(post("/projects/{projectCode}/executors/start-process-instance", projectCode) .header("sessionId", sessionId) .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - //Then - final JsonObject actualResponseContent = gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); + // Then + final JsonObject actualResponseContent = + gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); assertThat(actualResponseContent).isEqualTo(expectResponseContent); } @Test public void testStartProcessInstanceWithRequiredParams() throws Exception { - //Given + // Given final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("processDefinitionCode", String.valueOf(processDefinitionCode)); paramsMap.add("failureStrategy", String.valueOf(failureStrategy)); @@ -208,26 +227,28 @@ public class ExecutorControllerTest extends AbstractControllerTest { paramsMap.add("scheduleTime", scheduleTime); when(executorService.execProcessInstance(any(User.class), eq(projectCode), eq(processDefinitionCode), - eq(scheduleTime), eq(null), eq(failureStrategy), eq(null), eq(null), eq(warningType), - eq(null), eq(null), eq(null), eq("default"), eq(-1L), - eq(Constants.MAX_TASK_TIMEOUT), eq(null), eq(null), eq(0), eq(0), - eq(complementDependentMode))).thenReturn(executeServiceResult); + eq(scheduleTime), eq(null), eq(failureStrategy), eq(null), eq(null), eq(warningType), + eq(null), eq(null), eq(null), eq("default"), eq(-1L), + eq(Constants.MAX_TASK_TIMEOUT), eq(null), eq(null), eq(0), eq(0), + eq(complementDependentMode))).thenReturn(executeServiceResult); - //When - final MvcResult mvcResult = mockMvc.perform(post("/projects/{projectCode}/executors/start-process-instance", projectCode) + // When + final MvcResult mvcResult = mockMvc + .perform(post("/projects/{projectCode}/executors/start-process-instance", projectCode) .header("sessionId", sessionId) .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - //Then - final JsonObject actualResponseContent = gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); + // Then + final JsonObject actualResponseContent = + gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); assertThat(actualResponseContent).isEqualTo(expectResponseContent); } @Test public void testExecuteWithSuccessStatus() throws Exception { - //Given + // Given final ExecuteType executeType = ExecuteType.NONE; final int processInstanceId = 40; final long projectCode = 1113; @@ -239,38 +260,40 @@ public class ExecutorControllerTest extends AbstractControllerTest { executeServiceResult.put(Constants.DATA_LIST, "Test Data"); final JsonObject expectResponseContent = gson - .fromJson("{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}" - , JsonObject.class); + .fromJson("{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}", + JsonObject.class); when(executorService.execute(any(User.class), eq(projectCode), eq(processInstanceId), eq(ExecuteType.NONE))) .thenReturn(executeServiceResult); - //When + // When final MvcResult mvcResult = mockMvc.perform(post("/projects/{projectCode}/executors/execute", projectCode) - .header("sessionId", sessionId) - .params(paramsMap)) + .header("sessionId", sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - //Then - final JsonObject actualResponseContent = gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); + // Then + final JsonObject actualResponseContent = + gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); assertThat(actualResponseContent).isEqualTo(expectResponseContent); } @Test public void testStartCheckProcessDefinition() throws Exception { - //Given + // Given when(executorService.startCheckByProcessDefinedCode(processDefinitionCode)) .thenReturn(executeServiceResult); - //When + // When final MvcResult mvcResult = mockMvc.perform(post("/projects/{projectCode}/executors/start-check", projectCode) - .header(SESSION_ID, sessionId) - .param("processDefinitionCode", String.valueOf(processDefinitionCode))) + .header(SESSION_ID, sessionId) + .param("processDefinitionCode", String.valueOf(processDefinitionCode))) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - //Then - final JsonObject actualResponseContent = gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); + // Then + final JsonObject actualResponseContent = + gson.fromJson(mvcResult.getResponse().getContentAsString(), JsonObject.class); assertThat(actualResponseContent).isEqualTo(expectResponseContent); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/K8sNamespaceControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/K8sNamespaceControllerTest.java index 9631ab6d11..973b118396 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/K8sNamespaceControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/K8sNamespaceControllerTest.java @@ -28,8 +28,8 @@ import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; import org.apache.dolphinscheduler.dao.entity.User; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -54,13 +54,13 @@ public class K8sNamespaceControllerTest extends AbstractControllerTest { paramsMap.add("pageSize", "20"); MvcResult mvcResult = mockMvc.perform(get("/k8s-namespace") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -71,14 +71,15 @@ public class K8sNamespaceControllerTest extends AbstractControllerTest { paramsMap.add("clusterCode", "0"); MvcResult mvcResult = mockMvc.perform(post("/k8s-namespace") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isCreated()) //it can - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isCreated()) // it can + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue());//because we not have a k8s cluster in test env + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue());// because we not have a k8s + // cluster in test env logger.info("create queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -90,13 +91,13 @@ public class K8sNamespaceControllerTest extends AbstractControllerTest { paramsMap.add("tag", "flink"); MvcResult mvcResult = mockMvc.perform(put("/k8s-namespace/{id}", 1) - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isCreated()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isCreated()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("update queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -110,28 +111,28 @@ public class K8sNamespaceControllerTest extends AbstractControllerTest { // success MvcResult mvcResult = mockMvc.perform(post("/k8s-namespace/verify") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); logger.info("verify namespace return result:{}", mvcResult.getResponse().getContentAsString()); - //error + // error paramsMap.clear(); paramsMap.add("namespace", null); paramsMap.add("clusterCode", "100"); mvcResult = mockMvc.perform(post("/k8s-namespace/verify") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.VERIFY_K8S_NAMESPACE_ERROR.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.VERIFY_K8S_NAMESPACE_ERROR.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); logger.info("verify namespace return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -142,14 +143,15 @@ public class K8sNamespaceControllerTest extends AbstractControllerTest { paramsMap.add("id", "1"); MvcResult mvcResult = mockMvc.perform(post("/k8s-namespace/delete") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue());//there is no k8s cluster in test env + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue());// there is no k8s cluster in + // test env logger.info(mvcResult.getResponse().getContentAsString()); } @@ -160,14 +162,14 @@ public class K8sNamespaceControllerTest extends AbstractControllerTest { paramsMap.add("userId", "1"); MvcResult mvcResult = mockMvc.perform(get("/k8s-namespace/unauth-namespace") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -177,14 +179,14 @@ public class K8sNamespaceControllerTest extends AbstractControllerTest { paramsMap.add("userId", "1"); MvcResult mvcResult = mockMvc.perform(get("/k8s-namespace/authed-namespace") - .header(SESSION_ID, sessionId) - .params(paramsMap)) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + .params(paramsMap)) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoggerControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoggerControllerTest.java index d7e780c1a9..ac699683be 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoggerControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoggerControllerTest.java @@ -25,9 +25,9 @@ import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -38,17 +38,18 @@ import org.springframework.util.MultiValueMap; /** * logger controller test */ -@Ignore +@Disabled public class LoggerControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(LoggerControllerTest.class); @Test public void testQueryLog() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("taskInstId","1501"); - paramsMap.add("skipLineNum","0"); - paramsMap.add("limit","1000"); + paramsMap.add("taskInstId", "1501"); + paramsMap.add("skipLineNum", "0"); + paramsMap.add("limit", "1000"); MvcResult mvcResult = mockMvc.perform(get("/log/detail") .header("sessionId", sessionId) @@ -58,7 +59,7 @@ public class LoggerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -66,16 +67,16 @@ public class LoggerControllerTest extends AbstractControllerTest { public void testDownloadTaskLog() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("taskInstId","1501"); + paramsMap.add("taskInstId", "1501"); MvcResult mvcResult = mockMvc.perform(get("/log/download-log") .header("sessionId", sessionId) .params(paramsMap)) .andExpect(status().isOk()) - /*.andExpect(content().contentType(MediaType.APPLICATION_JSON))*/ + /* .andExpect(content().contentType(MediaType.APPLICATION_JSON)) */ .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java index 0e4cad9c27..58f0ff862f 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java @@ -28,8 +28,8 @@ import org.apache.dolphinscheduler.common.utils.JSONUtils; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -41,6 +41,7 @@ import org.springframework.util.MultiValueMap; * login controller test */ public class LoginControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(LoginControllerTest.class); @Test @@ -56,11 +57,11 @@ public class LoginControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); Map data = (Map) result.getData(); - Assert.assertEquals(Constants.SECURITY_CONFIG_TYPE_PASSWORD,data.get(Constants.SECURITY_CONFIG_TYPE)); - Assert.assertNotEquals(Constants.SECURITY_CONFIG_TYPE_LDAP,data.get(Constants.SECURITY_CONFIG_TYPE)); + Assertions.assertEquals(Constants.SECURITY_CONFIG_TYPE_PASSWORD, data.get(Constants.SECURITY_CONFIG_TYPE)); + Assertions.assertNotEquals(Constants.SECURITY_CONFIG_TYPE_LDAP, data.get(Constants.SECURITY_CONFIG_TYPE)); } @Test @@ -75,7 +76,7 @@ public class LoginControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/MonitorControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/MonitorControllerTest.java index ea22ac117d..737faa1636 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/MonitorControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/MonitorControllerTest.java @@ -25,8 +25,8 @@ import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -36,22 +36,23 @@ import org.springframework.test.web.servlet.MvcResult; * monitor controller test */ public class MonitorControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(MonitorControllerTest.class); @Test public void testListMaster() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/monitor/masters") - .header(SESSION_ID, sessionId) - /* .param("type", ResourceType.FILE.name())*/) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + /* .param("type", ResourceType.FILE.name()) */) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); result.getCode().equals(Status.SUCCESS.getCode()); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -59,32 +60,32 @@ public class MonitorControllerTest extends AbstractControllerTest { public void testListWorker() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/monitor/workers") - .header(SESSION_ID, sessionId) - /* .param("type", ResourceType.FILE.name())*/) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + /* .param("type", ResourceType.FILE.name()) */) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); result.getCode().equals(Status.SUCCESS.getCode()); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @Test public void testQueryDatabaseState() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/monitor/databases") - .header(SESSION_ID, sessionId) - /* .param("type", ResourceType.FILE.name())*/) - .andExpect(status().isOk()) - .andExpect(content().contentType(MediaType.APPLICATION_JSON)) - .andReturn(); + .header(SESSION_ID, sessionId) + /* .param("type", ResourceType.FILE.name()) */) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); result.getCode().equals(Status.SUCCESS.getCode()); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessDefinitionControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessDefinitionControllerTest.java index 3ae23d9fc3..f97b18b400 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessDefinitionControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessDefinitionControllerTest.java @@ -37,21 +37,20 @@ import java.util.Map; import javax.servlet.http.HttpServletResponse; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -import org.junit.runner.RunWith; +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 org.springframework.mock.web.MockHttpServletResponse; /** * process definition controller test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) public class ProcessDefinitionControllerTest { @InjectMocks @@ -62,7 +61,7 @@ public class ProcessDefinitionControllerTest { protected User user; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -106,7 +105,7 @@ public class ProcessDefinitionControllerTest { processDefinitionController.createProcessDefinition(user, projectCode, name, description, globalParams, locations, timeout, tenantCode, relationJson, taskDefinitionJson, "", ProcessExecutionTypeEnum.PARALLEL); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } private void putMsg(Map result, Status status, Object... statusParams) { @@ -138,7 +137,7 @@ public class ProcessDefinitionControllerTest { .thenReturn(result); Result response = processDefinitionController.verifyProcessDefinitionName(user, projectCode, name, 0); - Assert.assertTrue(response.isStatus(Status.PROCESS_DEFINITION_NAME_EXIST)); + Assertions.assertTrue(response.isStatus(Status.PROCESS_DEFINITION_NAME_EXIST)); } @Test @@ -176,7 +175,7 @@ public class ProcessDefinitionControllerTest { description, globalParams, locations, timeout, tenantCode, relationJson, taskDefinitionJson, "", ProcessExecutionTypeEnum.PARALLEL, ReleaseState.OFFLINE); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -190,7 +189,7 @@ public class ProcessDefinitionControllerTest { .thenReturn(result); Result response = processDefinitionController.releaseProcessDefinition(user, projectCode, id, ReleaseState.OFFLINE); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -215,7 +214,7 @@ public class ProcessDefinitionControllerTest { Mockito.when(processDefinitionService.queryProcessDefinitionByCode(user, projectCode, code)).thenReturn(result); Result response = processDefinitionController.queryProcessDefinitionByCode(user, projectCode, code); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -231,7 +230,7 @@ public class ProcessDefinitionControllerTest { .thenReturn(result); Result response = processDefinitionController.copyProcessDefinition(user, projectCode, code, targetProjectCode); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -247,7 +246,7 @@ public class ProcessDefinitionControllerTest { .thenReturn(result); Result response = processDefinitionController.moveProcessDefinition(user, projectCode, id, targetProjectCode); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -262,7 +261,7 @@ public class ProcessDefinitionControllerTest { Mockito.when(processDefinitionService.queryProcessDefinitionList(user, projectCode)).thenReturn(result); Result response = processDefinitionController.queryProcessDefinitionList(user, projectCode); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } public List getDefinitionList() { @@ -317,7 +316,7 @@ public class ProcessDefinitionControllerTest { .thenReturn(result); Result response = processDefinitionController.getNodeListByDefinitionCode(user, projectCode, code); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -332,7 +331,7 @@ public class ProcessDefinitionControllerTest { .thenReturn(result); Result response = processDefinitionController.getNodeListMapByDefinitionCodes(user, projectCode, codeList); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -345,7 +344,7 @@ public class ProcessDefinitionControllerTest { .thenReturn(result); Result response = processDefinitionController.queryAllProcessDefinitionByProjectCode(user, projectCode); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -360,7 +359,7 @@ public class ProcessDefinitionControllerTest { Mockito.when(processDefinitionService.viewTree(user, projectCode, processId, limit)).thenReturn(result); Result response = processDefinitionController.viewTree(user, projectCode, processId, limit); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -378,7 +377,7 @@ public class ProcessDefinitionControllerTest { Result> response = processDefinitionController .queryProcessDefinitionListPaging(user, projectCode, searchVal, "", userId, pageNo, pageSize); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -405,7 +404,7 @@ public class ProcessDefinitionControllerTest { Result result = processDefinitionController.queryProcessDefinitionVersions( user, projectCode, 1, 10, 1); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); } @Test @@ -417,7 +416,7 @@ public class ProcessDefinitionControllerTest { .thenReturn(resultMap); Result result = processDefinitionController.switchProcessDefinitionVersion(user, projectCode, 1, 10); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); } @Test @@ -429,7 +428,7 @@ public class ProcessDefinitionControllerTest { user, projectCode, 1, 10)).thenReturn(resultMap); Result result = processDefinitionController.deleteProcessDefinitionVersion( user, projectCode, 1, 10); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java index 56cbee73dc..73a0656c18 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java @@ -34,8 +34,8 @@ import org.apache.dolphinscheduler.common.utils.JSONUtils; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; @@ -78,8 +78,8 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -97,8 +97,8 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.PROJECT_NOT_FOUND.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND.getCode(), result.getCode().intValue()); } @Test @@ -134,8 +134,8 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -152,8 +152,8 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -172,8 +172,8 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.TASK_INSTANCE_NOT_EXISTS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.TASK_INSTANCE_NOT_EXISTS.getCode(), result.getCode().intValue()); } @Test @@ -193,8 +193,9 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.PROCESS_INSTANCE_NOT_SUB_PROCESS_INSTANCE.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.PROCESS_INSTANCE_NOT_SUB_PROCESS_INSTANCE.getCode(), + result.getCode().intValue()); } @Test @@ -209,8 +210,8 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -228,8 +229,8 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -248,7 +249,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.DELETE_PROCESS_INSTANCE_BY_ID_ERROR.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.DELETE_PROCESS_INSTANCE_BY_ID_ERROR.getCode(), result.getCode().intValue()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java index ca675812e0..4749ab6c21 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java @@ -30,8 +30,8 @@ import org.apache.dolphinscheduler.common.utils.JSONUtils; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; @@ -61,8 +61,8 @@ public class ProcessTaskRelationControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -81,7 +81,7 @@ public class ProcessTaskRelationControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectControllerTest.java index 650ca2a3fc..647dc14533 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectControllerTest.java @@ -29,19 +29,22 @@ import org.apache.dolphinscheduler.dao.mapper.ProjectMapper; import java.text.MessageFormat; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** * project controller test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ProjectControllerTest { protected User user; @@ -55,7 +58,7 @@ public class ProjectControllerTest { @Mock private ProjectMapper projectMapper; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -75,7 +78,7 @@ public class ProjectControllerTest { String userName = "jack"; Mockito.when(projectService.update(user, projectCode, projectName, desc, userName)).thenReturn(result); Result response = projectController.updateProject(user, projectCode, projectName, desc, userName); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -86,7 +89,7 @@ public class ProjectControllerTest { Mockito.when(projectMapper.queryByCode(projectCode)).thenReturn(getProject()); Mockito.when(projectService.queryByCode(user, projectCode)).thenReturn(result); Result response = projectController.queryProjectByCode(user, projectCode); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -100,7 +103,7 @@ public class ProjectControllerTest { Mockito.when(projectService.queryProjectListPaging(user, pageSize, pageNo, searchVal)).thenReturn(result); Result response = projectController.queryProjectListPaging(user, searchVal, pageSize, pageNo); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -109,7 +112,7 @@ public class ProjectControllerTest { putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryUnauthorizedProject(user, 2)).thenReturn(result); Result response = projectController.queryUnauthorizedProject(user, 2); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -118,7 +121,7 @@ public class ProjectControllerTest { putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryAuthorizedProject(user, 2)).thenReturn(result); Result response = projectController.queryAuthorizedProject(user, 2); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -128,7 +131,7 @@ public class ProjectControllerTest { Mockito.when(this.projectService.queryAuthorizedUser(this.user, 3682329499136L)).thenReturn(result); Result response = this.projectController.queryAuthorizedUser(this.user, 3682329499136L); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -139,7 +142,7 @@ public class ProjectControllerTest { putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryAllProjectList(user)).thenReturn(result); Result response = projectController.queryAllProjectList(user); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test public void testQueryAllProjectListForDependent() { @@ -149,7 +152,7 @@ public class ProjectControllerTest { putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryAllProjectListForDependent()).thenReturn(result); Result response = projectController.queryAllProjectListForDependent(user); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } private Project getProject() { Project project = new Project(); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectV2ControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectV2ControllerTest.java index eafc3794a4..7c1260a1a0 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectV2ControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectV2ControllerTest.java @@ -33,19 +33,22 @@ import org.apache.dolphinscheduler.dao.mapper.ProjectMapper; import java.text.MessageFormat; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** * project v2 controller test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ProjectV2ControllerTest { protected User user; @@ -56,7 +59,7 @@ public class ProjectV2ControllerTest { @Mock private ProjectMapper projectMapper; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -76,9 +79,9 @@ public class ProjectV2ControllerTest { projectUpdateReq.setDescription("james lbj"); projectUpdateReq.setUserName("admin"); Mockito.when(projectService.update(user, projectCode, projectUpdateReq.getProjectName(), - projectUpdateReq.getDescription(), projectUpdateReq.getUserName())).thenReturn(result); + projectUpdateReq.getDescription(), projectUpdateReq.getUserName())).thenReturn(result); Result response = projectV2Controller.updateProject(user, projectCode, projectUpdateReq); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -89,7 +92,7 @@ public class ProjectV2ControllerTest { Mockito.when(projectMapper.queryByCode(projectCode)).thenReturn(getProject()); Mockito.when(projectService.queryByCode(user, projectCode)).thenReturn(result); ProjectQueryResponse response = projectV2Controller.queryProjectByCode(user, projectCode); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -101,9 +104,9 @@ public class ProjectV2ControllerTest { Result result = Result.success(new PageInfo(1, 10)); Mockito.when(projectService.queryProjectListPaging(user, projectQueryReq.getPageSize(), - projectQueryReq.getPageNo(), projectQueryReq.getSearchVal())).thenReturn(result); + projectQueryReq.getPageNo(), projectQueryReq.getSearchVal())).thenReturn(result); Result response = projectV2Controller.queryProjectListPaging(user, projectQueryReq); - Assert.assertTrue(response != null && response.isSuccess()); + Assertions.assertTrue(response != null && response.isSuccess()); } @Test @@ -112,7 +115,7 @@ public class ProjectV2ControllerTest { putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryUnauthorizedProject(user, 2)).thenReturn(result); ProjectListResponse response = projectV2Controller.queryUnauthorizedProject(user, 2); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -121,7 +124,7 @@ public class ProjectV2ControllerTest { putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryAuthorizedProject(user, 2)).thenReturn(result); ProjectListResponse response = projectV2Controller.queryAuthorizedProject(user, 2); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -131,7 +134,7 @@ public class ProjectV2ControllerTest { Mockito.when(this.projectService.queryAuthorizedUser(this.user, 3682329499136L)).thenReturn(result); Result response = this.projectV2Controller.queryAuthorizedUser(this.user, 3682329499136L); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test @@ -142,7 +145,7 @@ public class ProjectV2ControllerTest { putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryAllProjectList(user)).thenReturn(result); Result response = projectV2Controller.queryAllProjectList(user); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test public void testQueryAllProjectListForDependent() { @@ -152,7 +155,7 @@ public class ProjectV2ControllerTest { putMsg(result, Status.SUCCESS); Mockito.when(projectService.queryAllProjectListForDependent()).thenReturn(result); Result response = projectV2Controller.queryAllProjectListForDependent(user); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } private Project getProject() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueControllerTest.java index c147f84a93..e2311a25ae 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueControllerTest.java @@ -27,8 +27,8 @@ import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -40,6 +40,7 @@ import org.springframework.util.MultiValueMap; * queue controller test */ public class QueueControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(QueueControllerTest.class); private static final String QUEUE_CREATE_NAME = "queue_create"; @@ -58,17 +59,17 @@ public class QueueControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("query list queue return result:{}", mvcResult.getResponse().getContentAsString()); } @Test public void testQueryQueueListPagingEmpty() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("searchVal",""); - paramsMap.add("pageNo","1"); - paramsMap.add("pageSize","20"); + paramsMap.add("searchVal", ""); + paramsMap.add("pageNo", "1"); + paramsMap.add("pageSize", "20"); MvcResult mvcResult = mockMvc.perform(get("/queues") .header(SESSION_ID, sessionId) @@ -78,8 +79,8 @@ public class QueueControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("query list-paging queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -97,15 +98,15 @@ public class QueueControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("create queue return result:{}", mvcResult.getResponse().getContentAsString()); } @Test public void testUpdateQueue() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("id","1"); + paramsMap.add("id", "1"); paramsMap.add("queue", QUEUE_MODIFY_NAME); paramsMap.add("queueName", QUEUE_NAME_MODIFY_NAME); @@ -117,8 +118,8 @@ public class QueueControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("update queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -139,8 +140,8 @@ public class QueueControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.QUEUE_VALUE_EXIST.getCode(),result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.QUEUE_VALUE_EXIST.getCode(), result.getCode().intValue()); // queue name exist paramsMap.clear(); @@ -148,15 +149,15 @@ public class QueueControllerTest extends AbstractControllerTest { paramsMap.add("queueName", QUEUE_NAME_CREATE_NAME); mvcResult = mockMvc.perform(post("/queues/verify") - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.QUEUE_NAME_EXIST.getCode(),result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.QUEUE_NAME_EXIST.getCode(), result.getCode().intValue()); // success paramsMap.clear(); @@ -171,8 +172,8 @@ public class QueueControllerTest extends AbstractControllerTest { .andReturn(); result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); logger.info("verify queue return result:{}", mvcResult.getResponse().getContentAsString()); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueV2ControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueV2ControllerTest.java index e4235ad7f2..1dd11a9d9e 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueV2ControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueV2ControllerTest.java @@ -30,8 +30,8 @@ import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -41,6 +41,7 @@ import org.springframework.test.web.servlet.MvcResult; * queue v2 controller test */ public class QueueV2ControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(QueueV2ControllerTest.class); private static final String QUEUE_CREATE_NAME = "queue_create"; @@ -52,15 +53,15 @@ public class QueueV2ControllerTest extends AbstractControllerTest { @Test public void testQueryList() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/v2/queues/list") - .header(SESSION_ID, sessionId) - .accept(MediaType.ALL) - .contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()) - .andReturn(); + .header(SESSION_ID, sessionId) + .accept(MediaType.ALL) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("query list queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -72,15 +73,15 @@ public class QueueV2ControllerTest extends AbstractControllerTest { queueQueryRequest.setPageSize(20); MvcResult mvcResult = mockMvc.perform(get("/v2/queues") - .header(SESSION_ID, sessionId) - .accept(MediaType.ALL) - .contentType(MediaType.APPLICATION_JSON) - .content(JSONUtils.toJsonString(queueQueryRequest))) - .andExpect(status().isOk()) - .andReturn(); + .header(SESSION_ID, sessionId) + .accept(MediaType.ALL) + .contentType(MediaType.APPLICATION_JSON) + .content(JSONUtils.toJsonString(queueQueryRequest))) + .andExpect(status().isOk()) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); + Assertions.assertNotNull(result); logger.info("query list-paging queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -90,16 +91,16 @@ public class QueueV2ControllerTest extends AbstractControllerTest { queueCreateRequest.setQueue(QUEUE_CREATE_NAME); queueCreateRequest.setQueueName(QUEUE_NAME_CREATE_NAME); MvcResult mvcResult = mockMvc.perform(post("/v2/queues") - .header(SESSION_ID, sessionId) - .accept(MediaType.ALL) - .contentType(MediaType.APPLICATION_JSON) - .content(JSONUtils.toJsonString(queueCreateRequest))) - .andExpect(status().isCreated()) - .andReturn(); + .header(SESSION_ID, sessionId) + .accept(MediaType.ALL) + .contentType(MediaType.APPLICATION_JSON) + .content(JSONUtils.toJsonString(queueCreateRequest))) + .andExpect(status().isCreated()) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("create queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -109,16 +110,16 @@ public class QueueV2ControllerTest extends AbstractControllerTest { queueUpdateRequest.setQueue(QUEUE_MODIFY_NAME); queueUpdateRequest.setQueueName(QUEUE_NAME_MODIFY_NAME); MvcResult mvcResult = mockMvc.perform(put("/v2/queues/{id}", 1) - .header(SESSION_ID, sessionId) - .accept(MediaType.ALL) - .contentType(MediaType.APPLICATION_JSON) - .content(JSONUtils.toJsonString(queueUpdateRequest))) - .andExpect(status().isCreated()) - .andReturn(); + .header(SESSION_ID, sessionId) + .accept(MediaType.ALL) + .contentType(MediaType.APPLICATION_JSON) + .content(JSONUtils.toJsonString(queueUpdateRequest))) + .andExpect(status().isCreated()) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info("update queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -129,44 +130,44 @@ public class QueueV2ControllerTest extends AbstractControllerTest { queueVerifyRequest.setQueue(QUEUE_MODIFY_NAME); queueVerifyRequest.setQueueName(NOT_EXISTS_NAME); MvcResult mvcResult = mockMvc.perform(post("/v2/queues/verify") - .header(SESSION_ID, sessionId) - .accept(MediaType.ALL) - .contentType(MediaType.APPLICATION_JSON) - .content(JSONUtils.toJsonString(queueVerifyRequest))) - .andExpect(status().isOk()) - .andReturn(); + .header(SESSION_ID, sessionId) + .accept(MediaType.ALL) + .contentType(MediaType.APPLICATION_JSON) + .content(JSONUtils.toJsonString(queueVerifyRequest))) + .andExpect(status().isOk()) + .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.QUEUE_VALUE_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.QUEUE_VALUE_EXIST.getCode(), result.getCode().intValue()); // queue name exist queueVerifyRequest.setQueue(NOT_EXISTS_NAME); queueVerifyRequest.setQueueName(QUEUE_NAME_CREATE_NAME); mvcResult = mockMvc.perform(post("/v2/queues/verify") - .header(SESSION_ID, sessionId) - .accept(MediaType.ALL) - .contentType(MediaType.APPLICATION_JSON) - .content(JSONUtils.toJsonString(queueVerifyRequest))) - .andExpect(status().isOk()) - .andReturn(); + .header(SESSION_ID, sessionId) + .accept(MediaType.ALL) + .contentType(MediaType.APPLICATION_JSON) + .content(JSONUtils.toJsonString(queueVerifyRequest))) + .andExpect(status().isOk()) + .andReturn(); result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.QUEUE_NAME_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.QUEUE_NAME_EXIST.getCode(), result.getCode().intValue()); // success queueVerifyRequest.setQueue(NOT_EXISTS_NAME); queueVerifyRequest.setQueueName(NOT_EXISTS_NAME); mvcResult = mockMvc.perform(post("/v2/queues/verify") - .header(SESSION_ID, sessionId) - .accept(MediaType.ALL) - .contentType(MediaType.APPLICATION_JSON) - .content(JSONUtils.toJsonString(queueVerifyRequest))) - .andExpect(status().isOk()) - .andReturn(); + .header(SESSION_ID, sessionId) + .accept(MediaType.ALL) + .contentType(MediaType.APPLICATION_JSON) + .content(JSONUtils.toJsonString(queueVerifyRequest))) + .andExpect(status().isOk()) + .andReturn(); result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertNotNull(result); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertNotNull(result); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); logger.info("verify queue return result:{}", mvcResult.getResponse().getContentAsString()); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java index d499a35125..a05600f5b3 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java @@ -36,8 +36,8 @@ import org.apache.dolphinscheduler.spi.enums.ResourceType; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -76,7 +76,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -105,7 +105,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -129,7 +129,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -153,7 +153,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.HDFS_NOT_STARTUP.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.HDFS_NOT_STARTUP.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -184,7 +184,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -208,7 +208,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -222,7 +222,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { .andExpect(status().is(HttpStatus.BAD_REQUEST.value())) .andReturn(); - Assert.assertNotNull(mvcResult); + Assertions.assertNotNull(mvcResult); } @Test @@ -252,7 +252,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -272,7 +272,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -304,7 +304,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -329,7 +329,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -351,7 +351,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -373,7 +373,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -395,7 +395,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -417,7 +417,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -439,7 +439,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -457,7 +457,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -475,7 +475,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/SchedulerControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/SchedulerControllerTest.java index 63ec80d287..e5d3950ed3 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/SchedulerControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/SchedulerControllerTest.java @@ -37,8 +37,8 @@ import org.apache.dolphinscheduler.common.utils.JSONUtils; import org.apache.dolphinscheduler.dao.entity.Resource; import org.apache.dolphinscheduler.dao.entity.User; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -81,7 +81,7 @@ public class SchedulerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -111,7 +111,7 @@ public class SchedulerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -131,7 +131,7 @@ public class SchedulerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -151,7 +151,7 @@ public class SchedulerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -177,7 +177,7 @@ public class SchedulerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -192,7 +192,7 @@ public class SchedulerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -210,7 +210,7 @@ public class SchedulerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -229,7 +229,7 @@ public class SchedulerControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupControllerTest.java index 639bae1896..6bc08fe228 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupControllerTest.java @@ -25,8 +25,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -56,7 +56,7 @@ public class TaskGroupControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("query list queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -74,7 +74,7 @@ public class TaskGroupControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("query list queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -92,7 +92,7 @@ public class TaskGroupControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("query list queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -112,7 +112,7 @@ public class TaskGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("create queue return result:{}", mvcResult.getResponse().getContentAsString()); // failed // name exists @@ -128,7 +128,7 @@ public class TaskGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result1 = JSONUtils.parseObject(mvcResult1.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result1 != null && result1.isFailed()); + Assertions.assertTrue(result1 != null && result1.isFailed()); logger.info("create queue return result:{}", mvcResult1.getResponse().getContentAsString()); } @@ -149,7 +149,7 @@ public class TaskGroupControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info("update queue return result:{}", mvcResult.getResponse().getContentAsString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("update queue return result:{}", mvcResult.getResponse().getContentAsString()); } @@ -167,7 +167,7 @@ public class TaskGroupControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); logger.info("update queue return result:{}", mvcResult.getResponse().getContentAsString()); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("update queue return result:{}", mvcResult.getResponse().getContentAsString()); // start @@ -181,7 +181,7 @@ public class TaskGroupControllerTest extends AbstractControllerTest { .andReturn(); Result result1 = JSONUtils.parseObject(mvcResult1.getResponse().getContentAsString(), Result.class); logger.info("update queue return result:{}", mvcResult1.getResponse().getContentAsString()); - Assert.assertTrue(result1 != null && result1.isSuccess()); + Assertions.assertTrue(result1 != null && result1.isSuccess()); logger.info("update queue return result:{}", mvcResult.getResponse().getContentAsString()); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupQueueControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupQueueControllerTest.java index 38cd1397d1..3cd207c2d4 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupQueueControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupQueueControllerTest.java @@ -24,8 +24,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -56,7 +56,7 @@ public class TaskGroupQueueControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info("query list queue return result:{}", mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskInstanceControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskInstanceControllerTest.java index b73a21302d..e79ee4d168 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskInstanceControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskInstanceControllerTest.java @@ -35,14 +35,14 @@ import org.apache.dolphinscheduler.common.enums.TaskExecuteType; import org.apache.dolphinscheduler.common.utils.JSONUtils; import org.apache.dolphinscheduler.dao.entity.TaskInstance; import org.apache.dolphinscheduler.dao.entity.User; +import org.apache.dolphinscheduler.plugin.task.api.enums.TaskExecutionStatus; import java.util.HashMap; import java.util.Map; -import org.apache.dolphinscheduler.plugin.task.api.enums.TaskExecutionStatus; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; @@ -76,10 +76,10 @@ public class TaskInstanceControllerTest extends AbstractControllerTest { Result taskResult = taskInstanceController.queryTaskListPaging(null, 1L, 1, "", "", "", "", "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", "2020-01-01 00:00:00", "2020-01-02 00:00:00", TaskExecuteType.BATCH, pageNo, pageSize); - Assert.assertEquals(Integer.valueOf(Status.SUCCESS.getCode()), taskResult.getCode()); + Assertions.assertEquals(Integer.valueOf(Status.SUCCESS.getCode()), taskResult.getCode()); } - @Ignore + @Disabled @Test public void testForceTaskSuccess() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); @@ -98,7 +98,7 @@ public class TaskInstanceControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TenantControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TenantControllerTest.java index bffa9d39a4..7178cbfce3 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TenantControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TenantControllerTest.java @@ -17,11 +17,19 @@ package org.apache.dolphinscheduler.api.controller; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -29,19 +37,16 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - public class TenantControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(TenantControllerTest.class); @Test public void testCreateTenant() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("tenantCode","hayden"); - paramsMap.add("queueId","1"); - paramsMap.add("description","tenant description"); + paramsMap.add("tenantCode", "hayden"); + paramsMap.add("queueId", "1"); + paramsMap.add("description", "tenant description"); MvcResult mvcResult = mockMvc.perform(post("/tenants/") .header(SESSION_ID, sessionId) @@ -51,7 +56,7 @@ public class TenantControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -59,9 +64,9 @@ public class TenantControllerTest extends AbstractControllerTest { @Test public void testQueryTenantlistPaging() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("pageNo","1"); - paramsMap.add("searchVal","tenant"); - paramsMap.add("pageSize","30"); + paramsMap.add("pageNo", "1"); + paramsMap.add("searchVal", "tenant"); + paramsMap.add("pageSize", "30"); MvcResult mvcResult = mockMvc.perform(get("/tenants/") .header(SESSION_ID, sessionId) @@ -71,17 +76,17 @@ public class TenantControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @Test public void testUpdateTenant() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("id","9"); - paramsMap.add("tenantCode","cxc_te"); - paramsMap.add("queueId","1"); - paramsMap.add("description","tenant description"); + paramsMap.add("id", "9"); + paramsMap.add("tenantCode", "cxc_te"); + paramsMap.add("queueId", "1"); + paramsMap.add("description", "tenant description"); MvcResult mvcResult = mockMvc.perform(put("/tenants/{id}", 9) .header(SESSION_ID, sessionId) @@ -91,7 +96,7 @@ public class TenantControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.TENANT_NOT_EXIST.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -99,7 +104,7 @@ public class TenantControllerTest extends AbstractControllerTest { @Test public void testVerifyTenantCode() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("tenantCode","cxc_test"); + paramsMap.add("tenantCode", "cxc_test"); MvcResult mvcResult = mockMvc.perform(get("/tenants/verify-code") .header(SESSION_ID, sessionId) @@ -109,12 +114,12 @@ public class TenantControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } - // @Test + // @Test public void testVerifyTenantCodeExists() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("tenantCode", "hayden"); @@ -127,7 +132,7 @@ public class TenantControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.OS_TENANT_CODE_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.OS_TENANT_CODE_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -142,7 +147,7 @@ public class TenantControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -150,7 +155,7 @@ public class TenantControllerTest extends AbstractControllerTest { @Test public void testDeleteTenantById() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("id","64"); + paramsMap.add("id", "64"); MvcResult mvcResult = mockMvc.perform(delete("/tenants/{id}", 64) .header(SESSION_ID, sessionId) @@ -159,7 +164,7 @@ public class TenantControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.TENANT_NOT_EXIST.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.TENANT_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UiPluginControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UiPluginControllerTest.java index f8aa941082..ad71b2528d 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UiPluginControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UiPluginControllerTest.java @@ -17,74 +17,78 @@ package org.apache.dolphinscheduler.api.controller; -import com.google.common.collect.ImmutableMap; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.service.UiPluginService; import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.enums.PluginType; import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Test; + +import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.when; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import com.google.common.collect.ImmutableMap; /** * ui plugin controller test */ public class UiPluginControllerTest extends AbstractControllerTest { + private static final PluginType pluginType = PluginType.ALERT; private static final int pluginId = 1; private static final Result expectResponseContent = JSONUtils.parseObject( - "{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}" - , Result.class); + "{\"code\":0,\"msg\":\"success\",\"data\":\"Test Data\",\"success\":true,\"failed\":false}", Result.class); private static final ImmutableMap uiPluginServiceResult = ImmutableMap.of(Constants.STATUS, Status.SUCCESS, Constants.DATA_LIST, "Test Data"); - + @MockBean(name = "uiPluginService") private UiPluginService uiPluginService; - + @Test public void testQueryUiPluginsByType() throws Exception { when(uiPluginService.queryUiPluginsByType(any(PluginType.class))) .thenReturn(uiPluginServiceResult); - + final MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pluginType", String.valueOf(pluginType)); - + final MvcResult mvcResult = mockMvc.perform(get("/ui-plugins/query-by-type") - .header(SESSION_ID, sessionId) - .params(paramsMap)) + .header(SESSION_ID, sessionId) + .params(paramsMap)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } - + @Test public void testQueryUiPluginDetailById() throws Exception { when(uiPluginService.queryUiPluginDetailById(anyInt())) .thenReturn(uiPluginServiceResult); - + final MvcResult mvcResult = mockMvc.perform(get("/ui-plugins/{id}", pluginId) - .header(SESSION_ID, sessionId)) + .header(SESSION_ID, sessionId)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); - - final Result actualResponseContent = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); + + final Result actualResponseContent = + JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); assertThat(actualResponseContent.toString()).isEqualTo(expectResponseContent.toString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UsersControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UsersControllerTest.java index 2794bae8e7..77b5d85442 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UsersControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UsersControllerTest.java @@ -29,9 +29,9 @@ import org.apache.dolphinscheduler.common.utils.JSONUtils; import java.util.ArrayList; import java.util.List; -import org.junit.Assert; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; @@ -43,6 +43,7 @@ import org.springframework.util.MultiValueMap; * users controller test */ public class UsersControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(UsersControllerTest.class); @Test @@ -63,7 +64,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.CREATE_USER_ERROR.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.CREATE_USER_ERROR.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -86,7 +87,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.UPDATE_USER_ERROR.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.UPDATE_USER_ERROR.getCode(), result.getCode().intValue()); } @Test @@ -103,7 +104,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -115,14 +116,14 @@ public class UsersControllerTest extends AbstractControllerTest { MvcResult mvcResult = this.mockMvc .perform(post("/users/grant-project-by-code") - .header(SESSION_ID, this.sessionId) - .params(paramsMap)) + .header(SESSION_ID, this.sessionId) + .params(paramsMap)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -140,7 +141,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -158,7 +159,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -176,7 +177,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -194,7 +195,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -207,7 +208,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -224,12 +225,12 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } // todo: there is a sql error, the table t_ds_relation_user_alertgroup has already been dropped - @Ignore + @Disabled @Test public void testAuthorizedUser() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); @@ -243,12 +244,12 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } // todo: t_ds_relation_user_alertgroup has already been dropped - @Ignore + @Disabled @Test public void testUnauthorizedUser() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); @@ -262,7 +263,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -278,7 +279,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -295,7 +296,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.USER_NOT_EXIST.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -309,7 +310,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -329,11 +330,11 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test - @Ignore + @Disabled public void testActivateUser() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("userName", "user_test"); @@ -346,7 +347,7 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -364,6 +365,6 @@ public class UsersControllerTest extends AbstractControllerTest { .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkFlowLineageControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkFlowLineageControllerTest.java index b5422b3fe9..8903686993 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkFlowLineageControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkFlowLineageControllerTest.java @@ -28,19 +28,19 @@ import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; -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; /** * work flow lineage controller test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class WorkFlowLineageControllerTest { @InjectMocks @@ -51,7 +51,7 @@ public class WorkFlowLineageControllerTest { protected User user; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -78,11 +78,11 @@ public class WorkFlowLineageControllerTest { result.put(Constants.DATA_LIST, 1); Mockito.when(workFlowLineageService.queryWorkFlowLineageByName(projectCode, searchVal)).thenReturn(result); Result response = workFlowLineageController.queryWorkFlowLineageByName(user, projectCode, searchVal); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } @Test - public void testQueryWorkFlowLineageByCode() { + public void testQueryWorkFlowLineageByCode() { long projectCode = 1L; long code = 1L; Map result = new HashMap<>(); @@ -90,6 +90,6 @@ public class WorkFlowLineageControllerTest { result.put(Constants.DATA_LIST, 1); Mockito.when(workFlowLineageService.queryWorkFlowLineageByCode(projectCode, code)).thenReturn(result); Result response = workFlowLineageController.queryWorkFlowLineageByCode(user, projectCode, code); - Assert.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), response.getCode().intValue()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java index 48d085685d..297fc988b9 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java @@ -35,8 +35,8 @@ import org.apache.dolphinscheduler.service.registry.RegistryClient; import java.util.HashMap; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -81,7 +81,7 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -98,7 +98,7 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -112,7 +112,7 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -124,7 +124,7 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info(mvcResult.getResponse().getContentAsString()); } @@ -145,7 +145,7 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(), Result.class); - Assert.assertTrue(result != null && result.isSuccess()); + Assertions.assertTrue(result != null && result.isSuccess()); logger.info(mvcResult.getResponse().getContentAsString()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkflowV2ControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkflowV2ControllerTest.java index 88ae51c176..83e509d490 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkflowV2ControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkflowV2ControllerTest.java @@ -35,20 +35,19 @@ import org.apache.dolphinscheduler.dao.mapper.TenantMapper; import java.util.ArrayList; import java.util.List; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -import org.junit.runner.RunWith; +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; /** * project v2 controller test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) public class WorkflowV2ControllerTest { protected User user; @@ -69,7 +68,7 @@ public class WorkflowV2ControllerTest { private final static int warningGroupId = 0; private final static String executionType = "PARALLEL"; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -94,7 +93,7 @@ public class WorkflowV2ControllerTest { Mockito.when(processDefinitionService.createSingleProcessDefinition(user, workflowCreateRequest)) .thenReturn(this.getProcessDefinition(name)); Result resourceResponse = workflowV2Controller.createWorkflow(user, workflowCreateRequest); - Assert.assertEquals(this.getProcessDefinition(name), resourceResponse.getData()); + Assertions.assertEquals(this.getProcessDefinition(name), resourceResponse.getData()); } @Test @@ -107,7 +106,7 @@ public class WorkflowV2ControllerTest { Result resourceResponse = workflowV2Controller.updateWorkflow(user, 1L, workflowUpdateRequest); - Assert.assertEquals(this.getProcessDefinition(newName), resourceResponse.getData()); + Assertions.assertEquals(this.getProcessDefinition(newName), resourceResponse.getData()); } @Test diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/filter/ResourceFilterTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/filter/ResourceFilterTest.java index 2ddce9e0d0..ba0c796f2e 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/filter/ResourceFilterTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/filter/ResourceFilterTest.java @@ -17,30 +17,32 @@ package org.apache.dolphinscheduler.api.dto.resources.filter; import org.apache.dolphinscheduler.dao.entity.Resource; -import org.junit.Assert; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + /** * resource filter test */ public class ResourceFilterTest { + private static Logger logger = LoggerFactory.getLogger(ResourceFilterTest.class); @Test - public void filterTest(){ + public void filterTest() { List allList = new ArrayList<>(); - Resource resource1 = new Resource(3,-1,"b","/b",true); - Resource resource2 = new Resource(4,2,"a1.txt","/a/a1.txt",false); - Resource resource3 = new Resource(5,3,"b1.txt","/b/b1.txt",false); - Resource resource4 = new Resource(6,3,"b2.jar","/b/b2.jar",false); - Resource resource5 = new Resource(7,-1,"b2","/b2",true); - Resource resource6 = new Resource(8,-1,"b2","/b/b2",true); - Resource resource7 = new Resource(9,8,"c2.jar","/b/b2/c2.jar",false); + Resource resource1 = new Resource(3, -1, "b", "/b", true); + Resource resource2 = new Resource(4, 2, "a1.txt", "/a/a1.txt", false); + Resource resource3 = new Resource(5, 3, "b1.txt", "/b/b1.txt", false); + Resource resource4 = new Resource(6, 3, "b2.jar", "/b/b2.jar", false); + Resource resource5 = new Resource(7, -1, "b2", "/b2", true); + Resource resource6 = new Resource(8, -1, "b2", "/b/b2", true); + Resource resource7 = new Resource(9, 8, "c2.jar", "/b/b2/c2.jar", false); allList.add(resource1); allList.add(resource2); allList.add(resource3); @@ -49,9 +51,9 @@ public class ResourceFilterTest { allList.add(resource6); allList.add(resource7); - ResourceFilter resourceFilter = new ResourceFilter(".jar",allList); + ResourceFilter resourceFilter = new ResourceFilter(".jar", allList); List resourceList = resourceFilter.filter(); - Assert.assertNotNull(resourceList); + Assertions.assertNotNull(resourceList); resourceList.forEach(t -> logger.info(t.toString())); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitorTest.java index d1f8a12012..f5ca3c559d 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitorTest.java @@ -18,12 +18,13 @@ package org.apache.dolphinscheduler.api.dto.resources.visitor; import org.apache.dolphinscheduler.api.dto.resources.ResourceComponent; import org.apache.dolphinscheduler.dao.entity.Resource; -import org.junit.Assert; -import org.junit.Test; import java.util.ArrayList; import java.util.List; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + /** * resource tree visitor test */ @@ -33,13 +34,13 @@ public class ResourceTreeVisitorTest { public void visit() throws Exception { List resourceList = new ArrayList<>(); - Resource resource1 = new Resource(3,-1,"b","/b",true); - Resource resource2 = new Resource(4,2,"a1.txt","/a/a1.txt",false); - Resource resource3 = new Resource(5,3,"b1.txt","/b/b1.txt",false); - Resource resource4 = new Resource(6,3,"b2.jar","/b/b2.jar",false); - Resource resource5 = new Resource(7,-1,"b2","/b2",true); - Resource resource6 = new Resource(8,-1,"b2","/b/b2",true); - Resource resource7 = new Resource(9,8,"c2.jar","/b/b2/c2.jar",false); + Resource resource1 = new Resource(3, -1, "b", "/b", true); + Resource resource2 = new Resource(4, 2, "a1.txt", "/a/a1.txt", false); + Resource resource3 = new Resource(5, 3, "b1.txt", "/b/b1.txt", false); + Resource resource4 = new Resource(6, 3, "b2.jar", "/b/b2.jar", false); + Resource resource5 = new Resource(7, -1, "b2", "/b2", true); + Resource resource6 = new Resource(8, -1, "b2", "/b/b2", true); + Resource resource7 = new Resource(9, 8, "c2.jar", "/b/b2/c2.jar", false); resourceList.add(resource1); resourceList.add(resource2); resourceList.add(resource3); @@ -50,20 +51,20 @@ public class ResourceTreeVisitorTest { ResourceTreeVisitor resourceTreeVisitor = new ResourceTreeVisitor(resourceList); ResourceComponent resourceComponent = resourceTreeVisitor.visit(); - Assert.assertNotNull(resourceComponent.getChildren()); + Assertions.assertNotNull(resourceComponent.getChildren()); } @Test public void rootNode() throws Exception { List resourceList = new ArrayList<>(); - Resource resource1 = new Resource(3,-1,"b","/b",true); - Resource resource2 = new Resource(4,2,"a1.txt","/a/a1.txt",false); - Resource resource3 = new Resource(5,3,"b1.txt","/b/b1.txt",false); - Resource resource4 = new Resource(6,3,"b2.jar","/b/b2.jar",false); - Resource resource5 = new Resource(7,-1,"b2","/b2",true); - Resource resource6 = new Resource(8,-1,"b2","/b/b2",true); - Resource resource7 = new Resource(9,8,"c2.jar","/b/b2/c2.jar",false); + Resource resource1 = new Resource(3, -1, "b", "/b", true); + Resource resource2 = new Resource(4, 2, "a1.txt", "/a/a1.txt", false); + Resource resource3 = new Resource(5, 3, "b1.txt", "/b/b1.txt", false); + Resource resource4 = new Resource(6, 3, "b2.jar", "/b/b2.jar", false); + Resource resource5 = new Resource(7, -1, "b2", "/b2", true); + Resource resource6 = new Resource(8, -1, "b2", "/b/b2", true); + Resource resource7 = new Resource(9, 8, "c2.jar", "/b/b2/c2.jar", false); resourceList.add(resource1); resourceList.add(resource2); resourceList.add(resource3); @@ -73,10 +74,10 @@ public class ResourceTreeVisitorTest { resourceList.add(resource7); ResourceTreeVisitor resourceTreeVisitor = new ResourceTreeVisitor(resourceList); - Assert.assertTrue(resourceTreeVisitor.rootNode(resource1)); - Assert.assertTrue(resourceTreeVisitor.rootNode(resource2)); - Assert.assertFalse(resourceTreeVisitor.rootNode(resource3)); + Assertions.assertTrue(resourceTreeVisitor.rootNode(resource1)); + Assertions.assertTrue(resourceTreeVisitor.rootNode(resource2)); + Assertions.assertFalse(resourceTreeVisitor.rootNode(resource3)); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/ExecuteTypeTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/ExecuteTypeTest.java index 70fb568b84..eaeb7dc4f7 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/ExecuteTypeTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/ExecuteTypeTest.java @@ -17,18 +17,17 @@ package org.apache.dolphinscheduler.api.enums; -import static org.junit.Assert.assertEquals; - -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ExecuteTypeTest { @Test public void testGetEnum() { - assertEquals(ExecuteType.REPEAT_RUNNING, ExecuteType.getEnum(1)); - assertEquals(ExecuteType.RECOVER_SUSPENDED_PROCESS, ExecuteType.getEnum(2)); - assertEquals(ExecuteType.START_FAILURE_TASK_PROCESS, ExecuteType.getEnum(3)); - assertEquals(ExecuteType.STOP, ExecuteType.getEnum(4)); - assertEquals(ExecuteType.PAUSE, ExecuteType.getEnum(5)); + Assertions.assertEquals(ExecuteType.REPEAT_RUNNING, ExecuteType.getEnum(1)); + Assertions.assertEquals(ExecuteType.RECOVER_SUSPENDED_PROCESS, ExecuteType.getEnum(2)); + Assertions.assertEquals(ExecuteType.START_FAILURE_TASK_PROCESS, ExecuteType.getEnum(3)); + Assertions.assertEquals(ExecuteType.STOP, ExecuteType.getEnum(4)); + Assertions.assertEquals(ExecuteType.PAUSE, ExecuteType.getEnum(5)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/StatusTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/StatusTest.java index 19b0926fbd..09a1280c87 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/StatusTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/StatusTest.java @@ -16,41 +16,39 @@ */ package org.apache.dolphinscheduler.api.enums; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.context.i18n.LocaleContextHolder; - import java.util.Locale; import java.util.Optional; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.context.i18n.LocaleContextHolder; public class StatusTest { @Test public void testGetCode() { - assertEquals(0, Status.SUCCESS.getCode()); - assertNotEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), 0); + Assertions.assertEquals(0, Status.SUCCESS.getCode()); + Assertions.assertNotEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), 0); } @Test public void testGetMsg() { LocaleContextHolder.setLocale(Locale.US); - Assert.assertEquals("success", Status.SUCCESS.getMsg()); + Assertions.assertEquals("success", Status.SUCCESS.getMsg()); LocaleContextHolder.setLocale(Locale.SIMPLIFIED_CHINESE); - Assert.assertEquals("成功", Status.SUCCESS.getMsg()); + Assertions.assertEquals("成功", Status.SUCCESS.getMsg()); } @Test public void testGetStatusByCode() { // FAILURE Optional optional = Status.findStatusBy(1); - Assert.assertFalse(optional.isPresent()); + Assertions.assertFalse(optional.isPresent()); // SUCCESS optional = Status.findStatusBy(10018); - Assert.assertTrue(optional.isPresent()); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, optional.get()); + Assertions.assertTrue(optional.isPresent()); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, optional.get()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ApiExceptionHandlerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ApiExceptionHandlerTest.java index 4b4fd613d4..3f358688e0 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ApiExceptionHandlerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ApiExceptionHandlerTest.java @@ -25,8 +25,8 @@ import org.apache.dolphinscheduler.dao.entity.User; import java.lang.reflect.Method; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.springframework.web.method.HandlerMethod; public class ApiExceptionHandlerTest { @@ -35,19 +35,21 @@ public class ApiExceptionHandlerTest { public void exceptionHandler() throws NoSuchMethodException { ApiExceptionHandler handler = new ApiExceptionHandler(); AccessTokenController controller = new AccessTokenController(); - Method method = controller.getClass().getMethod("createToken", User.class, int.class, String.class, String.class); + Method method = + controller.getClass().getMethod("createToken", User.class, int.class, String.class, String.class); HandlerMethod hm = new HandlerMethod(controller, method); Result result = handler.exceptionHandler(new RuntimeException("test exception"), hm); - Assert.assertEquals(Status.CREATE_ACCESS_TOKEN_ERROR.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.CREATE_ACCESS_TOKEN_ERROR.getCode(), result.getCode().intValue()); } @Test public void exceptionHandlerRuntime() throws NoSuchMethodException { ApiExceptionHandler handler = new ApiExceptionHandler(); ProcessDefinitionController controller = new ProcessDefinitionController(); - Method method = controller.getClass().getMethod("queryAllProcessDefinitionByProjectCode", User.class, long.class); + Method method = + controller.getClass().getMethod("queryAllProcessDefinitionByProjectCode", User.class, long.class); HandlerMethod hm = new HandlerMethod(controller, method); Result result = handler.exceptionHandler(new RuntimeException("test exception"), hm); - Assert.assertEquals(Status.QUERY_PROCESS_DEFINITION_LIST.getCode(),result.getCode().intValue()); + Assertions.assertEquals(Status.QUERY_PROCESS_DEFINITION_LIST.getCode(), result.getCode().intValue()); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ServiceExceptionTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ServiceExceptionTest.java index 3bb6479ba9..2753ce6492 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ServiceExceptionTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ServiceExceptionTest.java @@ -18,31 +18,31 @@ package org.apache.dolphinscheduler.api.exceptions; import org.apache.dolphinscheduler.api.enums.Status; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ServiceExceptionTest { @Test public void getCodeTest() { ServiceException serviceException = new ServiceException(); - Assert.assertEquals(Status.INTERNAL_SERVER_ERROR_ARGS.getCode(), serviceException.getCode()); + Assertions.assertEquals(Status.INTERNAL_SERVER_ERROR_ARGS.getCode(), serviceException.getCode()); serviceException = new ServiceException(Status.ALERT_GROUP_EXIST); - Assert.assertEquals(Status.ALERT_GROUP_EXIST.getCode(), serviceException.getCode()); + Assertions.assertEquals(Status.ALERT_GROUP_EXIST.getCode(), serviceException.getCode()); serviceException = new ServiceException(10012, "alarm group already exists"); - Assert.assertEquals(10012, serviceException.getCode()); + Assertions.assertEquals(10012, serviceException.getCode()); } @Test public void getMessageTest() { ServiceException serviceException = new ServiceException(); - Assert.assertEquals(Status.INTERNAL_SERVER_ERROR_ARGS.getMsg(), serviceException.getMessage()); + Assertions.assertEquals(Status.INTERNAL_SERVER_ERROR_ARGS.getMsg(), serviceException.getMessage()); serviceException = new ServiceException(Status.ALERT_GROUP_EXIST); - Assert.assertNotNull(serviceException.getMessage()); + Assertions.assertNotNull(serviceException.getMessage()); serviceException = new ServiceException(10012, "alarm group already exists"); - Assert.assertNotNull(serviceException.getMessage()); + Assertions.assertNotNull(serviceException.getMessage()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LocaleChangeInterceptorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LocaleChangeInterceptorTest.java index 2e36c5c57a..89c95ebec4 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LocaleChangeInterceptorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LocaleChangeInterceptorTest.java @@ -22,8 +22,8 @@ import org.apache.dolphinscheduler.api.controller.AbstractControllerTest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -37,7 +37,7 @@ public class LocaleChangeInterceptorTest extends AbstractControllerTest { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); // test no language - Assert.assertTrue(interceptor.preHandle(request, response, null)); + Assertions.assertTrue(interceptor.preHandle(request, response, null)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java index 467cfa0e07..8cf9609dbb 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java @@ -28,12 +28,13 @@ import org.apache.dolphinscheduler.common.enums.UserType; import org.apache.dolphinscheduler.dao.entity.User; import org.apache.dolphinscheduler.dao.mapper.UserMapper; +import java.util.Date; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -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.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -44,13 +45,9 @@ import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.annotation.Transactional; -import java.util.Date; - @ActiveProfiles(value = {ProfileType.H2}) -@RunWith(SpringRunner.class) @SpringBootTest(classes = ApiApplicationServer.class) @Transactional @Rollback @@ -64,14 +61,14 @@ public class LoginHandlerInterceptorTest { @MockBean(name = "authenticator") private Authenticator authenticator; @MockBean(name = "userMapper") - private UserMapper userMapper; + private UserMapper userMapper; @Test public void testPreHandle() { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); // test no token and no cookie - Assert.assertFalse(interceptor.preHandle(request, response, null)); + Assertions.assertFalse(interceptor.preHandle(request, response, null)); User mockUser = new User(); mockUser.setId(1); @@ -80,17 +77,17 @@ public class LoginHandlerInterceptorTest { // test no token when(authenticator.getAuthUser(request)).thenReturn(mockUser); - Assert.assertTrue(interceptor.preHandle(request, response, null)); + Assertions.assertTrue(interceptor.preHandle(request, response, null)); // test token String token = "123456"; when(request.getHeader("token")).thenReturn(token); when(userMapper.queryUserByToken(eq(token), any(Date.class))).thenReturn(mockUser); - Assert.assertTrue(interceptor.preHandle(request, response, null)); + Assertions.assertTrue(interceptor.preHandle(request, response, null)); // test disable user mockUser.setState(0); when(authenticator.getAuthUser(request)).thenReturn(mockUser); - Assert.assertFalse(interceptor.preHandle(request, response, null)); + Assertions.assertFalse(interceptor.preHandle(request, response, null)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java index e1eef9e41d..9dcd1111e2 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java @@ -26,13 +26,13 @@ import java.util.concurrent.ExecutionException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class RateLimitInterceptorTest { @Test @@ -40,8 +40,8 @@ public class RateLimitInterceptorTest { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); RateLimitInterceptor rateLimitInterceptor = new RateLimitInterceptor(new TrafficConfiguration()); - Assert.assertTrue(rateLimitInterceptor.preHandle(request, response, null)); - Assert.assertTrue(rateLimitInterceptor.preHandle(request, response, null)); + Assertions.assertTrue(rateLimitInterceptor.preHandle(request, response, null)); + Assertions.assertTrue(rateLimitInterceptor.preHandle(request, response, null)); } @Test @@ -64,8 +64,8 @@ public class RateLimitInterceptorTest { for (int i = 0; i < 2; i++) { rateLimitInterceptor.preHandle(tenant1Request, response, null); } - Assert.assertFalse(rateLimitInterceptor.preHandle(tenant1Request, response, null)); - Assert.assertTrue(rateLimitInterceptor.preHandle(tenant2Request, response, null)); + Assertions.assertFalse(rateLimitInterceptor.preHandle(tenant1Request, response, null)); + Assertions.assertTrue(rateLimitInterceptor.preHandle(tenant2Request, response, null)); } @Test @@ -82,7 +82,7 @@ public class RateLimitInterceptorTest { for (int i = 0; i < 2; i++) { rateLimitInterceptor.preHandle(request, response, null); } - Assert.assertFalse(rateLimitInterceptor.preHandle(request, response, null)); + Assertions.assertFalse(rateLimitInterceptor.preHandle(request, response, null)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/k8s/K8sManagerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/k8s/K8sManagerTest.java index fb36dd2e35..8243cbff51 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/k8s/K8sManagerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/k8s/K8sManagerTest.java @@ -24,19 +24,22 @@ import org.apache.dolphinscheduler.remote.exceptions.RemotingException; import java.util.ArrayList; import java.util.List; -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.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 io.fabric8.kubernetes.client.KubernetesClient; -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class K8sManagerTest { @InjectMocks @@ -45,11 +48,11 @@ public class K8sManagerTest { @Mock private ClusterMapper clusterMapper; - @Before + @BeforeEach public void setUp() throws Exception { } - @After + @AfterEach public void tearDown() throws Exception { } @@ -58,9 +61,9 @@ public class K8sManagerTest { Mockito.when(clusterMapper.selectList(Mockito.any())).thenReturn(getClusterList()); KubernetesClient result = k8sManager.getK8sClient(1L); - Assert.assertNull(result); + Assertions.assertNull(result); result = k8sManager.getK8sClient(null); - Assert.assertNull(result); + Assertions.assertNull(result); } private Cluster getCluster() { @@ -77,4 +80,4 @@ public class K8sManagerTest { clusterList.add(getCluster()); return clusterList; } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/permission/ResourcePermissionCheckServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/permission/ResourcePermissionCheckServiceTest.java index e1f0e63ad3..4ce733a37d 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/permission/ResourcePermissionCheckServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/permission/ResourcePermissionCheckServiceTest.java @@ -16,7 +16,6 @@ */ package org.apache.dolphinscheduler.api.permission; - import org.apache.dolphinscheduler.common.enums.AuthorizationType; import org.apache.dolphinscheduler.common.enums.UserType; import org.apache.dolphinscheduler.dao.entity.Project; @@ -30,22 +29,20 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; -import com.google.common.collect.Lists; - /** * permission service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ResourcePermissionCheckServiceTest { private static final Logger logger = LoggerFactory.getLogger(ResourcePermissionCheckServiceTest.class); @@ -57,52 +54,53 @@ public class ResourcePermissionCheckServiceTest { private ProjectMapper projectMapper; @Mock - private ApplicationContext context; + private ApplicationContext context; @Mock private ResourcePermissionCheckService resourcePermissionCheckService; @InjectMocks ResourcePermissionCheckServiceImpl resourcePermissionCheckServices; - protected static final Map> RESOURCE_LIST_MAP = new ConcurrentHashMap<>(); + protected static final Map> RESOURCE_LIST_MAP = + new ConcurrentHashMap<>(); @Test - public void testResourcePermissionCheck(){ + public void testResourcePermissionCheck() { User user = new User(); user.setId(1); - Object[] obj = new Object[]{1,2}; - boolean result = this.resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.PROJECTS, obj, user.getId(), logger); - Assert.assertFalse(result); + Object[] obj = new Object[]{1, 2}; + boolean result = this.resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.PROJECTS, obj, + user.getId(), logger); + Assertions.assertFalse(result); } @Test - public void testOperationPermissionCheck(){ + public void testOperationPermissionCheck() { User user = new User(); user.setId(1); resourcePermissionCheckServices.setApplicationContext(context); - Assert.assertFalse(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.PROJECTS, null, user.getId(), null, logger)); + Assertions.assertFalse(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.PROJECTS, null, + user.getId(), null, logger)); String sourceUrl = "/tmp/"; - Assert.assertFalse(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.PROJECTS, null, user.getId(), sourceUrl, logger)); + Assertions.assertFalse(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.PROJECTS, null, + user.getId(), sourceUrl, logger)); } @Test - public void testUserOwnedResourceIdsAcquisition(){ + public void testUserOwnedResourceIdsAcquisition() { User user = new User(); user.setId(1); - //ADMIN + // ADMIN user.setUserType(UserType.ADMIN_USER); - Object[] obj = new Object[]{1,2}; - List projectList = Lists.newArrayList(this.getEntity()); Set result = resourcePermissionCheckServices.userOwnedResourceIdsAcquisition(AuthorizationType.PROJECTS, user.getId(), logger); - Assert.assertNotNull(result); + Assertions.assertNotNull(result); } - @Test - public void testSetApplication(){ - resourcePermissionCheckServices.setApplicationContext(context); + public void testSetApplication() { + resourcePermissionCheckServices.setApplicationContext(context); } /** * create entity diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/python/PythonGatewayTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/python/PythonGatewayTest.java index 2a49ed307b..310b176b6c 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/python/PythonGatewayTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/python/PythonGatewayTest.java @@ -28,21 +28,22 @@ import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper; import org.apache.dolphinscheduler.dao.mapper.ProjectMapper; import org.apache.dolphinscheduler.dao.mapper.TaskDefinitionMapper; import org.apache.dolphinscheduler.spi.enums.ResourceType; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; import java.util.Date; import java.util.Map; +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.jupiter.MockitoExtension; + /** * python gate test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class PythonGatewayTest { @InjectMocks @@ -66,13 +67,16 @@ public class PythonGatewayTest { Mockito.when(projectMapper.queryByName(project.getName())).thenReturn(project); ProcessDefinition processDefinition = getTestProcessDefinition(); - Mockito.when(processDefinitionMapper.queryByDefineName(project.getCode(), processDefinition.getName())).thenReturn(processDefinition); + Mockito.when(processDefinitionMapper.queryByDefineName(project.getCode(), processDefinition.getName())) + .thenReturn(processDefinition); TaskDefinition taskDefinition = getTestTaskDefinition(); - Mockito.when(taskDefinitionMapper.queryByName(project.getCode(), processDefinition.getCode(), taskDefinition.getName())).thenReturn(taskDefinition); + Mockito.when(taskDefinitionMapper.queryByName(project.getCode(), processDefinition.getCode(), + taskDefinition.getName())).thenReturn(taskDefinition); - Map result = pythonGateway.getCodeAndVersion(project.getName(), processDefinition.getName(), taskDefinition.getName()); - Assert.assertEquals(result.get("code").longValue(), taskDefinition.getCode()); + Map result = pythonGateway.getCodeAndVersion(project.getName(), processDefinition.getName(), + taskDefinition.getName()); + Assertions.assertEquals(result.get("code").longValue(), taskDefinition.getCode()); } @Test @@ -81,13 +85,16 @@ public class PythonGatewayTest { Mockito.when(projectMapper.queryByName(project.getName())).thenReturn(project); ProcessDefinition processDefinition = getTestProcessDefinition(); - Mockito.when(processDefinitionMapper.queryByDefineName(project.getCode(), processDefinition.getName())).thenReturn(processDefinition); + Mockito.when(processDefinitionMapper.queryByDefineName(project.getCode(), processDefinition.getName())) + .thenReturn(processDefinition); TaskDefinition taskDefinition = getTestTaskDefinition(); - Mockito.when(taskDefinitionMapper.queryByName(project.getCode(), processDefinition.getCode(), taskDefinition.getName())).thenReturn(taskDefinition); + Mockito.when(taskDefinitionMapper.queryByName(project.getCode(), processDefinition.getCode(), + taskDefinition.getName())).thenReturn(taskDefinition); - Map result = pythonGateway.getDependentInfo(project.getName(), processDefinition.getName(), taskDefinition.getName()); - Assert.assertEquals((long) result.get("taskDefinitionCode"), taskDefinition.getCode()); + Map result = pythonGateway.getDependentInfo(project.getName(), processDefinition.getName(), + taskDefinition.getName()); + Assertions.assertEquals((long) result.get("taskDefinitionCode"), taskDefinition.getCode()); } @Test @@ -107,17 +114,17 @@ public class PythonGatewayTest { int id = pythonGateway.createOrUpdateResource( user.getUserName(), resourceFullName, desc, content); - Assert.assertEquals(id, resourceId); + Assertions.assertEquals(id, resourceId); } - @Test public void testQueryResourcesFileInfo() { User user = getTestUser(); Resource resource = getTestResource(); - Mockito.when(resourcesService.queryResourcesFileInfo(user.getUserName(), resource.getFullName())).thenReturn(resource); + Mockito.when(resourcesService.queryResourcesFileInfo(user.getUserName(), resource.getFullName())) + .thenReturn(resource); Resource result = pythonGateway.queryResourcesFileInfo(user.getUserName(), resource.getFullName()); - Assert.assertEquals(result.getId(), resource.getId()); + Assertions.assertEquals(result.getId(), resource.getId()); } private Resource getTestResource() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigLDAPTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigLDAPTest.java index 910e5d812e..88662273ea 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigLDAPTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigLDAPTest.java @@ -20,8 +20,8 @@ package org.apache.dolphinscheduler.api.security; import org.apache.dolphinscheduler.api.controller.AbstractControllerTest; import org.apache.dolphinscheduler.api.security.impl.ldap.LdapService; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.TestPropertySource; @@ -39,16 +39,15 @@ public class SecurityConfigLDAPTest extends AbstractControllerTest { @Test public void testAuthenticator() { Authenticator authenticator = securityConfig.authenticator(); - Assert.assertNotNull(authenticator); + Assertions.assertNotNull(authenticator); } @Test public void testLdapUserNotExistAction() { LdapUserNotExistActionType authenticator = ldapService.getLdapUserNotExistAction(); - Assert.assertEquals(LdapUserNotExistActionType.CREATE, authenticator); + Assertions.assertEquals(LdapUserNotExistActionType.CREATE, authenticator); boolean isCreateAction = ldapService.createIfUserNotExists(); - Assert.assertEquals(Boolean.TRUE, isCreateAction); + Assertions.assertEquals(Boolean.TRUE, isCreateAction); } } - diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigPasswordTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigPasswordTest.java index bb800c5dac..0a58446fc8 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigPasswordTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigPasswordTest.java @@ -19,8 +19,8 @@ package org.apache.dolphinscheduler.api.security; import org.apache.dolphinscheduler.api.controller.AbstractControllerTest; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.TestPropertySource; @@ -35,6 +35,6 @@ public class SecurityConfigPasswordTest extends AbstractControllerTest { @Test public void testAuthenticator() { Authenticator authenticator = securityConfig.authenticator(); - Assert.assertNotNull(authenticator); + Assertions.assertNotNull(authenticator); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapAuthenticatorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapAuthenticatorTest.java index f3835a560a..82e57a776b 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapAuthenticatorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapAuthenticatorTest.java @@ -36,9 +36,9 @@ import java.util.UUID; import javax.servlet.http.HttpServletRequest; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.mockito.Spy; import org.slf4j.Logger; @@ -48,19 +48,19 @@ import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.TestPropertySource; -@TestPropertySource( - properties = { - "security.authentication.type=LDAP", - "security.authentication.ldap.user.admin=read-only-admin", - "security.authentication.ldap.urls=ldap://ldap.forumsys.com:389/", - "security.authentication.ldap.base-dn=dc=example,dc=com", - "security.authentication.ldap.username=cn=read-only-admin,dc=example,dc=com", - "security.authentication.ldap.password=password", - "security.authentication.ldap.user.identity-attribute=uid", - "security.authentication.ldap.user.email-attribute=mail", - "security.authentication.ldap.user.not-exist-action=CREATE", - }) +@TestPropertySource(properties = { + "security.authentication.type=LDAP", + "security.authentication.ldap.user.admin=read-only-admin", + "security.authentication.ldap.urls=ldap://ldap.forumsys.com:389/", + "security.authentication.ldap.base-dn=dc=example,dc=com", + "security.authentication.ldap.username=cn=read-only-admin,dc=example,dc=com", + "security.authentication.ldap.password=password", + "security.authentication.ldap.user.identity-attribute=uid", + "security.authentication.ldap.user.email-attribute=mail", + "security.authentication.ldap.user.not-exist-action=CREATE", +}) public class LdapAuthenticatorTest extends AbstractControllerTest { + private static Logger logger = LoggerFactory.getLogger(LdapAuthenticatorTest.class); @Autowired protected AutowireCapableBeanFactory beanFactory; @@ -73,7 +73,7 @@ public class LdapAuthenticatorTest extends AbstractControllerTest { private LdapAuthenticator ldapAuthenticator; - //test param + // test param private User mockUser; private Session mockSession; @@ -84,7 +84,7 @@ public class LdapAuthenticatorTest extends AbstractControllerTest { private UserType userType = UserType.GENERAL_USER; @Override - @Before + @BeforeEach public void setUp() { ldapAuthenticator = new LdapAuthenticator(); beanFactory.autowireBean(ldapAuthenticator); @@ -112,24 +112,24 @@ public class LdapAuthenticatorTest extends AbstractControllerTest { when(ldapService.getLdapUserNotExistAction()).thenReturn(LdapUserNotExistActionType.DENY); when(ldapService.createIfUserNotExists()).thenReturn(false); Result> result = ldapAuthenticator.authenticate(ldapUid, ldapUserPwd, ip); - Assert.assertEquals(Status.USER_NAME_PASSWD_ERROR.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.USER_NAME_PASSWD_ERROR.getCode(), (int) result.getCode()); // test username pwd correct and user not exist, config user not exist action create, so login success when(ldapService.getLdapUserNotExistAction()).thenReturn(LdapUserNotExistActionType.CREATE); when(ldapService.createIfUserNotExists()).thenReturn(true); result = ldapAuthenticator.authenticate(ldapUid, ldapUserPwd, ip); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); logger.info(result.toString()); // test username pwd correct and user not exist, config action create but can't create session, so login failed when(sessionService.createSession(Mockito.any(User.class), Mockito.eq(ip))).thenReturn(null); result = ldapAuthenticator.authenticate(ldapUid, ldapUserPwd, ip); - Assert.assertEquals(Status.LOGIN_SESSION_FAILED.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.LOGIN_SESSION_FAILED.getCode(), (int) result.getCode()); // test username pwd error, login failed when(ldapService.ldapLogin(ldapUid, ldapUserPwd)).thenReturn(null); result = ldapAuthenticator.authenticate(ldapUid, ldapUserPwd, ip); - Assert.assertEquals(Status.USER_NAME_PASSWD_ERROR.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.USER_NAME_PASSWD_ERROR.getCode(), (int) result.getCode()); } @Test @@ -139,10 +139,10 @@ public class LdapAuthenticatorTest extends AbstractControllerTest { when(sessionService.getSession(request)).thenReturn(mockSession); User user = ldapAuthenticator.getAuthUser(request); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); when(sessionService.getSession(request)).thenReturn(null); user = ldapAuthenticator.getAuthUser(request); - Assert.assertNull(user); + Assertions.assertNull(user); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapServiceTest.java index ecda46d13f..c773a85ae4 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapServiceTest.java @@ -21,41 +21,38 @@ import org.apache.dolphinscheduler.api.ApiApplicationServer; import org.apache.dolphinscheduler.common.enums.ProfileType; import org.apache.dolphinscheduler.common.enums.UserType; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -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.Disabled; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; -@Ignore +@Disabled @ActiveProfiles(ProfileType.H2) -@RunWith(SpringRunner.class) @SpringBootTest(classes = ApiApplicationServer.class) -@TestPropertySource( - properties = { - "security.authentication.type=LDAP", - "security.authentication.ldap.user.admin=read-only-admin", - "security.authentication.ldap.urls=ldap://ldap.forumsys.com:389/", - "security.authentication.ldap.base-dn=dc=example,dc=com", - "security.authentication.ldap.username=cn=read-only-admin,dc=example,dc=com", - "security.authentication.ldap.password=password", - "security.authentication.ldap.user.identity-attribute=uid", - "security.authentication.ldap.user.email-attribute=mail", - "security.authentication.ldap.user.not-exist-action=CREATE", - }) +@TestPropertySource(properties = { + "security.authentication.type=LDAP", + "security.authentication.ldap.user.admin=read-only-admin", + "security.authentication.ldap.urls=ldap://ldap.forumsys.com:389/", + "security.authentication.ldap.base-dn=dc=example,dc=com", + "security.authentication.ldap.username=cn=read-only-admin,dc=example,dc=com", + "security.authentication.ldap.password=password", + "security.authentication.ldap.user.identity-attribute=uid", + "security.authentication.ldap.user.email-attribute=mail", + "security.authentication.ldap.user.not-exist-action=CREATE", +}) public class LdapServiceTest { + @Autowired protected AutowireCapableBeanFactory beanFactory; private LdapService ldapService; - @Before + @BeforeEach public void setUp() { ldapService = new LdapService(); beanFactory.autowireBean(ldapService); @@ -64,24 +61,24 @@ public class LdapServiceTest { @Test public void getUserType() { UserType userType = ldapService.getUserType("read-only-admin"); - Assert.assertEquals(UserType.ADMIN_USER, userType); + Assertions.assertEquals(UserType.ADMIN_USER, userType); } @Test public void ldapLogin() { String email = ldapService.ldapLogin("tesla", "password"); - Assert.assertEquals("tesla@ldap.forumsys.com", email); + Assertions.assertEquals("tesla@ldap.forumsys.com", email); String email2 = ldapService.ldapLogin("tesla", "error password"); - Assert.assertNull(email2); + Assertions.assertNull(email2); } @Test public void ldapLoginError() { String email = ldapService.ldapLogin("tesla", "password"); - Assert.assertEquals("tesla@ldap.forumsys.com", email); + Assertions.assertEquals("tesla@ldap.forumsys.com", email); String email2 = ldapService.ldapLogin("tesla", "error password"); - Assert.assertNull(email2); + Assertions.assertNull(email2); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/pwd/PasswordAuthenticatorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/pwd/PasswordAuthenticatorTest.java index b58a4b59df..eb65560b91 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/pwd/PasswordAuthenticatorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/pwd/PasswordAuthenticatorTest.java @@ -32,9 +32,9 @@ import java.util.UUID; import javax.servlet.http.HttpServletRequest; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,6 +43,7 @@ import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.boot.test.mock.mockito.MockBean; public class PasswordAuthenticatorTest extends AbstractControllerTest { + private static Logger logger = LoggerFactory.getLogger(PasswordAuthenticatorTest.class); @Autowired @@ -58,7 +59,7 @@ public class PasswordAuthenticatorTest extends AbstractControllerTest { private Session mockSession; @Override - @Before + @BeforeEach public void setUp() { authenticator = new PasswordAuthenticator(); beanFactory.autowireBean(authenticator); @@ -81,7 +82,7 @@ public class PasswordAuthenticatorTest extends AbstractControllerTest { public void testLogin() { when(usersService.queryUser("test", "test")).thenReturn(mockUser); User login = authenticator.login("test", "test", "127.0.0.1"); - Assert.assertNotNull(login); + Assertions.assertNotNull(login); } @Test @@ -89,14 +90,14 @@ public class PasswordAuthenticatorTest extends AbstractControllerTest { when(usersService.queryUser("test", "test")).thenReturn(mockUser); when(sessionService.createSession(mockUser, "127.0.0.1")).thenReturn(mockSession.getId()); Result result = authenticator.authenticate("test", "test", "127.0.0.1"); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); logger.info(result.toString()); mockUser.setState(0); when(usersService.queryUser("test", "test")).thenReturn(mockUser); when(sessionService.createSession(mockUser, "127.0.0.1")).thenReturn(mockSession.getId()); Result result1 = authenticator.authenticate("test", "test", "127.0.0.1"); - Assert.assertEquals(Status.USER_DISABLED.getCode(), (int) result1.getCode()); + Assertions.assertEquals(Status.USER_DISABLED.getCode(), (int) result1.getCode()); logger.info(result1.toString()); } @@ -107,6 +108,6 @@ public class PasswordAuthenticatorTest extends AbstractControllerTest { when(sessionService.getSession(request)).thenReturn(mockSession); User user = authenticator.getAuthUser(request); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AccessTokenServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AccessTokenServiceTest.java index 12930e00f3..6c0eb404c4 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AccessTokenServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AccessTokenServiceTest.java @@ -19,8 +19,6 @@ package org.apache.dolphinscheduler.api.service; import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.ACCESS_TOKEN_DELETE; import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.ACCESS_TOKEN_UPDATE; - -import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @@ -46,13 +44,15 @@ import java.util.List; import java.util.Map; import org.assertj.core.util.Lists; -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.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; @@ -62,8 +62,10 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * access token service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class AccessTokenServiceTest { + private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); private static final Logger logger = LoggerFactory.getLogger(AccessTokenServiceTest.class); @@ -87,14 +89,14 @@ public class AccessTokenServiceTest { when(accessTokenMapper.selectAccessTokenPage(any(Page.class), eq("zhangsan"), eq(0))).thenReturn(tokenPage); Result result = accessTokenService.queryAccessTokenList(user, "zhangsan", 1, 10); PageInfo pageInfo = (PageInfo) result.getData(); - assertEquals(0, (int) pageInfo.getTotal()); + Assertions.assertEquals(0, (int) pageInfo.getTotal()); tokenPage.setTotal(1L); when(accessTokenMapper.selectAccessTokenPage(any(Page.class), eq("zhangsan"), eq(0))).thenReturn(tokenPage); result = accessTokenService.queryAccessTokenList(user, "zhangsan", 1, 10); pageInfo = (PageInfo) result.getData(); logger.info(result.toString()); - Assert.assertTrue(pageInfo.getTotal() > 0); + Assertions.assertTrue(pageInfo.getTotal() > 0); } @Test @@ -105,7 +107,7 @@ public class AccessTokenServiceTest { Mockito.when(this.accessTokenMapper.queryAccessTokenByUser(Mockito.anyInt())).thenReturn(accessTokenList); Map result = this.accessTokenService.queryAccessTokenByUser(user, 1); logger.info(result.toString()); - assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -114,12 +116,12 @@ public class AccessTokenServiceTest { when(accessTokenMapper.insert(any(AccessToken.class))).thenReturn(2); Result result = accessTokenService.createToken(getLoginUser(), 1, getDate(), "AccessTokenServiceTest"); logger.info(result.toString()); - assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); // Token is absent result = this.accessTokenService.createToken(getLoginUser(), 1, getDate(), null); logger.info(result.toString()); - assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -127,11 +129,11 @@ public class AccessTokenServiceTest { User user = new User(); user.setId(1); user.setUserType(UserType.ADMIN_USER); - Map result = accessTokenService.generateToken(getLoginUser(), Integer.MAX_VALUE,getDate()); + Map result = accessTokenService.generateToken(getLoginUser(), Integer.MAX_VALUE, getDate()); logger.info(result.toString()); - assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); String token = (String) result.get(Constants.DATA_LIST); - Assert.assertNotNull(token); + Assertions.assertNotNull(token); } @Test @@ -141,24 +143,27 @@ public class AccessTokenServiceTest { User userLogin = new User(); userLogin.setId(1); userLogin.setUserType(UserType.ADMIN_USER); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 1, ACCESS_TOKEN_DELETE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 1, + ACCESS_TOKEN_DELETE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, + baseServiceLogger)).thenReturn(true); // not exist Map result = accessTokenService.delAccessTokenById(userLogin, 0); logger.info(result.toString()); - assertEquals(Status.ACCESS_TOKEN_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ACCESS_TOKEN_NOT_EXIST, result.get(Constants.STATUS)); // no operate userLogin.setId(2); result = accessTokenService.delAccessTokenById(userLogin, 1); logger.info(result.toString()); - assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); - //success + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + // success userLogin.setId(1); userLogin.setUserType(UserType.ADMIN_USER); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, + baseServiceLogger)).thenReturn(true); result = accessTokenService.delAccessTokenById(userLogin, 1); logger.info(result.toString()); - assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -166,26 +171,30 @@ public class AccessTokenServiceTest { User user = new User(); user.setId(1); user.setUserType(UserType.ADMIN_USER); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 1, ACCESS_TOKEN_UPDATE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 1, + ACCESS_TOKEN_UPDATE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, + baseServiceLogger)).thenReturn(true); // Given Token when(accessTokenMapper.selectById(1)).thenReturn(getEntity()); - Map result = accessTokenService.updateToken(getLoginUser(), 1,Integer.MAX_VALUE,getDate(),"token"); + Map result = + accessTokenService.updateToken(getLoginUser(), 1, Integer.MAX_VALUE, getDate(), "token"); logger.info(result.toString()); - assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - Assert.assertNotNull(result.get(Constants.DATA_LIST)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertNotNull(result.get(Constants.DATA_LIST)); // Token is absent - result = accessTokenService.updateToken(getLoginUser(), 1, Integer.MAX_VALUE,getDate(),null); + result = accessTokenService.updateToken(getLoginUser(), 1, Integer.MAX_VALUE, getDate(), null); logger.info(result.toString()); - assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - Assert.assertNotNull(result.get(Constants.DATA_LIST)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertNotNull(result.get(Constants.DATA_LIST)); // ACCESS_TOKEN_NOT_EXIST - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, baseServiceLogger)).thenReturn(true); - result = accessTokenService.updateToken(getLoginUser(), 2,Integer.MAX_VALUE,getDate(),"token"); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 0, + baseServiceLogger)).thenReturn(true); + result = accessTokenService.updateToken(getLoginUser(), 2, Integer.MAX_VALUE, getDate(), "token"); logger.info(result.toString()); - assertEquals(Status.ACCESS_TOKEN_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ACCESS_TOKEN_NOT_EXIST, result.get(Constants.STATUS)); } private User getLoginUser() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java index 017c9aab19..2197dc163b 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java @@ -17,7 +17,9 @@ package org.apache.dolphinscheduler.api.service; -import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.*; +import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.ALERT_GROUP_CREATE; +import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.ALERT_GROUP_DELETE; +import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.ALERT_GROUP_UPDATE; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -42,14 +44,14 @@ import java.util.List; import java.util.Map; import java.util.Set; -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.Mockito; import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.dao.DuplicateKeyException; @@ -60,7 +62,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * alert group service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class AlertGroupServiceTest { private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); @@ -85,7 +87,7 @@ public class AlertGroupServiceTest { Map result = alertGroupService.queryAlertgroup(getLoginUser()); logger.info(result.toString()); List alertGroups = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(alertGroups)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(alertGroups)); } @Test @@ -103,14 +105,14 @@ public class AlertGroupServiceTest { ids.add(1); Result result = alertGroupService.listPaging(user, groupName, 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); // success user.setUserType(UserType.ADMIN_USER); user.setId(0); result = alertGroupService.listPaging(user, groupName, 1, 10); logger.info(result.toString()); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @@ -124,7 +126,7 @@ public class AlertGroupServiceTest { user.setUserType(UserType.GENERAL_USER); Map result = alertGroupService.createAlertgroup(user, groupName, groupName, null); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); user.setUserType(UserType.ADMIN_USER); user.setId(0); // success @@ -134,8 +136,8 @@ public class AlertGroupServiceTest { user.getId(), baseServiceLogger)).thenReturn(true); result = alertGroupService.createAlertgroup(user, groupName, groupName, null); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - Assert.assertNotNull(result.get(Constants.DATA_LIST)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertNotNull(result.get(Constants.DATA_LIST)); } @Test @@ -152,7 +154,7 @@ public class AlertGroupServiceTest { user.getId(), baseServiceLogger)).thenReturn(true); Map result = alertGroupService.createAlertgroup(user, groupName, groupName, null); logger.info(result.toString()); - Assert.assertEquals(Status.ALERT_GROUP_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ALERT_GROUP_EXIST, result.get(Constants.STATUS)); } @Test @@ -164,7 +166,7 @@ public class AlertGroupServiceTest { user.setUserType(UserType.GENERAL_USER); Map result = alertGroupService.updateAlertgroup(user, 1, groupName, groupName, null); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); user.setUserType(UserType.ADMIN_USER); // not exist user.setUserType(UserType.ADMIN_USER); @@ -174,14 +176,14 @@ public class AlertGroupServiceTest { new Object[]{1}, 0, baseServiceLogger)).thenReturn(true); result = alertGroupService.updateAlertgroup(user, 1, groupName, groupName, null); logger.info(result.toString()); - Assert.assertEquals(Status.ALERT_GROUP_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ALERT_GROUP_NOT_EXIST, result.get(Constants.STATUS)); // success Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ALERT_GROUP, new Object[]{2}, user.getId(), baseServiceLogger)).thenReturn(true); Mockito.when(alertGroupMapper.selectById(2)).thenReturn(getEntity()); result = alertGroupService.updateAlertgroup(user, 2, groupName, groupName, null); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @@ -198,7 +200,7 @@ public class AlertGroupServiceTest { Mockito.when(alertGroupMapper.updateById(Mockito.any())) .thenThrow(new DuplicateKeyException("group name exist")); Map result = alertGroupService.updateAlertgroup(user, 2, groupName, groupName, null); - Assert.assertEquals(Status.ALERT_GROUP_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ALERT_GROUP_EXIST, result.get(Constants.STATUS)); } @Test @@ -212,7 +214,7 @@ public class AlertGroupServiceTest { user.getId(), ALERT_GROUP_DELETE, baseServiceLogger)).thenReturn(true); Map result = alertGroupService.delAlertgroupById(user, 1); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // not exist user.setUserType(UserType.ADMIN_USER); @@ -223,14 +225,14 @@ public class AlertGroupServiceTest { new Object[]{2}, 0, baseServiceLogger)).thenReturn(true); result = alertGroupService.delAlertgroupById(user, 2); logger.info(result.toString()); - Assert.assertEquals(Status.ALERT_GROUP_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ALERT_GROUP_NOT_EXIST, result.get(Constants.STATUS)); // success Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ALERT_GROUP, new Object[]{2}, 0, baseServiceLogger)).thenReturn(true); Mockito.when(alertGroupMapper.selectById(2)).thenReturn(getEntity()); result = alertGroupService.delAlertgroupById(user, 2); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @@ -238,12 +240,12 @@ public class AlertGroupServiceTest { public void testVerifyGroupName() { // group name not exist boolean result = alertGroupService.existGroupName(groupName); - Assert.assertFalse(result); + Assertions.assertFalse(result); Mockito.when(alertGroupMapper.existGroupName(groupName)).thenReturn(true); // group name exist result = alertGroupService.existGroupName(groupName); - Assert.assertTrue(result); + Assertions.assertTrue(result); } /** diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceServiceTest.java index 7fe691c841..93773e4338 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceServiceTest.java @@ -17,7 +17,12 @@ package org.apache.dolphinscheduler.api.service; +import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.ALART_INSTANCE_CREATE; +import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.ALERT_PLUGIN_DELETE; +import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.ALERT_PLUGIN_UPDATE; + import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.permission.ResourcePermissionCheckService; import org.apache.dolphinscheduler.api.service.impl.AlertPluginInstanceServiceImpl; import org.apache.dolphinscheduler.api.service.impl.BaseServiceImpl; import org.apache.dolphinscheduler.common.Constants; @@ -36,25 +41,23 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import org.apache.dolphinscheduler.api.permission.ResourcePermissionCheckService; -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 org.slf4j.Logger; import org.slf4j.LoggerFactory; -import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.*; - /** * alert plugin instance service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class AlertPluginInstanceServiceTest { + private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); @InjectMocks @@ -152,7 +155,7 @@ public class AlertPluginInstanceServiceTest { private String paramsMap = "{\"path\":\"/kris/script/path\",\"userParams\":\"userParams\",\"type\":\"0\"}"; - @Before + @BeforeEach public void before() { user = new User(); user.setUserType(UserType.ADMIN_USER); @@ -169,40 +172,47 @@ public class AlertPluginInstanceServiceTest { @Test public void testCreate() { Mockito.when(alertPluginInstanceMapper.existInstanceName("test")).thenReturn(true); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, null, 1, ALART_INSTANCE_CREATE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, + null, 1, ALART_INSTANCE_CREATE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, + null, 0, baseServiceLogger)).thenReturn(true); Map result = alertPluginInstanceService.create(user, 1, "test", uiParams); - Assert.assertEquals(Status.PLUGIN_INSTANCE_ALREADY_EXIT, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.PLUGIN_INSTANCE_ALREADY_EXIT, result.get(Constants.STATUS)); Mockito.when(alertPluginInstanceMapper.insert(Mockito.any())).thenReturn(1); result = alertPluginInstanceService.create(user, 1, "test1", uiParams); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); - Assert.assertNotNull(result.get(Constants.DATA_LIST)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertNotNull(result.get(Constants.DATA_LIST)); } @Test public void testDelete() { List ids = Arrays.asList("11,2,3", null, "98,1"); Mockito.when(alertGroupMapper.queryInstanceIdsList()).thenReturn(ids); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, null, 1, ALERT_PLUGIN_DELETE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, + null, 1, ALERT_PLUGIN_DELETE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, + null, 0, baseServiceLogger)).thenReturn(true); Map result = alertPluginInstanceService.delete(user, 1); - Assert.assertEquals(Status.DELETE_ALERT_PLUGIN_INSTANCE_ERROR_HAS_ALERT_GROUP_ASSOCIATED, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.DELETE_ALERT_PLUGIN_INSTANCE_ERROR_HAS_ALERT_GROUP_ASSOCIATED, + result.get(Constants.STATUS)); Mockito.when(alertPluginInstanceMapper.deleteById(9)).thenReturn(1); result = alertPluginInstanceService.delete(user, 9); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test public void testUpdate() { Mockito.when(alertPluginInstanceMapper.updateById(Mockito.any())).thenReturn(0); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, null, 1, ALERT_PLUGIN_UPDATE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, + null, 1, ALERT_PLUGIN_UPDATE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.ALERT_PLUGIN_INSTANCE, + null, 0, baseServiceLogger)).thenReturn(true); Map result = alertPluginInstanceService.update(user, 1, "testUpdate", uiParams); - Assert.assertEquals(Status.SAVE_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SAVE_ERROR, result.get(Constants.STATUS)); Mockito.when(alertPluginInstanceMapper.updateById(Mockito.any())).thenReturn(1); result = alertPluginInstanceService.update(user, 1, "testUpdate", uiParams); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -219,7 +229,7 @@ public class AlertPluginInstanceServiceTest { Mockito.when(alertPluginInstanceMapper.queryAllAlertPluginInstanceList()).thenReturn(pluginInstanceList); Mockito.when(pluginDefineMapper.queryAllPluginDefineList()).thenReturn(pluginDefines); Map result = alertPluginInstanceService.queryAll(); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AuditServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AuditServiceTest.java index c0cf9ad3ef..64ca0e72c2 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AuditServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AuditServiceTest.java @@ -32,13 +32,13 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -48,7 +48,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * audit service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class AuditServiceTest { private static final Logger logger = LoggerFactory.getLogger(AuditServiceTest.class); @@ -69,10 +69,11 @@ public class AuditServiceTest { page.setTotal(1L); when(auditLogMapper.queryAuditLog(Mockito.any(Page.class), Mockito.any(), Mockito.any(), Mockito.eq(""), eq(start), eq(end))) - .thenReturn(page); - Result result = auditService.queryLogListPaging(new User(), null, null, "2020-11-01 00:00:00", "2020-11-02 00:00:00", "", 1, 10); + .thenReturn(page); + Result result = auditService.queryLogListPaging(new User(), null, null, "2020-11-01 00:00:00", + "2020-11-02 00:00:00", "", 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); } private List getLists() { @@ -88,4 +89,4 @@ public class AuditServiceTest { auditLog.setResourceType(0); return auditLog; } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java index be4c433e2e..325b499841 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java @@ -27,19 +27,19 @@ import org.apache.dolphinscheduler.service.storage.impl.HadoopUtils; import java.util.HashMap; import java.util.Map; -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.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * base service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class BaseServiceTest { private static final Logger logger = LoggerFactory.getLogger(BaseServiceTest.class); @@ -49,7 +49,7 @@ public class BaseServiceTest { @Mock private HadoopUtils hadoopUtils; - @Before + @BeforeEach public void setUp() { baseService = new BaseServiceImpl(); } @@ -60,10 +60,10 @@ public class BaseServiceTest { User user = new User(); user.setUserType(UserType.ADMIN_USER); // ADMIN_USER - Assert.assertTrue(baseService.isAdmin(user)); + Assertions.assertTrue(baseService.isAdmin(user)); // GENERAL_USER user.setUserType(UserType.GENERAL_USER); - Assert.assertFalse(baseService.isAdmin(user)); + Assertions.assertFalse(baseService.isAdmin(user)); } @@ -72,7 +72,7 @@ public class BaseServiceTest { Map result = new HashMap<>(); baseService.putMsg(result, Status.SUCCESS); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); // has params baseService.putMsg(result, Status.PROJECT_NOT_FOUND, "test"); @@ -83,7 +83,7 @@ public class BaseServiceTest { Result result = new Result(); baseService.putMsg(result, Status.SUCCESS); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); // has params baseService.putMsg(result, Status.PROJECT_NOT_FOUND, "test"); } @@ -94,12 +94,12 @@ public class BaseServiceTest { User user = new User(); user.setId(1); // create user - Assert.assertTrue(baseService.canOperator(user, 1)); + Assertions.assertTrue(baseService.canOperator(user, 1)); // admin user.setId(2); user.setUserType(UserType.ADMIN_USER); - Assert.assertTrue(baseService.canOperator(user, 1)); + Assertions.assertTrue(baseService.canOperator(user, 1)); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ClusterServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ClusterServiceTest.java index 3659fbc937..e406a42aa5 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ClusterServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ClusterServiceTest.java @@ -37,15 +37,15 @@ import java.util.List; import java.util.Map; import org.assertj.core.util.Lists; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -55,7 +55,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * cluster service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ClusterServiceTest { public static final Logger logger = LoggerFactory.getLogger(ClusterServiceTest.class); @@ -76,11 +76,11 @@ public class ClusterServiceTest { public static final String clusterName = "Env1"; - @Before + @BeforeEach public void setUp() { } - @After + @AfterEach public void after() { } @@ -89,36 +89,36 @@ public class ClusterServiceTest { User loginUser = getGeneralUser(); Map result = clusterService.createCluster(loginUser, clusterName, getConfig(), getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); loginUser = getAdminUser(); result = clusterService.createCluster(loginUser, clusterName, "", getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_CONFIG_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_CONFIG_IS_NULL, result.get(Constants.STATUS)); result = clusterService.createCluster(loginUser, "", getConfig(), getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_NAME_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_NAME_IS_NULL, result.get(Constants.STATUS)); Mockito.when(clusterMapper.queryByClusterName(clusterName)).thenReturn(getCluster()); result = clusterService.createCluster(loginUser, clusterName, getConfig(), getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_NAME_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_NAME_EXISTS, result.get(Constants.STATUS)); Mockito.when(clusterMapper.insert(Mockito.any(Cluster.class))).thenReturn(1); result = clusterService.createCluster(loginUser, "testName", "testConfig", "testDesc"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test public void testCheckParams() { Map result = clusterService.checkParams(clusterName, getConfig()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); result = clusterService.checkParams("", getConfig()); - Assert.assertEquals(Status.CLUSTER_NAME_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_NAME_IS_NULL, result.get(Constants.STATUS)); result = clusterService.checkParams(clusterName, ""); - Assert.assertEquals(Status.CLUSTER_CONFIG_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_CONFIG_IS_NULL, result.get(Constants.STATUS)); } @Test @@ -127,32 +127,32 @@ public class ClusterServiceTest { Map result = clusterService.updateClusterByCode(loginUser, 1L, clusterName, getConfig(), getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); loginUser = getAdminUser(); result = clusterService.updateClusterByCode(loginUser, 1L, clusterName, "", getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_CONFIG_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_CONFIG_IS_NULL, result.get(Constants.STATUS)); result = clusterService.updateClusterByCode(loginUser, 1L, "", getConfig(), getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_NAME_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_NAME_IS_NULL, result.get(Constants.STATUS)); result = clusterService.updateClusterByCode(loginUser, 2L, clusterName, getConfig(), getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_NOT_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_NOT_EXISTS, result.get(Constants.STATUS)); Mockito.when(clusterMapper.queryByClusterName(clusterName)).thenReturn(getCluster()); result = clusterService.updateClusterByCode(loginUser, 2L, clusterName, getConfig(), getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_NAME_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_NAME_EXISTS, result.get(Constants.STATUS)); Mockito.when(clusterMapper.updateById(Mockito.any(Cluster.class))).thenReturn(1); Mockito.when(clusterMapper.queryByClusterCode(1L)).thenReturn(getCluster()); result = clusterService.updateClusterByCode(loginUser, 1L, "testName", getConfig(), "test"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @@ -161,10 +161,10 @@ public class ClusterServiceTest { Mockito.when(clusterMapper.queryAllClusterList()).thenReturn(Lists.newArrayList(getCluster())); Map result = clusterService.queryAllClusterList(); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List list = (List) (result.get(Constants.DATA_LIST)); - Assert.assertEquals(1, list.size()); + Assertions.assertEquals(1, list.size()); } @Test @@ -178,7 +178,7 @@ public class ClusterServiceTest { Result result = clusterService.queryClusterListPaging(1, 10, clusterName); logger.info(result.toString()); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @Test @@ -186,12 +186,12 @@ public class ClusterServiceTest { Mockito.when(clusterMapper.queryByClusterName(clusterName)).thenReturn(null); Map result = clusterService.queryClusterByName(clusterName); logger.info(result.toString()); - Assert.assertEquals(Status.QUERY_CLUSTER_BY_NAME_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.QUERY_CLUSTER_BY_NAME_ERROR, result.get(Constants.STATUS)); Mockito.when(clusterMapper.queryByClusterName(clusterName)).thenReturn(getCluster()); result = clusterService.queryClusterByName(clusterName); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -199,12 +199,12 @@ public class ClusterServiceTest { Mockito.when(clusterMapper.queryByClusterCode(1L)).thenReturn(null); Map result = clusterService.queryClusterByCode(1L); logger.info(result.toString()); - Assert.assertEquals(Status.QUERY_CLUSTER_BY_CODE_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.QUERY_CLUSTER_BY_CODE_ERROR, result.get(Constants.STATUS)); Mockito.when(clusterMapper.queryByClusterCode(1L)).thenReturn(getCluster()); result = clusterService.queryClusterByCode(1L); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -212,30 +212,30 @@ public class ClusterServiceTest { User loginUser = getGeneralUser(); Map result = clusterService.deleteClusterByCode(loginUser, 1L); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); loginUser = getAdminUser(); Mockito.when(clusterMapper.deleteByCode(1L)).thenReturn(1); result = clusterService.deleteClusterByCode(loginUser, 1L); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); Mockito.when(k8sNamespaceMapper.selectCount(Mockito.any())).thenReturn(1L); result = clusterService.deleteClusterByCode(loginUser, 1L); logger.info(result.toString()); - Assert.assertEquals(Status.DELETE_CLUSTER_RELATED_NAMESPACE_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.DELETE_CLUSTER_RELATED_NAMESPACE_EXISTS, result.get(Constants.STATUS)); } @Test public void testVerifyCluster() { Map result = clusterService.verifyCluster(""); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_NAME_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_NAME_IS_NULL, result.get(Constants.STATUS)); Mockito.when(clusterMapper.queryByClusterName(clusterName)).thenReturn(getCluster()); result = clusterService.verifyCluster(clusterName); logger.info(result.toString()); - Assert.assertEquals(Status.CLUSTER_NAME_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.CLUSTER_NAME_EXISTS, result.get(Constants.STATUS)); } private Cluster getCluster() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java index d732be6f03..de26867826 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java @@ -51,22 +51,25 @@ import java.util.List; import java.util.Map; import java.util.Set; -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.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; /** * data analysis service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class DataAnalysisServiceTest { private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); @@ -104,7 +107,7 @@ public class DataAnalysisServiceTest { private User user; - @Before + @BeforeEach public void setUp() { user = new User(); @@ -117,7 +120,7 @@ public class DataAnalysisServiceTest { Mockito.when(projectMapper.queryByCode(1L)).thenReturn(project); } - @After + @AfterEach public void after() { user = null; projectMapper = null; @@ -136,7 +139,7 @@ public class DataAnalysisServiceTest { // SUCCESS result = dataAnalysisServiceImpl.countTaskStateByProject(user, 1, startDate, endDate); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -149,7 +152,7 @@ public class DataAnalysisServiceTest { putMsg(failResult, Status.PROJECT_NOT_FOUND, 1); Mockito.when(projectService.checkProjectAndAuth(any(), any(), anyLong(), any())).thenReturn(failResult); failResult = dataAnalysisServiceImpl.countTaskStateByProject(user, 1, startDate, endDate); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, failResult.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, failResult.get(Constants.STATUS)); } @Test @@ -163,19 +166,19 @@ public class DataAnalysisServiceTest { String startDate2 = "illegalDateString"; String endDate2 = "illegalDateString"; result = dataAnalysisServiceImpl.countTaskStateByProject(user, 1, startDate2, endDate2); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); // when one of date in illegal format then return error message String startDate3 = "2020-08-28 14:13:40"; String endDate3 = "illegalDateString"; result = dataAnalysisServiceImpl.countTaskStateByProject(user, 1, startDate3, endDate3); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); // when one of date in illegal format then return error message String startDate4 = "illegalDateString"; String endDate4 = "2020-08-28 14:13:40"; result = dataAnalysisServiceImpl.countTaskStateByProject(user, 1, startDate4, endDate4); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); } @Test @@ -214,7 +217,7 @@ public class DataAnalysisServiceTest { Mockito.when(taskInstanceMapper.countTaskInstanceStateByProjectCodes(any(), any(), any())) .thenReturn(null); result = dataAnalysisServiceImpl.countTaskStateByProject(user, 1, null, null); - Assert.assertNull(result.get(Constants.DATA_LIST)); + Assertions.assertNull(result.get(Constants.DATA_LIST)); } @Test @@ -229,7 +232,7 @@ public class DataAnalysisServiceTest { putMsg(failResult, Status.PROJECT_NOT_FOUND, 1); Mockito.when(projectService.checkProjectAndAuth(any(), any(), anyLong(), any())).thenReturn(failResult); failResult = dataAnalysisServiceImpl.countProcessInstanceStateByProject(user, 1, startDate, endDate); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, failResult.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, failResult.get(Constants.STATUS)); Map result = new HashMap<>(); putMsg(result, Status.SUCCESS, null); @@ -237,7 +240,7 @@ public class DataAnalysisServiceTest { // SUCCESS result = dataAnalysisServiceImpl.countProcessInstanceStateByProject(user, 1, startDate, endDate); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -249,12 +252,12 @@ public class DataAnalysisServiceTest { Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.PROJECTS, 1, serviceLogger)).thenReturn(projectIds()); result = dataAnalysisServiceImpl.countDefinitionByUser(user, 0); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.PROJECTS, 1, serviceLogger)).thenReturn(Collections.emptySet()); result = dataAnalysisServiceImpl.countDefinitionByUser(user, 0); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -264,7 +267,7 @@ public class DataAnalysisServiceTest { user.setId(1); Map result = dataAnalysisServiceImpl.countCommandState(user); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); // when no command found then return all count are 0 Mockito.when(commandMapper.countCommandState(any(), any(), any())).thenReturn(Collections.emptyList()); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java index 41e378e671..9bc17f1116 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java @@ -55,21 +55,21 @@ import java.util.List; import java.util.Map; import java.util.Set; -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.MockedStatic; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * data source service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class DataSourceServiceTest { private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); @@ -109,7 +109,7 @@ public class DataSourceServiceTest { dataSourceList.add(dataSource); Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(dataSourceList); Result dataSourceExitsResult = dataSourceService.createDataSource(loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.DATASOURCE_EXIST.getCode(), dataSourceExitsResult.getCode().intValue()); + Assertions.assertEquals(Status.DATASOURCE_EXIST.getCode(), dataSourceExitsResult.getCode().intValue()); ConnectionParam connectionParam = DataSourceUtils.buildConnectionParams(postgreSqlDatasourceParam); DbType dataSourceType = postgreSqlDatasourceParam.getType(); @@ -120,20 +120,20 @@ public class DataSourceServiceTest { Mockito.doReturn(connectionResult).when(dataSourceService).checkConnection(dataSourceType, connectionParam); Result connectFailedResult = dataSourceService.createDataSource(loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.DATASOURCE_CONNECT_FAILED.getCode(), connectFailedResult.getCode().intValue()); + Assertions.assertEquals(Status.DATASOURCE_CONNECT_FAILED.getCode(), connectFailedResult.getCode().intValue()); // data source exits Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(null); connectionResult = new Result(Status.SUCCESS.getCode(), Status.SUCCESS.getMsg()); Mockito.when(dataSourceService.checkConnection(dataSourceType, connectionParam)).thenReturn(connectionResult); Result notValidError = dataSourceService.createDataSource(loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), notValidError.getCode().intValue()); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), notValidError.getCode().intValue()); // success Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(null); Mockito.when(dataSourceService.checkConnection(dataSourceType, connectionParam)).thenReturn(connectionResult); Result success = dataSourceService.createDataSource(loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.SUCCESS.getCode(), success.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), success.getCode().intValue()); } public void updateDataSourceTest() { @@ -156,14 +156,14 @@ public class DataSourceServiceTest { Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); Result resourceNotExits = dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getCode(), resourceNotExits.getCode().intValue()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getCode(), resourceNotExits.getCode().intValue()); // user no operation perm DataSource dataSource = new DataSource(); dataSource.setUserId(0); Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); Result userNoOperationPerm = dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM.getCode(), userNoOperationPerm.getCode().intValue()); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM.getCode(), userNoOperationPerm.getCode().intValue()); // data source name exits dataSource.setUserId(-1); @@ -173,7 +173,7 @@ public class DataSourceServiceTest { Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(dataSourceList); Result dataSourceNameExist = dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.DATASOURCE_EXIST.getCode(), dataSourceNameExist.getCode().intValue()); + Assertions.assertEquals(Status.DATASOURCE_EXIST.getCode(), dataSourceNameExist.getCode().intValue()); // data source connect failed DbType dataSourceType = postgreSqlDatasourceParam.getType(); @@ -183,7 +183,7 @@ public class DataSourceServiceTest { Result connectionResult = new Result(Status.SUCCESS.getCode(), Status.SUCCESS.getMsg()); Mockito.when(dataSourceService.checkConnection(dataSourceType, connectionParam)).thenReturn(connectionResult); Result connectFailed = dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.DATASOURCE_CONNECT_FAILED.getCode(), connectFailed.getCode().intValue()); + Assertions.assertEquals(Status.DATASOURCE_CONNECT_FAILED.getCode(), connectFailed.getCode().intValue()); // success Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); @@ -192,7 +192,7 @@ public class DataSourceServiceTest { new Result(Status.DATASOURCE_CONNECT_FAILED.getCode(), Status.DATASOURCE_CONNECT_FAILED.getMsg()); Mockito.when(dataSourceService.checkConnection(dataSourceType, connectionParam)).thenReturn(connectionResult); Result success = dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); - Assert.assertEquals(Status.SUCCESS.getCode(), success.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), success.getCode().intValue()); } @@ -204,7 +204,7 @@ public class DataSourceServiceTest { int pageSize = 10; Result result = dataSourceService.queryDataSourceListPaging(loginUser, searchVal, pageNo, pageSize); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); } @Test @@ -212,7 +212,7 @@ public class DataSourceServiceTest { int dataSourceId = -1; Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); Result result = dataSourceService.connectionTest(dataSourceId); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getCode(), result.getCode().intValue()); } @Test @@ -223,14 +223,14 @@ public class DataSourceServiceTest { // resource not exist dataSourceService.putMsg(result, Status.RESOURCE_NOT_EXIST); Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); - Assert.assertEquals(result.getCode(), dataSourceService.delete(loginUser, dataSourceId).getCode()); + Assertions.assertEquals(result.getCode(), dataSourceService.delete(loginUser, dataSourceId).getCode()); // user no operation perm dataSourceService.putMsg(result, Status.USER_NO_OPERATION_PERM); DataSource dataSource = new DataSource(); dataSource.setUserId(0); Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); - Assert.assertEquals(result.getCode(), dataSourceService.delete(loginUser, dataSourceId).getCode()); + Assertions.assertEquals(result.getCode(), dataSourceService.delete(loginUser, dataSourceId).getCode()); // success dataSourceService.putMsg(result, Status.SUCCESS); @@ -243,7 +243,7 @@ public class DataSourceServiceTest { Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATASOURCE, new Object[]{dataSource.getId()}, 0, baseServiceLogger)).thenReturn(true); Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); - Assert.assertEquals(result.getCode(), dataSourceService.delete(loginUser, dataSourceId).getCode()); + Assertions.assertEquals(result.getCode(), dataSourceService.delete(loginUser, dataSourceId).getCode()); } @@ -263,7 +263,7 @@ public class DataSourceServiceTest { Map result = dataSourceService.unauthDatasource(loginUser, userId); logger.info(result.toString()); List dataSources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(dataSources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(dataSources)); // test non-admin user loginUser.setId(2); @@ -273,7 +273,7 @@ public class DataSourceServiceTest { result = dataSourceService.unauthDatasource(loginUser, userId); logger.info(result.toString()); dataSources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(dataSources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(dataSources)); } @Test @@ -288,14 +288,14 @@ public class DataSourceServiceTest { Map result = dataSourceService.authedDatasource(loginUser, userId); logger.info(result.toString()); List dataSources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(dataSources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(dataSources)); // test non-admin user loginUser.setId(2); loginUser.setUserType(UserType.GENERAL_USER); Map success = dataSourceService.authedDatasource(loginUser, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, success.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, success.get(Constants.STATUS)); } @Test @@ -312,7 +312,7 @@ public class DataSourceServiceTest { Mockito.when(dataSourceMapper.selectBatchIds(dataSourceIds)).thenReturn(Collections.singletonList(dataSource)); Map map = dataSourceService.queryDataSourceList(loginUser, DbType.MYSQL.ordinal(), Constants.TEST_FLAG_NO); - Assert.assertEquals(Status.SUCCESS, map.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, map.get(Constants.STATUS)); } @Test @@ -322,18 +322,18 @@ public class DataSourceServiceTest { String dataSourceName = "dataSource1"; Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(getDataSourceList()); Result result = dataSourceService.verifyDataSourceName(dataSourceName); - Assert.assertEquals(Status.DATASOURCE_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.DATASOURCE_EXIST.getMsg(), result.getMsg()); } @Test public void queryDataSourceTest() { Mockito.when(dataSourceMapper.selectById(Mockito.anyInt())).thenReturn(null); Map result = dataSourceService.queryDataSource(Mockito.anyInt()); - Assert.assertEquals(((Status) result.get(Constants.STATUS)).getCode(), Status.RESOURCE_NOT_EXIST.getCode()); + Assertions.assertEquals(((Status) result.get(Constants.STATUS)).getCode(), Status.RESOURCE_NOT_EXIST.getCode()); Mockito.when(dataSourceMapper.selectById(Mockito.anyInt())).thenReturn(getOracleDataSource()); result = dataSourceService.queryDataSource(Mockito.anyInt()); - Assert.assertEquals(((Status) result.get(Constants.STATUS)).getCode(), Status.SUCCESS.getCode()); + Assertions.assertEquals(((Status) result.get(Constants.STATUS)).getCode(), Status.SUCCESS.getCode()); } private List getDataSourceList() { @@ -388,7 +388,7 @@ public class DataSourceServiceTest { String expected = "{\"user\":\"test\",\"password\":\"test\",\"address\":\"jdbc:oracle:thin:@//192.168.9.1:1521\",\"database\":\"im\",\"jdbcUrl\":\"jdbc:oracle:thin:@//192.168.9.1:1521/im\"," + "\"driverClassName\":\"oracle.jdbc.OracleDriver\",\"validationQuery\":\"select 1 from dual\",\"connectType\":\"ORACLE_SERVICE_NAME\"}"; - Assert.assertEquals(expected, JSONUtils.toJsonString(connectionParam)); + Assertions.assertEquals(expected, JSONUtils.toJsonString(connectionParam)); try (MockedStatic mockedStaticCommonUtils = Mockito.mockStatic(CommonUtils.class)) { mockedStaticCommonUtils.when(CommonUtils::getKerberosStartupState).thenReturn(true); @@ -409,7 +409,7 @@ public class DataSourceServiceTest { + "\"jdbcUrl\":\"jdbc:hive2://192.168.9.1:10000/im\",\"driverClassName\":\"org.apache.hive.jdbc.HiveDriver\",\"validationQuery\":\"select 1\"," + "\"principal\":\"hive/hdfs-mycluster@ESZ.COM\",\"javaSecurityKrb5Conf\":\"/opt/krb5.conf\",\"loginUserKeytabUsername\":\"test2/hdfs-mycluster@ESZ.COM\"," + "\"loginUserKeytabPath\":\"/opt/hdfs.headless.keytab\"}"; - Assert.assertEquals(expected, JSONUtils.toJsonString(connectionParam)); + Assertions.assertEquals(expected, JSONUtils.toJsonString(connectionParam)); } } @@ -433,7 +433,7 @@ public class DataSourceServiceTest { String expected = "{\"user\":\"test\",\"password\":\"bnVsbE1USXpORFUy\",\"address\":\"jdbc:mysql://192.168.9.1:1521\",\"database\":\"im\",\"jdbcUrl\":\"jdbc:mysql://192.168.9.1:1521/" + "im\",\"driverClassName\":\"com.mysql.cj.jdbc.Driver\",\"validationQuery\":\"select 1\",\"props\":{\"autoDeserialize\":\"yes\",\"allowUrlInLocalInfile\":\"true\"}}"; - Assert.assertEquals(expected, JSONUtils.toJsonString(connectionParam)); + Assertions.assertEquals(expected, JSONUtils.toJsonString(connectionParam)); } MySQLDataSourceParamDTO mysqlDatasourceParamDTO = new MySQLDataSourceParamDTO(); @@ -446,7 +446,7 @@ public class DataSourceServiceTest { String expected = "{\"user\":\"test\",\"password\":\"123456\",\"address\":\"jdbc:mysql://192.168.9.1:1521\",\"database\":\"im\"," + "\"jdbcUrl\":\"jdbc:mysql://192.168.9.1:1521/im\",\"driverClassName\":\"com.mysql.cj.jdbc.Driver\",\"validationQuery\":\"select 1\"}"; - Assert.assertEquals(expected, JSONUtils.toJsonString(connectionParam)); + Assertions.assertEquals(expected, JSONUtils.toJsonString(connectionParam)); } /** @@ -489,12 +489,12 @@ public class DataSourceServiceTest { mockedStaticDataSourceClientProvider.when(DataSourceClientProvider::getInstance).thenReturn(clientProvider); Result result = dataSourceService.checkConnection(dataSourceType, connectionParam); - Assert.assertEquals(Status.CONNECTION_TEST_FAILURE.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.CONNECTION_TEST_FAILURE.getCode(), result.getCode().intValue()); Connection connection = Mockito.mock(Connection.class); Mockito.when(clientProvider.getConnection(Mockito.any(), Mockito.any())).thenReturn(connection); result = dataSourceService.checkConnection(dataSourceType, connectionParam); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqExecuteResultServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqExecuteResultServiceTest.java index 9a27dd5a0d..86d2b6bbeb 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqExecuteResultServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqExecuteResultServiceTest.java @@ -23,6 +23,7 @@ import static org.mockito.Mockito.when; import org.apache.dolphinscheduler.api.ApiApplicationServer; import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.permission.ResourcePermissionCheckService; import org.apache.dolphinscheduler.api.service.impl.BaseServiceImpl; import org.apache.dolphinscheduler.api.service.impl.DqExecuteResultServiceImpl; import org.apache.dolphinscheduler.api.utils.Result; @@ -38,14 +39,15 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import org.apache.dolphinscheduler.api.permission.ResourcePermissionCheckService; -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.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 org.springframework.boot.test.context.SpringBootTest; @@ -53,9 +55,11 @@ import org.springframework.boot.test.context.SpringBootTest; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) @SpringBootTest(classes = ApiApplicationServer.class) public class DqExecuteResultServiceTest { + private static final Logger logger = LoggerFactory.getLogger(DqExecuteResultServiceTest.class); private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); @@ -79,17 +83,19 @@ public class DqExecuteResultServiceTest { User loginUser = new User(); loginUser.setId(1); loginUser.setUserType(UserType.ADMIN_USER); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATA_QUALITY, null, loginUser.getId(), null, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATA_QUALITY, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATA_QUALITY, null, + loginUser.getId(), null, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATA_QUALITY, null, 0, + baseServiceLogger)).thenReturn(true); Page page = new Page<>(1, 10); page.setTotal(1); page.setRecords(getExecuteResultList()); when(dqExecuteResultMapper.queryResultListPaging( - any(IPage.class), eq(""), eq(loginUser), any(),eq(ruleType), eq(start), eq(end))).thenReturn(page); + any(IPage.class), eq(""), eq(loginUser), any(), eq(ruleType), eq(start), eq(end))).thenReturn(page); Result result = dqExecuteResultService.queryResultListPaging( - loginUser,searchVal,1,0,"2020-01-01 00:00:00","2020-01-02 00:00:00",1,10); - Assert.assertEquals(Integer.valueOf(Status.SUCCESS.getCode()),result.getCode()); + loginUser, searchVal, 1, 0, "2020-01-01 00:00:00", "2020-01-02 00:00:00", 1, 10); + Assertions.assertEquals(Integer.valueOf(Status.SUCCESS.getCode()), result.getCode()); } public List getExecuteResultList() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqRuleServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqRuleServiceTest.java index 3e68d669a1..b28d2b2b18 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqRuleServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqRuleServiceTest.java @@ -53,13 +53,15 @@ import java.util.Date; import java.util.List; import java.util.Map; -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.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 org.springframework.boot.test.context.SpringBootTest; @@ -68,7 +70,8 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) @SpringBootTest(classes = ApiApplicationServer.class) public class DqRuleServiceTest { @@ -107,21 +110,21 @@ public class DqRuleServiceTest { + "\"统计值计算SQL\",\"validate\":[{\"required\":true,\"type\":\"string\",\"trigger\":\"blur\"}]}]"; when(dqRuleInputEntryMapper.getRuleInputEntryList(1)).thenReturn(getRuleInputEntryList()); Map result = dqRuleService.getRuleFormCreateJsonById(1); - Assert.assertEquals(json, result.get(Constants.DATA_LIST)); + Assertions.assertEquals(json, result.get(Constants.DATA_LIST)); } @Test public void testQueryAllRuleList() { when(dqRuleMapper.selectList(new QueryWrapper<>())).thenReturn(getRuleList()); Map result = dqRuleService.queryAllRuleList(); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test public void testGetDatasourceOptionsById() { when(dataSourceMapper.listAllDataSourceByType(DbType.MYSQL.getCode())).thenReturn(dataSourceList()); Map result = dqRuleService.queryAllRuleList(); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -151,7 +154,7 @@ public class DqRuleServiceTest { Result result = dqRuleService.queryRuleListPaging( loginUser, searchVal, 0, "2020-01-01 00:00:00", "2020-01-02 00:00:00", 1, 10); - Assert.assertEquals(Integer.valueOf(Status.SUCCESS.getCode()), result.getCode()); + Assertions.assertEquals(Integer.valueOf(Status.SUCCESS.getCode()), result.getCode()); } private List dataSourceList() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentServiceTest.java index 44aaf72e32..a911f290b5 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentServiceTest.java @@ -46,13 +46,15 @@ import java.util.Map; import java.util.Set; import org.assertj.core.util.Lists; -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.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; @@ -64,7 +66,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * environment service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class EnvironmentServiceTest { public static final Logger logger = LoggerFactory.getLogger(EnvironmentServiceTest.class); @@ -102,38 +105,38 @@ public class EnvironmentServiceTest { Map result = environmentService.createEnvironment(loginUser, environmentName, getConfig(), getDesc(), workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); loginUser = getAdminUser(); result = environmentService.createEnvironment(loginUser, environmentName, "", getDesc(), workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_CONFIG_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_CONFIG_IS_NULL, result.get(Constants.STATUS)); result = environmentService.createEnvironment(loginUser, "", getConfig(), getDesc(), workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_NAME_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_NAME_IS_NULL, result.get(Constants.STATUS)); result = environmentService.createEnvironment(loginUser, environmentName, getConfig(), getDesc(), "test"); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_WORKER_GROUPS_IS_INVALID, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_WORKER_GROUPS_IS_INVALID, result.get(Constants.STATUS)); Mockito.when(environmentMapper.queryByEnvironmentName(environmentName)).thenReturn(getEnvironment()); result = environmentService.createEnvironment(loginUser, environmentName, getConfig(), getDesc(), workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_NAME_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_NAME_EXISTS, result.get(Constants.STATUS)); Mockito.when(environmentMapper.insert(Mockito.any(Environment.class))).thenReturn(1); Mockito.when(relationMapper.insert(Mockito.any(EnvironmentWorkerGroupRelation.class))).thenReturn(1); result = environmentService.createEnvironment(loginUser, "testName", "test", "test", workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test public void testCheckParams() { Map result = environmentService.checkParams(environmentName, getConfig(), "test"); - Assert.assertEquals(Status.ENVIRONMENT_WORKER_GROUPS_IS_INVALID, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_WORKER_GROUPS_IS_INVALID, result.get(Constants.STATUS)); } @Test @@ -146,34 +149,34 @@ public class EnvironmentServiceTest { Map result = environmentService.updateEnvironmentByCode(loginUser, 1L, environmentName, getConfig(), getDesc(), workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); loginUser = getAdminUser(); result = environmentService.updateEnvironmentByCode(loginUser, 1L, environmentName, "", getDesc(), workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_CONFIG_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_CONFIG_IS_NULL, result.get(Constants.STATUS)); result = environmentService.updateEnvironmentByCode(loginUser, 1L, "", getConfig(), getDesc(), workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_NAME_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_NAME_IS_NULL, result.get(Constants.STATUS)); result = environmentService.updateEnvironmentByCode(loginUser, 1L, environmentName, getConfig(), getDesc(), "test"); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_WORKER_GROUPS_IS_INVALID, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_WORKER_GROUPS_IS_INVALID, result.get(Constants.STATUS)); Mockito.when(environmentMapper.queryByEnvironmentName(environmentName)).thenReturn(getEnvironment()); result = environmentService.updateEnvironmentByCode(loginUser, 2L, environmentName, getConfig(), getDesc(), workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_NAME_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_NAME_EXISTS, result.get(Constants.STATUS)); Mockito.when(environmentMapper.update(Mockito.any(Environment.class), Mockito.any(Wrapper.class))) .thenReturn(1); result = environmentService.updateEnvironmentByCode(loginUser, 1L, "testName", "test", "test", workerGroups); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -186,10 +189,10 @@ public class EnvironmentServiceTest { Map result = environmentService.queryAllEnvironmentList(getAdminUser()); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List list = (List) (result.get(Constants.DATA_LIST)); - Assert.assertEquals(1, list.size()); + Assertions.assertEquals(1, list.size()); } @Test @@ -203,7 +206,7 @@ public class EnvironmentServiceTest { Result result = environmentService.queryEnvironmentListPaging(getAdminUser(), 1, 10, environmentName); logger.info(result.toString()); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @Test @@ -211,12 +214,12 @@ public class EnvironmentServiceTest { Mockito.when(environmentMapper.queryByEnvironmentName(environmentName)).thenReturn(null); Map result = environmentService.queryEnvironmentByName(environmentName); logger.info(result.toString()); - Assert.assertEquals(Status.QUERY_ENVIRONMENT_BY_NAME_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.QUERY_ENVIRONMENT_BY_NAME_ERROR, result.get(Constants.STATUS)); Mockito.when(environmentMapper.queryByEnvironmentName(environmentName)).thenReturn(getEnvironment()); result = environmentService.queryEnvironmentByName(environmentName); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -224,12 +227,12 @@ public class EnvironmentServiceTest { Mockito.when(environmentMapper.queryByEnvironmentCode(1L)).thenReturn(null); Map result = environmentService.queryEnvironmentByCode(1L); logger.info(result.toString()); - Assert.assertEquals(Status.QUERY_ENVIRONMENT_BY_CODE_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.QUERY_ENVIRONMENT_BY_CODE_ERROR, result.get(Constants.STATUS)); Mockito.when(environmentMapper.queryByEnvironmentCode(1L)).thenReturn(getEnvironment()); result = environmentService.queryEnvironmentByCode(1L); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -241,31 +244,31 @@ public class EnvironmentServiceTest { 0, baseServiceLogger)).thenReturn(true); Map result = environmentService.deleteEnvironmentByCode(loginUser, 1L); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); loginUser = getAdminUser(); Mockito.when(taskDefinitionMapper.selectCount(Mockito.any(LambdaQueryWrapper.class))).thenReturn(1L); result = environmentService.deleteEnvironmentByCode(loginUser, 1L); logger.info(result.toString()); - Assert.assertEquals(Status.DELETE_ENVIRONMENT_RELATED_TASK_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.DELETE_ENVIRONMENT_RELATED_TASK_EXISTS, result.get(Constants.STATUS)); Mockito.when(taskDefinitionMapper.selectCount(Mockito.any(LambdaQueryWrapper.class))).thenReturn(0L); Mockito.when(environmentMapper.deleteByCode(1L)).thenReturn(1); result = environmentService.deleteEnvironmentByCode(loginUser, 1L); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test public void testVerifyEnvironment() { Map result = environmentService.verifyEnvironment(""); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_NAME_IS_NULL, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_NAME_IS_NULL, result.get(Constants.STATUS)); Mockito.when(environmentMapper.queryByEnvironmentName(environmentName)).thenReturn(getEnvironment()); result = environmentService.verifyEnvironment(environmentName); logger.info(result.toString()); - Assert.assertEquals(Status.ENVIRONMENT_NAME_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.ENVIRONMENT_NAME_EXISTS, result.get(Constants.STATUS)); } private Environment getEnvironment() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentWorkerGroupRelationServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentWorkerGroupRelationServiceTest.java index 5a3026fd1f..56fcd295bd 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentWorkerGroupRelationServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentWorkerGroupRelationServiceTest.java @@ -26,20 +26,20 @@ import org.apache.dolphinscheduler.dao.mapper.EnvironmentWorkerGroupRelationMapp import java.util.Map; import org.assertj.core.util.Lists; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * environment service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class EnvironmentWorkerGroupRelationServiceTest { public static final Logger logger = LoggerFactory.getLogger(EnvironmentWorkerGroupRelationServiceTest.class); @@ -52,18 +52,20 @@ public class EnvironmentWorkerGroupRelationServiceTest { @Test public void testQueryEnvironmentWorkerGroupRelation() { - Mockito.when(relationMapper.queryByEnvironmentCode(1L)).thenReturn(Lists.newArrayList(new EnvironmentWorkerGroupRelation())); + Mockito.when(relationMapper.queryByEnvironmentCode(1L)) + .thenReturn(Lists.newArrayList(new EnvironmentWorkerGroupRelation())); Map result = relationService.queryEnvironmentWorkerGroupRelation(1L); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test public void testQueryAllEnvironmentWorkerGroupRelationList() { - Mockito.when(relationMapper.selectList(Mockito.any())).thenReturn(Lists.newArrayList(new EnvironmentWorkerGroupRelation())); + Mockito.when(relationMapper.selectList(Mockito.any())) + .thenReturn(Lists.newArrayList(new EnvironmentWorkerGroupRelation())); Map result = relationService.queryAllEnvironmentWorkerGroupRelationList(); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ExecutorServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ExecutorServiceTest.java index 8a8fd243a1..58889636c0 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ExecutorServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ExecutorServiceTest.java @@ -69,21 +69,24 @@ import java.util.Map; import java.util.Optional; import org.assertj.core.util.Lists; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * executor service 2 test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ExecutorServiceTest { private static final Logger logger = LoggerFactory.getLogger(ExecutorServiceTest.class); @@ -151,7 +154,7 @@ public class ExecutorServiceTest { private String cronTime; - @Before + @BeforeEach public void init() { // user loginUser.setId(userId); @@ -194,7 +197,8 @@ public class ExecutorServiceTest { doReturn(1).when(processService).createCommand(argThat(c -> c.getId() == null)); doReturn(0).when(processService).createCommand(argThat(c -> c.getId() != null)); Mockito.when(monitorService.getServerListFromRegistry(true)).thenReturn(getMasterServersList()); - Mockito.when(processService.findProcessInstanceDetailById(processInstanceId)).thenReturn(Optional.ofNullable(processInstance)); + Mockito.when(processService.findProcessInstanceDetailById(processInstanceId)) + .thenReturn(Optional.ofNullable(processInstance)); Mockito.when(processService.findProcessDefinition(1L, 1)).thenReturn(processDefinition); Mockito.when(taskGroupQueueMapper.selectById(1)).thenReturn(taskGroupQueue); Mockito.when(processInstanceMapper.selectById(1)).thenReturn(processInstance); @@ -204,7 +208,7 @@ public class ExecutorServiceTest { public void testForceStartTaskInstance() { Map result = executorService.forceStartTaskInstance(loginUser, taskQueueId); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } /** @@ -222,9 +226,10 @@ public class ExecutorServiceTest { null, null, null, null, null, RunMode.RUN_MODE_SERIAL, - Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 10, null, 0, Constants.DRY_RUN_FLAG_NO, Constants.TEST_FLAG_NO, + Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 10, null, 0, Constants.DRY_RUN_FLAG_NO, + Constants.TEST_FLAG_NO, ComplementDependentMode.OFF_MODE); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); verify(processService, times(1)).createCommand(any(Command.class)); } @@ -244,9 +249,10 @@ public class ExecutorServiceTest { null, "n1,n2", null, null, null, RunMode.RUN_MODE_SERIAL, - Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, Constants.TEST_FLAG_NO, + Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, + Constants.TEST_FLAG_NO, ComplementDependentMode.OFF_MODE); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); verify(processService, times(1)).createCommand(any(Command.class)); } @@ -292,7 +298,7 @@ public class ExecutorServiceTest { command.setExecutorId(1); int count = executorService.createComplementDependentCommand(schedules, command); - Assert.assertEquals(1, count); + Assertions.assertEquals(1, count); } /** @@ -310,9 +316,10 @@ public class ExecutorServiceTest { null, null, null, null, null, RunMode.RUN_MODE_SERIAL, - Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, Constants.TEST_FLAG_NO, + Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, + Constants.TEST_FLAG_NO, ComplementDependentMode.OFF_MODE); - Assert.assertEquals(Status.START_PROCESS_INSTANCE_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.START_PROCESS_INSTANCE_ERROR, result.get(Constants.STATUS)); verify(processService, times(0)).createCommand(any(Command.class)); } @@ -331,9 +338,10 @@ public class ExecutorServiceTest { null, null, null, null, null, RunMode.RUN_MODE_SERIAL, - Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, Constants.TEST_FLAG_NO, + Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, + Constants.TEST_FLAG_NO, ComplementDependentMode.OFF_MODE); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); verify(processService, times(1)).createCommand(any(Command.class)); } @@ -352,9 +360,10 @@ public class ExecutorServiceTest { null, null, null, null, null, RunMode.RUN_MODE_PARALLEL, - Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, Constants.TEST_FLAG_NO, + Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, + Constants.TEST_FLAG_NO, ComplementDependentMode.OFF_MODE); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); verify(processService, times(31)).createCommand(any(Command.class)); } @@ -374,9 +383,10 @@ public class ExecutorServiceTest { null, null, null, null, null, RunMode.RUN_MODE_PARALLEL, - Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 15, Constants.DRY_RUN_FLAG_NO, Constants.TEST_FLAG_NO, + Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 15, Constants.DRY_RUN_FLAG_NO, + Constants.TEST_FLAG_NO, ComplementDependentMode.OFF_MODE); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); verify(processService, times(15)).createCommand(any(Command.class)); } @@ -392,9 +402,10 @@ public class ExecutorServiceTest { null, null, null, null, null, RunMode.RUN_MODE_PARALLEL, - Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, Constants.TEST_FLAG_NO, + Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 0, Constants.DRY_RUN_FLAG_NO, + Constants.TEST_FLAG_NO, ComplementDependentMode.OFF_MODE); - Assert.assertEquals(result.get(Constants.STATUS), Status.MASTER_NOT_EXISTS); + Assertions.assertEquals(result.get(Constants.STATUS), Status.MASTER_NOT_EXISTS); } @@ -405,11 +416,11 @@ public class ExecutorServiceTest { .thenReturn(checkProjectAndAuth()); Map result = executorService.execute(loginUser, projectCode, processInstanceId, ExecuteType.REPEAT_RUNNING); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test - public void testOfTestRun(){ + public void testOfTestRun() { Mockito.when(processService.verifyIsNeedCreateCommand(any(Command.class))).thenReturn(true); Mockito.when(projectService.checkProjectAndAuth(loginUser, project, projectCode, RERUN)) .thenReturn(checkProjectAndAuth()); @@ -420,13 +431,12 @@ public class ExecutorServiceTest { null, null, null, null, 0, RunMode.RUN_MODE_PARALLEL, - Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 15, Constants.DRY_RUN_FLAG_NO, Constants.TEST_FLAG_YES, + Priority.LOW, Constants.DEFAULT_WORKER_GROUP, 100L, 110, null, 15, Constants.DRY_RUN_FLAG_NO, + Constants.TEST_FLAG_YES, ComplementDependentMode.OFF_MODE); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } - - @Test public void testStartCheckByProcessDefinedCode() { List ids = new ArrayList<>(); @@ -442,7 +452,7 @@ public class ExecutorServiceTest { .thenReturn(processDefinitionList); Map result = executorService.startCheckByProcessDefinedCode(1L); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } private List getMasterServersList() { @@ -515,9 +525,9 @@ public class ExecutorServiceTest { result.add(listDate.get(startDateIndex) + "," + listDate.get(endDateIndex)); } - Assert.assertEquals("0,1", result.get(0)); - Assert.assertEquals("2,3", result.get(1)); - Assert.assertEquals("4,4", result.get(2)); + Assertions.assertEquals("0,1", result.get(0)); + Assertions.assertEquals("2,3", result.get(1)); + Assertions.assertEquals("4,4", result.get(2)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/K8SNamespaceServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/K8SNamespaceServiceTest.java index 390153aa3d..57233c3768 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/K8SNamespaceServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/K8SNamespaceServiceTest.java @@ -38,22 +38,25 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -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.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.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class K8SNamespaceServiceTest { private static final Logger logger = LoggerFactory.getLogger(K8SNamespaceServiceTest.class); @@ -76,7 +79,7 @@ public class K8SNamespaceServiceTest { private String namespace = "default"; private Long clusterCode = 100L; - @Before + @BeforeEach public void setUp() throws Exception { Mockito.when( k8sClientService.upsertNamespaceAndResourceToK8s(Mockito.any(K8sNamespace.class), Mockito.anyString())) @@ -84,7 +87,7 @@ public class K8SNamespaceServiceTest { Mockito.when(k8sClientService.deleteNamespaceToK8s(Mockito.anyString(), Mockito.anyLong())).thenReturn(null); } - @After + @AfterEach public void tearDown() throws Exception { } @@ -98,7 +101,7 @@ public class K8SNamespaceServiceTest { Result result = k8sNamespaceService.queryListPaging(getLoginUser(), namespace, 1, 10); logger.info(result.toString()); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @Test @@ -107,20 +110,20 @@ public class K8SNamespaceServiceTest { Map result = k8sNamespaceService.createK8sNamespace(getLoginUser(), null, clusterCode, 10.0, 100); logger.info(result.toString()); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); // k8s is null result = k8sNamespaceService.createK8sNamespace(getLoginUser(), namespace, null, 10.0, 100); logger.info(result.toString()); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); // correct Mockito.when(clusterMapper.queryByClusterCode(Mockito.anyLong())).thenReturn(getCluster()); result = k8sNamespaceService.createK8sNamespace(getLoginUser(), namespace, clusterCode, 10.0, 100); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); // null limit cpu and mem result = k8sNamespaceService.createK8sNamespace(getLoginUser(), namespace, clusterCode, null, null); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -129,15 +132,15 @@ public class K8SNamespaceServiceTest { Map result = k8sNamespaceService.updateK8sNamespace(getLoginUser(), 1, null, null, null); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); result = k8sNamespaceService.updateK8sNamespace(getLoginUser(), 1, null, -1.0, 100); logger.info(result.toString()); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); result = k8sNamespaceService.updateK8sNamespace(getLoginUser(), 1, null, 1.0, 100); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -148,22 +151,22 @@ public class K8SNamespaceServiceTest { // namespace null Result result = k8sNamespaceService.verifyNamespaceK8s(null, clusterCode); logger.info(result.toString()); - Assert.assertEquals(result.getCode().intValue(), Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode()); + Assertions.assertEquals(result.getCode().intValue(), Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode()); // k8s null result = k8sNamespaceService.verifyNamespaceK8s(namespace, null); logger.info(result.toString()); - Assert.assertEquals(result.getCode().intValue(), Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode()); + Assertions.assertEquals(result.getCode().intValue(), Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode()); // exist result = k8sNamespaceService.verifyNamespaceK8s(namespace, clusterCode); logger.info(result.toString()); - Assert.assertEquals(result.getCode().intValue(), Status.K8S_NAMESPACE_EXIST.getCode()); + Assertions.assertEquals(result.getCode().intValue(), Status.K8S_NAMESPACE_EXIST.getCode()); // not exist result = k8sNamespaceService.verifyNamespaceK8s(namespace, 9999L); logger.info(result.toString()); - Assert.assertEquals(result.getCode().intValue(), Status.SUCCESS.getCode()); + Assertions.assertEquals(result.getCode().intValue(), Status.SUCCESS.getCode()); } @Test @@ -173,7 +176,7 @@ public class K8SNamespaceServiceTest { Map result = k8sNamespaceService.deleteNamespaceById(getLoginUser(), 1); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -187,15 +190,15 @@ public class K8SNamespaceServiceTest { Map result = k8sNamespaceService.queryAuthorizedNamespace(loginUser, 2); logger.info(result.toString()); List namespaces = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(namespaces)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(namespaces)); // test non-admin user loginUser.setUserType(UserType.GENERAL_USER); loginUser.setId(3); result = k8sNamespaceService.queryAuthorizedNamespace(loginUser, 2); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); namespaces = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isEmpty(namespaces)); + Assertions.assertTrue(CollectionUtils.isEmpty(namespaces)); } @Test @@ -209,16 +212,16 @@ public class K8SNamespaceServiceTest { Map result = k8sNamespaceService.queryUnauthorizedNamespace(loginUser, 2); logger.info(result.toString()); List namespaces = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(namespaces)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(namespaces)); // test non-admin user loginUser.setId(2); loginUser.setUserType(UserType.GENERAL_USER); result = k8sNamespaceService.queryUnauthorizedNamespace(loginUser, 3); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); namespaces = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isEmpty(namespaces)); + Assertions.assertTrue(CollectionUtils.isEmpty(namespaces)); } @Test @@ -237,7 +240,7 @@ public class K8SNamespaceServiceTest { Mockito.when(k8sNamespaceMapper.selectList(Mockito.any())).thenReturn(k8sNamespaces); Mockito.when(clusterMapper.queryAllClusterList()).thenReturn(clusters); List result = k8sNamespaceService.queryNamespaceAvailable(getLoginUser()); - Assert.assertEquals(result.get(0).getClusterName(), cluster.getName()); + Assertions.assertEquals(result.get(0).getClusterName(), cluster.getName()); } private User getLoginUser() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java index 6fc0dd5ebb..5430fd2ec5 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java @@ -38,20 +38,23 @@ import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; -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.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; /** * logger service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class LoggerServiceTest { private static final Logger logger = LoggerFactory.getLogger(LoggerServiceTest.class); @@ -81,23 +84,23 @@ public class LoggerServiceTest { Mockito.when(processService.findTaskInstanceById(1)).thenReturn(taskInstance); Result result = loggerService.queryLog(2, 1, 1); // TASK_INSTANCE_NOT_FOUND - Assert.assertEquals(Status.TASK_INSTANCE_NOT_FOUND.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.TASK_INSTANCE_NOT_FOUND.getCode(), result.getCode().intValue()); try { // HOST NOT FOUND OR ILLEGAL result = loggerService.queryLog(1, 1, 1); } catch (RuntimeException e) { - Assert.assertTrue(true); + Assertions.assertTrue(true); logger.error("testQueryDataSourceList error {}", e.getMessage()); } - Assert.assertEquals(Status.TASK_INSTANCE_HOST_IS_NULL.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.TASK_INSTANCE_HOST_IS_NULL.getCode(), result.getCode().intValue()); // SUCCESS taskInstance.setHost("127.0.0.1:8080"); taskInstance.setLogPath("/temp/log"); Mockito.when(processService.findTaskInstanceById(1)).thenReturn(taskInstance); result = loggerService.queryLog(1, 1, 1); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -110,7 +113,7 @@ public class LoggerServiceTest { try { loggerService.getLogBytes(2); } catch (RuntimeException e) { - Assert.assertTrue(true); + Assertions.assertTrue(true); logger.error("testGetLogBytes error: {}", "task instance is null"); } @@ -118,7 +121,7 @@ public class LoggerServiceTest { try { loggerService.getLogBytes(1); } catch (RuntimeException e) { - Assert.assertTrue(true); + Assertions.assertTrue(true); logger.error("testGetLogBytes error: {}", "task instance host is null"); } @@ -158,7 +161,7 @@ public class LoggerServiceTest { Mockito.when(processService.findTaskInstanceById(1)).thenReturn(taskInstance); Mockito.when(taskDefinitionMapper.queryByCode(taskInstance.getTaskCode())).thenReturn(taskDefinition); result = loggerService.queryLog(loginUser, projectCode, 1, 1, 1); - Assert.assertEquals(Status.SUCCESS.getCode(), ((Status) result.get(Constants.STATUS)).getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), ((Status) result.get(Constants.STATUS)).getCode()); } @Test diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/MonitorServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/MonitorServiceTest.java index 6854f91071..3838cd5962 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/MonitorServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/MonitorServiceTest.java @@ -19,6 +19,7 @@ package org.apache.dolphinscheduler.api.service; import org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant; import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.permission.ResourcePermissionCheckService; import org.apache.dolphinscheduler.api.service.impl.BaseServiceImpl; import org.apache.dolphinscheduler.api.service.impl.MonitorServiceImpl; import org.apache.dolphinscheduler.common.Constants; @@ -29,7 +30,6 @@ import org.apache.dolphinscheduler.common.model.Server; import org.apache.dolphinscheduler.dao.MonitorDBDao; import org.apache.dolphinscheduler.dao.entity.MonitorRecord; import org.apache.dolphinscheduler.dao.entity.User; -import org.apache.dolphinscheduler.api.permission.ResourcePermissionCheckService; import org.apache.dolphinscheduler.service.registry.RegistryClient; import org.apache.dolphinscheduler.spi.enums.DbType; @@ -40,21 +40,24 @@ import java.util.Date; import java.util.List; import java.util.Map; -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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * monitor service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class MonitorServiceTest { private static final Logger logger = LoggerFactory.getLogger(MonitorServiceTest.class); @@ -75,62 +78,64 @@ public class MonitorServiceTest { public static final Logger serviceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); - @Before - public void init () { + @BeforeEach + public void init() { user = new User(); user.setUserType(UserType.ADMIN_USER); user.setId(1); } @Test - public void testQueryDatabaseState() { + public void testQueryDatabaseState() { mockPermissionCheck(ApiFuncIdentificationConstant.MONITOR_DATABASES_VIEW, true); Mockito.when(monitorDBDao.queryDatabaseState()).thenReturn(getList()); - Map result = monitorService.queryDatabaseState(user); + Map result = monitorService.queryDatabaseState(user); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List monitorRecordList = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(monitorRecordList)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(monitorRecordList)); mockPermissionCheck(ApiFuncIdentificationConstant.MONITOR_DATABASES_VIEW, false); - Map noPermission = monitorService.queryDatabaseState(user); - Assert.assertEquals(Status.SUCCESS,noPermission.get(Constants.STATUS)); + Map noPermission = monitorService.queryDatabaseState(user); + Assertions.assertEquals(Status.SUCCESS, noPermission.get(Constants.STATUS)); } @Test - public void testQueryMaster() { + public void testQueryMaster() { mockPermissionCheck(ApiFuncIdentificationConstant.MONITOR_MASTER_VIEW, true); Mockito.when(registryClient.getServerList(NodeType.MASTER)).thenReturn(getServerList()); Map result = monitorService.queryMaster(user); - Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); mockPermissionCheck(ApiFuncIdentificationConstant.MONITOR_MASTER_VIEW, false); - Map noPermission = monitorService.queryMaster(user); - Assert.assertEquals(Status.SUCCESS,noPermission.get(Constants.STATUS)); + Map noPermission = monitorService.queryMaster(user); + Assertions.assertEquals(Status.SUCCESS, noPermission.get(Constants.STATUS)); } @Test - public void testQueryWorker() { + public void testQueryWorker() { mockPermissionCheck(ApiFuncIdentificationConstant.MONITOR_WORKER_VIEW, true); Mockito.when(registryClient.getServerList(NodeType.WORKER)).thenReturn(getServerList()); Map result = monitorService.queryWorker(user); - Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); mockPermissionCheck(ApiFuncIdentificationConstant.MONITOR_WORKER_VIEW, false); - Map noPermission = monitorService.queryWorker(user); - Assert.assertEquals(Status.SUCCESS,noPermission.get(Constants.STATUS)); + Map noPermission = monitorService.queryWorker(user); + Assertions.assertEquals(Status.SUCCESS, noPermission.get(Constants.STATUS)); } @Test - public void testGetServerListFromZK() { - //TODO need zk - /*List serverList = monitorService.getServerListFromZK(true);*/ - /*logger.info(serverList.toString());*/ + public void testGetServerListFromZK() { + // TODO need zk + /* List serverList = monitorService.getServerListFromZK(true); */ + /* logger.info(serverList.toString()); */ } - private void mockPermissionCheck(String permissionKey, boolean result){ - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.MONITOR, null, 1, permissionKey, serviceLogger)).thenReturn(result); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.MONITOR, null, 0, serviceLogger)).thenReturn(true); + private void mockPermissionCheck(String permissionKey, boolean result) { + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.MONITOR, null, 1, + permissionKey, serviceLogger)).thenReturn(result); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.MONITOR, null, 0, + serviceLogger)).thenReturn(true); } private List getList() { @@ -140,7 +145,7 @@ public class MonitorServiceTest { } private MonitorRecord getEntity() { - MonitorRecord monitorRecord = new MonitorRecord(); + MonitorRecord monitorRecord = new MonitorRecord(); monitorRecord.setDbType(DbType.MYSQL); return monitorRecord; } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessDefinitionServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessDefinitionServiceTest.java index c96e067e58..007f2efe0c 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessDefinitionServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessDefinitionServiceTest.java @@ -89,21 +89,20 @@ import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletResponse; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -import org.junit.runner.RunWith; +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 org.springframework.mock.web.MockMultipartFile; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ProcessDefinitionServiceTest extends BaseServiceTestTool { private static final String taskRelationJson = @@ -175,7 +174,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { protected final static String executionType = "PARALLEL"; protected final static String tenantCode = "tenant"; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -198,7 +197,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(projectService.checkProjectAndAuth(user, project, projectCode, WORKFLOW_DEFINITION)) .thenReturn(result); Map map = processDefinitionService.queryProcessDefinitionList(user, projectCode); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); // project check auth success putMsg(result, Status.SUCCESS, projectCode); @@ -209,7 +208,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processDefinitionMapper.queryAllDefinitionList(project.getCode())).thenReturn(resourceList); Map checkSuccessRes = processDefinitionService.queryProcessDefinitionList(user, projectCode); - Assert.assertEquals(Status.SUCCESS, checkSuccessRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, checkSuccessRes.get(Constants.STATUS)); } @Test @@ -225,7 +224,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { .checkProjectAndAuthThrowException(user, null, WORKFLOW_DEFINITION); processDefinitionService.queryProcessDefinitionListPaging(user, projectCode, "", "", 1, 5, 0); } catch (ServiceException serviceException) { - Assert.assertEquals(Status.PROJECT_NOT_EXIST.getCode(), serviceException.getCode()); + Assertions.assertEquals(Status.PROJECT_NOT_EXIST.getCode(), serviceException.getCode()); } Map result = new HashMap<>(); @@ -250,7 +249,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { PageInfo pageInfo = processDefinitionService.queryProcessDefinitionListPaging( user, project.getCode(), "", "", 1, 0, 10); - Assert.assertNotNull(pageInfo); + Assertions.assertNotNull(pageInfo); } @Test @@ -269,7 +268,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(projectService.checkProjectAndAuth(user, project, projectCode, WORKFLOW_DEFINITION)) .thenReturn(result); Map map = processDefinitionService.queryProcessDefinitionByCode(user, 1L, 1L); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); // project check auth success, instance not exist putMsg(result, Status.SUCCESS, projectCode); @@ -280,7 +279,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Map instanceNotexitRes = processDefinitionService.queryProcessDefinitionByCode(user, projectCode, 1L); - Assert.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, instanceNotexitRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, instanceNotexitRes.get(Constants.STATUS)); // instance exit Mockito.when(processDefinitionMapper.queryByCode(46L)).thenReturn(getProcessDefinition()); @@ -290,7 +289,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(tenantMapper.queryById(1)).thenReturn(tenant); Map successRes = processDefinitionService.queryProcessDefinitionByCode(user, projectCode, 46L); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -307,7 +306,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { .thenReturn(result); Map map = processDefinitionService.queryProcessDefinitionByName(user, projectCode, "test_def"); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); // project check auth success, instance not exist putMsg(result, Status.SUCCESS, projectCode); @@ -317,7 +316,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Map instanceNotExitRes = processDefinitionService.queryProcessDefinitionByName(user, projectCode, "test_def"); - Assert.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, instanceNotExitRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, instanceNotExitRes.get(Constants.STATUS)); // instance exit Mockito.when(processDefinitionMapper.queryByDefineName(project.getCode(), "test")) @@ -327,7 +326,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { .thenReturn(result); Map successRes = processDefinitionService.queryProcessDefinitionByName(user, projectCode, "test"); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -343,7 +342,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { // copy project definition ids empty test Map map = processDefinitionService.batchCopyProcessDefinition(user, projectCode, StringUtils.EMPTY, 2L); - Assert.assertEquals(Status.PROCESS_DEFINITION_CODES_IS_EMPTY, map.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINITION_CODES_IS_EMPTY, map.get(Constants.STATUS)); // project check auth fail putMsg(result, Status.PROJECT_NOT_FOUND, projectCode); @@ -351,7 +350,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { .thenReturn(result); Map map1 = processDefinitionService.batchCopyProcessDefinition( user, projectCode, String.valueOf(project.getId()), 2L); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, map1.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, map1.get(Constants.STATUS)); // project check auth success, target project name not equal project name, check auth target project fail Project project1 = getProject(projectCodeOther); @@ -377,7 +376,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processService.saveProcessDefine(user, definition, Boolean.TRUE, Boolean.TRUE)).thenReturn(2); Map map3 = processDefinitionService.batchCopyProcessDefinition( user, projectCodeOther, String.valueOf(processDefinitionCode), projectCode); - Assert.assertEquals(Status.SUCCESS, map3.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, map3.get(Constants.STATUS)); } @Test @@ -418,7 +417,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Map successRes = processDefinitionService.batchMoveProcessDefinition( user, projectCode, String.valueOf(processDefinitionCode), projectCodeOther); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -522,7 +521,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Throwable exception = Assertions.assertThrows(ServiceException.class, () -> processDefinitionService.batchDeleteProcessDefinitionByCodes(user, projectCode, twoCodes)); String formatter = MessageFormat.format(Status.BATCH_DELETE_PROCESS_DEFINE_BY_CODES_ERROR.getMsg(), - "12[process definition not exist]"); + "12[process definition not exist]"); Assertions.assertEquals(formatter, exception.getMessage()); // return the right data @@ -556,7 +555,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { putMsg(result, Status.SUCCESS, projectCode); Map deleteSuccess = processDefinitionService.batchDeleteProcessDefinitionByCodes(user, projectCode, singleCodes); - Assert.assertEquals(Status.SUCCESS, deleteSuccess.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, deleteSuccess.get(Constants.STATUS)); } @Test @@ -572,7 +571,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { .thenReturn(result); Map map = processDefinitionService.releaseProcessDefinition(user, projectCode, processDefinitionCode, ReleaseState.OFFLINE); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); // project check auth success, processes definition online putMsg(result, Status.SUCCESS, projectCode); @@ -586,17 +585,17 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processService.findRelationByCode(46L, 1)).thenReturn(processTaskRelationList); Map onlineRes = processDefinitionService.releaseProcessDefinition(user, projectCode, 46, ReleaseState.ONLINE); - Assert.assertEquals(Status.SUCCESS, onlineRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, onlineRes.get(Constants.STATUS)); // project check auth success, processes definition online Map onlineWithResourceRes = processDefinitionService.releaseProcessDefinition(user, projectCode, 46, ReleaseState.ONLINE); - Assert.assertEquals(Status.SUCCESS, onlineWithResourceRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, onlineWithResourceRes.get(Constants.STATUS)); // release error code Map failRes = processDefinitionService.releaseProcessDefinition(user, projectCode, 46, ReleaseState.getEnum(2)); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, failRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, failRes.get(Constants.STATUS)); } @Test @@ -611,33 +610,33 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { .thenReturn(result); Map map = processDefinitionService.verifyProcessDefinitionName(user, projectCode, "test_pdf", 0); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, map.get(Constants.STATUS)); // project check auth success, process not exist putMsg(result, Status.SUCCESS, projectCode); Mockito.when(processDefinitionMapper.verifyByDefineName(project.getCode(), "test_pdf")).thenReturn(null); Map processNotExistRes = processDefinitionService.verifyProcessDefinitionName(user, projectCode, "test_pdf", 0); - Assert.assertEquals(Status.SUCCESS, processNotExistRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, processNotExistRes.get(Constants.STATUS)); // process exist Mockito.when(processDefinitionMapper.verifyByDefineName(project.getCode(), "test_pdf")) .thenReturn(getProcessDefinition()); Map processExistRes = processDefinitionService.verifyProcessDefinitionName(user, projectCode, "test_pdf", 0); - Assert.assertEquals(Status.PROCESS_DEFINITION_NAME_EXIST, processExistRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINITION_NAME_EXIST, processExistRes.get(Constants.STATUS)); } @Test public void testCheckProcessNodeList() { Map dataNotValidRes = processDefinitionService.checkProcessNodeList(null, null); - Assert.assertEquals(Status.DATA_IS_NOT_VALID, dataNotValidRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.DATA_IS_NOT_VALID, dataNotValidRes.get(Constants.STATUS)); List taskDefinitionLogs = JSONUtils.toList(taskDefinitionJson, TaskDefinitionLog.class); Map taskEmptyRes = processDefinitionService.checkProcessNodeList(taskRelationJson, taskDefinitionLogs); - Assert.assertEquals(Status.PROCESS_DAG_IS_EMPTY, taskEmptyRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DAG_IS_EMPTY, taskEmptyRes.get(Constants.STATUS)); } @Test @@ -653,7 +652,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processDefinitionMapper.queryByCode(46L)).thenReturn(null); Map processDefinitionNullRes = processDefinitionService.getTaskNodeListByDefinitionCode(user, projectCode, 46L); - Assert.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, processDefinitionNullRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, processDefinitionNullRes.get(Constants.STATUS)); // success ProcessDefinition processDefinition = getProcessDefinition(); @@ -662,7 +661,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processDefinitionMapper.queryByCode(46L)).thenReturn(processDefinition); Map dataNotValidRes = processDefinitionService.getTaskNodeListByDefinitionCode(user, projectCode, 46L); - Assert.assertEquals(Status.SUCCESS, dataNotValidRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, dataNotValidRes.get(Constants.STATUS)); } @Test @@ -681,7 +680,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processDefinitionMapper.queryByCodes(defineCodeSet)).thenReturn(null); Map processNotExistRes = processDefinitionService.getNodeListMapByDefinitionCodes(user, projectCode, defineCodes); - Assert.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, processNotExistRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, processNotExistRes.get(Constants.STATUS)); putMsg(result, Status.SUCCESS, projectCode); ProcessDefinition processDefinition = getProcessDefinition(); @@ -697,7 +696,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Map successRes = processDefinitionService.getNodeListMapByDefinitionCodes(user, projectCode, defineCodes); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -714,7 +713,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processDefinitionMapper.queryAllDefinitionList(projectCode)).thenReturn(processDefinitionList); Map successRes = processDefinitionService.queryAllProcessDefinitionByProjectCode(user, projectCode); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -729,7 +728,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { ProcessDefinition processDefinition = getProcessDefinition(); Map processDefinitionNullRes = processDefinitionService.viewTree(user, processDefinition.getProjectCode(), 46, 10); - Assert.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, processDefinitionNullRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, processDefinitionNullRes.get(Constants.STATUS)); // task instance not existproject putMsg(result, Status.SUCCESS, projectCode); @@ -739,12 +738,12 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processService.genDagGraph(processDefinition)).thenReturn(new DAG<>()); Map taskNullRes = processDefinitionService.viewTree(user, processDefinition.getProjectCode(), 46, 10); - Assert.assertEquals(Status.SUCCESS, taskNullRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, taskNullRes.get(Constants.STATUS)); // task instance exist Map taskNotNuLLRes = processDefinitionService.viewTree(user, processDefinition.getProjectCode(), 46, 10); - Assert.assertEquals(Status.SUCCESS, taskNotNuLLRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, taskNotNuLLRes.get(Constants.STATUS)); } @Test @@ -761,7 +760,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { Mockito.when(processService.genDagGraph(processDefinition)).thenReturn(new DAG<>()); Map taskNotNuLLRes = processDefinitionService.viewTree(user, processDefinition.getProjectCode(), 46, 10); - Assert.assertEquals(Status.SUCCESS, taskNotNuLLRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, taskNotNuLLRes.get(Constants.STATUS)); } @Test @@ -777,9 +776,9 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { try { processDefinitionService.updateProcessDefinition(user, projectCode, "test", 1, "", "", "", 0, "root", null, "", null, ProcessExecutionTypeEnum.PARALLEL); - Assert.fail(); + Assertions.fail(); } catch (ServiceException ex) { - Assert.assertEquals(Status.DATA_IS_NOT_VALID.getCode(), ex.getCode()); + Assertions.assertEquals(Status.DATA_IS_NOT_VALID.getCode(), ex.getCode()); } } @@ -801,7 +800,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { DagData dagData = new DagData(getProcessDefinition(), null, null); Mockito.when(processService.genDagData(Mockito.any())).thenReturn(dagData); processDefinitionService.batchExportProcessDefinitionByCodes(user, projectCode, "1", response); - Assert.assertNotNull(processDefinitionService.exportProcessDagData(processDefinition)); + Assertions.assertNotNull(processDefinitionService.exportProcessDagData(processDefinition)); } @Test @@ -845,20 +844,20 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool { .thenReturn(0); result = processDefinitionService.importSqlProcessDefinition(user, projectCode, mockMultipartFile); - Assert.assertEquals(result.get(Constants.STATUS), Status.SUCCESS); + Assertions.assertEquals(result.get(Constants.STATUS), Status.SUCCESS); } @Test public void testGetNewProcessName() { String processName1 = "test_copy_" + DateUtils.getCurrentTimeStamp(); final String newName1 = processDefinitionService.getNewName(processName1, Constants.COPY_SUFFIX); - Assert.assertEquals(2, newName1.split(Constants.COPY_SUFFIX).length); + Assertions.assertEquals(2, newName1.split(Constants.COPY_SUFFIX).length); String processName2 = "wf_copy_all_ods_data_to_d"; final String newName2 = processDefinitionService.getNewName(processName2, Constants.COPY_SUFFIX); - Assert.assertEquals(3, newName2.split(Constants.COPY_SUFFIX).length); + Assertions.assertEquals(3, newName2.split(Constants.COPY_SUFFIX).length); String processName3 = "test_import_" + DateUtils.getCurrentTimeStamp(); final String newName3 = processDefinitionService.getNewName(processName3, Constants.IMPORT_SUFFIX); - Assert.assertEquals(2, newName3.split(Constants.IMPORT_SUFFIX).length); + Assertions.assertEquals(2, newName3.split(Constants.IMPORT_SUFFIX).length); } @Test diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessInstanceServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessInstanceServiceTest.java index e648977f61..08b06b720f 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessInstanceServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessInstanceServiceTest.java @@ -73,20 +73,23 @@ import java.util.List; import java.util.Map; import java.util.Optional; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * process instance service test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ProcessInstanceServiceTest { @InjectMocks @@ -180,7 +183,7 @@ public class ProcessInstanceServiceTest { processInstanceService.queryProcessInstanceList(loginUser, projectCode, 46, "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", "test_user", WorkflowExecutionStatus.SUBMITTED_SUCCESS, "192.168.xx.xx", "", 1, 10); - Assert.assertEquals(Status.PROJECT_NOT_FOUND.getCode(), (int) proejctAuthFailRes.getCode()); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND.getCode(), (int) proejctAuthFailRes.getCode()); Date start = DateUtils.stringToDate("2020-01-01 00:00:00"); Date end = DateUtils.stringToDate("2020-01-02 00:00:00"); @@ -203,7 +206,7 @@ public class ProcessInstanceServiceTest { processInstanceService.queryProcessInstanceList(loginUser, projectCode, 1, "20200101 00:00:00", "20200102 00:00:00", "", loginUser.getUserName(), WorkflowExecutionStatus.SUBMITTED_SUCCESS, "192.168.xx.xx", "", 1, 10); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), (int) dataParameterRes.getCode()); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), (int) dataParameterRes.getCode()); // project auth success putMsg(result, Status.SUCCESS, projectCode); @@ -221,7 +224,7 @@ public class ProcessInstanceServiceTest { processInstanceService.queryProcessInstanceList(loginUser, projectCode, 1, "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", loginUser.getUserName(), WorkflowExecutionStatus.SUBMITTED_SUCCESS, "192.168.xx.xx", "", 1, 10); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) successRes.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) successRes.getCode()); // data parameter empty when(processInstanceMapper.queryProcessInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), @@ -230,7 +233,7 @@ public class ProcessInstanceServiceTest { successRes = processInstanceService.queryProcessInstanceList(loginUser, projectCode, 1, "", "", "", loginUser.getUserName(), WorkflowExecutionStatus.SUBMITTED_SUCCESS, "192.168.xx.xx", "", 1, 10); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) successRes.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) successRes.getCode()); // executor null when(usersService.queryUser(loginUser.getId())).thenReturn(null); @@ -240,7 +243,7 @@ public class ProcessInstanceServiceTest { "2020-01-02 00:00:00", "", "admin", WorkflowExecutionStatus.SUBMITTED_SUCCESS, "192.168.xx.xx", "", 1, 10); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) executorExistRes.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) executorExistRes.getCode()); // executor name empty when(processInstanceMapper.queryProcessInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), @@ -250,7 +253,7 @@ public class ProcessInstanceServiceTest { processInstanceService.queryProcessInstanceList(loginUser, projectCode, 1, "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", "", WorkflowExecutionStatus.SUBMITTED_SUCCESS, "192.168.xx.xx", "", 1, 10); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) executorEmptyRes.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) executorEmptyRes.getCode()); } @@ -272,7 +275,8 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); Map projectAuthFailRes = processInstanceService .queryTopNLongestRunningProcessInstance(loginUser, projectCode, size, startTime, endTime); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); + + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); // project auth success putMsg(result, Status.SUCCESS, projectCode); @@ -281,7 +285,7 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); projectAuthFailRes = processInstanceService .queryTopNLongestRunningProcessInstance(loginUser, projectCode, -1, startTime, endTime); - Assert.assertEquals(Status.NEGTIVE_SIZE_NUMBER_ERROR, projectAuthFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.NEGTIVE_SIZE_NUMBER_ERROR, projectAuthFailRes.get(Constants.STATUS)); putMsg(result, Status.SUCCESS, projectCode); when(projectMapper.queryByCode(projectCode)).thenReturn(project); @@ -292,7 +296,7 @@ public class ProcessInstanceServiceTest { Map successRes = processInstanceService.queryTopNLongestRunningProcessInstance(loginUser, projectCode, size, startTime, endTime); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -311,21 +315,21 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); Map startTimeBiggerFailRes = processInstanceService .queryTopNLongestRunningProcessInstance(loginUser, projectCode, size, endTime, startTime); - Assert.assertEquals(Status.START_TIME_BIGGER_THAN_END_TIME_ERROR, startTimeBiggerFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.START_TIME_BIGGER_THAN_END_TIME_ERROR, startTimeBiggerFailRes.get(Constants.STATUS)); putMsg(result, Status.SUCCESS, projectCode); when(projectMapper.queryByCode(projectCode)).thenReturn(project); when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); Map dataNullFailRes = processInstanceService .queryTopNLongestRunningProcessInstance(loginUser, projectCode, size, null, endTime); - Assert.assertEquals(Status.DATA_IS_NULL, dataNullFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.DATA_IS_NULL, dataNullFailRes.get(Constants.STATUS)); putMsg(result, Status.SUCCESS, projectCode); when(projectMapper.queryByCode(projectCode)).thenReturn(project); when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); dataNullFailRes = processInstanceService .queryTopNLongestRunningProcessInstance(loginUser, projectCode, size, startTime, null); - Assert.assertEquals(Status.DATA_IS_NULL, dataNullFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.DATA_IS_NULL, dataNullFailRes.get(Constants.STATUS)); } @Test @@ -341,7 +345,7 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); Map projectAuthFailRes = processInstanceService.queryProcessInstanceById(loginUser, projectCode, 1); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); // project auth success ProcessInstance processInstance = getProcessInstance(); @@ -355,21 +359,21 @@ public class ProcessInstanceServiceTest { when(processService.findProcessDefinition(processInstance.getProcessDefinitionCode(), processInstance.getProcessDefinitionVersion())).thenReturn(processDefinition); Map successRes = processInstanceService.queryProcessInstanceById(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); // worker group null Map workerNullRes = processInstanceService.queryProcessInstanceById(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUCCESS, workerNullRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, workerNullRes.get(Constants.STATUS)); // worker group exist WorkerGroup workerGroup = getWorkGroup(); Map workerExistRes = processInstanceService.queryProcessInstanceById(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUCCESS, workerExistRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, workerExistRes.get(Constants.STATUS)); when(processService.findProcessDefinition(processInstance.getProcessDefinitionCode(), processInstance.getProcessDefinitionVersion())).thenReturn(null);; workerExistRes = processInstanceService.queryProcessInstanceById(loginUser, projectCode, 1); - Assert.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, workerExistRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, workerExistRes.get(Constants.STATUS)); } @Test @@ -385,7 +389,7 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); Map projectAuthFailRes = processInstanceService.queryTaskListByProcessId(loginUser, projectCode, 1); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); // project auth success putMsg(result, Status.SUCCESS, projectCode); @@ -401,11 +405,13 @@ public class ProcessInstanceServiceTest { res.setData("xxx"); when(projectMapper.queryByCode(projectCode)).thenReturn(project); when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); - when(processService.findProcessInstanceDetailById(processInstance.getId())).thenReturn(Optional.of(processInstance)); - when(processService.findValidTaskListByProcessId(processInstance.getId(), processInstance.getTestFlag())).thenReturn(taskInstanceList); + when(processService.findProcessInstanceDetailById(processInstance.getId())) + .thenReturn(Optional.of(processInstance)); + when(processService.findValidTaskListByProcessId(processInstance.getId(), processInstance.getTestFlag())) + .thenReturn(taskInstanceList); when(loggerService.queryLog(taskInstance.getId(), 0, 4098)).thenReturn(res); Map successRes = processInstanceService.queryTaskListByProcessId(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -418,12 +424,11 @@ public class ProcessInstanceServiceTest { + "[root@node2 current]# "; Map resultMap = processInstanceService.parseLogForDependentResult(logString); - Assert.assertEquals(1, resultMap.size()); + Assertions.assertEquals(1, resultMap.size()); resultMap.clear(); resultMap = processInstanceService.parseLogForDependentResult(""); - Assert.assertEquals(0, resultMap.size()); - + Assertions.assertEquals(0, resultMap.size()); } @Test @@ -439,7 +444,7 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); Map projectAuthFailRes = processInstanceService.querySubProcessInstanceByTaskId(loginUser, projectCode, 1); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); // task null putMsg(result, Status.SUCCESS, projectCode); @@ -448,7 +453,7 @@ public class ProcessInstanceServiceTest { when(processService.findTaskInstanceById(1)).thenReturn(null); Map taskNullRes = processInstanceService.querySubProcessInstanceByTaskId(loginUser, projectCode, 1); - Assert.assertEquals(Status.TASK_INSTANCE_NOT_EXISTS, taskNullRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.TASK_INSTANCE_NOT_EXISTS, taskNullRes.get(Constants.STATUS)); // task not sub process TaskInstance taskInstance = getTaskInstance(); @@ -461,12 +466,12 @@ public class ProcessInstanceServiceTest { when(taskDefinitionMapper.queryByCode(taskInstance.getTaskCode())).thenReturn(taskDefinition); Map notSubprocessRes = processInstanceService.querySubProcessInstanceByTaskId(loginUser, projectCode, 1); - Assert.assertEquals(Status.TASK_INSTANCE_NOT_SUB_WORKFLOW_INSTANCE, notSubprocessRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.TASK_INSTANCE_NOT_SUB_WORKFLOW_INSTANCE, notSubprocessRes.get(Constants.STATUS)); putMsg(result, Status.SUCCESS, projectCode); taskDefinition.setProjectCode(0L); notSubprocessRes = processInstanceService.querySubProcessInstanceByTaskId(loginUser, projectCode, 1); - Assert.assertEquals(Status.TASK_INSTANCE_NOT_EXISTS, notSubprocessRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.TASK_INSTANCE_NOT_EXISTS, notSubprocessRes.get(Constants.STATUS)); taskDefinition.setProjectCode(projectCode); when(taskDefinitionMapper.queryByCode(taskInstance.getTaskCode())).thenReturn(taskDefinition); @@ -479,7 +484,7 @@ public class ProcessInstanceServiceTest { when(processService.findSubProcessInstance(subTask.getProcessInstanceId(), subTask.getId())).thenReturn(null); Map subprocessNotExistRes = processInstanceService.querySubProcessInstanceByTaskId(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUB_PROCESS_INSTANCE_NOT_EXIST, subprocessNotExistRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUB_PROCESS_INSTANCE_NOT_EXIST, subprocessNotExistRes.get(Constants.STATUS)); // sub process exist ProcessInstance processInstance = getProcessInstance(); @@ -488,7 +493,7 @@ public class ProcessInstanceServiceTest { .thenReturn(processInstance); Map subprocessExistRes = processInstanceService.querySubProcessInstanceByTaskId(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUCCESS, subprocessExistRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, subprocessExistRes.get(Constants.STATUS)); } @Test @@ -504,7 +509,7 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, INSTANCE_UPDATE)).thenReturn(result); Map projectAuthFailRes = processInstanceService.updateProcessInstance(loginUser, projectCode, 1, shellJson, taskJson, "2020-02-21 00:00:00", true, "", "", 0, ""); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); // process instance null putMsg(result, Status.SUCCESS, projectCode); @@ -516,9 +521,9 @@ public class ProcessInstanceServiceTest { Map processInstanceNullRes = processInstanceService.updateProcessInstance(loginUser, projectCode, 1, shellJson, taskJson, "2020-02-21 00:00:00", true, "", "", 0, ""); - Assert.fail(); + Assertions.fail(); } catch (ServiceException ex) { - Assert.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST.getCode(), ex.getCode()); + Assertions.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST.getCode(), ex.getCode()); } // process instance not finish @@ -528,7 +533,7 @@ public class ProcessInstanceServiceTest { Map processInstanceNotFinishRes = processInstanceService.updateProcessInstance(loginUser, projectCode, 1, shellJson, taskJson, "2020-02-21 00:00:00", true, "", "", 0, ""); - Assert.assertEquals(Status.PROCESS_INSTANCE_STATE_OPERATION_ERROR, + Assertions.assertEquals(Status.PROCESS_INSTANCE_STATE_OPERATION_ERROR, processInstanceNotFinishRes.get(Constants.STATUS)); // process instance finish @@ -555,7 +560,7 @@ public class ProcessInstanceServiceTest { Map processInstanceFinishRes = processInstanceService.updateProcessInstance(loginUser, projectCode, 1, taskRelationJson, taskDefinitionJson, "2020-02-21 00:00:00", true, "", "", 0, "root"); - Assert.assertEquals(Status.SUCCESS, processInstanceFinishRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, processInstanceFinishRes.get(Constants.STATUS)); // success when(processDefineMapper.queryByCode(46L)).thenReturn(processDefinition); @@ -565,7 +570,7 @@ public class ProcessInstanceServiceTest { .thenReturn(1); Map successRes = processInstanceService.updateProcessInstance(loginUser, projectCode, 1, taskRelationJson, taskDefinitionJson, "2020-02-21 00:00:00", Boolean.FALSE, "", "", 0, "root"); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -581,7 +586,7 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, WORKFLOW_INSTANCE)).thenReturn(result); Map projectAuthFailRes = processInstanceService.queryParentInstanceBySubId(loginUser, projectCode, 1); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); // process instance null putMsg(result, Status.SUCCESS, projectCode); @@ -593,7 +598,7 @@ public class ProcessInstanceServiceTest { processInstanceService.queryParentInstanceBySubId(loginUser, projectCode, 1); } catch (ServiceException ex) { - Assert.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST.getCode(), ex.getCode()); + Assertions.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST.getCode(), ex.getCode()); } // not sub process @@ -603,7 +608,8 @@ public class ProcessInstanceServiceTest { when(processService.findProcessInstanceDetailById(1)).thenReturn(Optional.ofNullable(processInstance)); Map notSubProcessRes = processInstanceService.queryParentInstanceBySubId(loginUser, projectCode, 1); - Assert.assertEquals(Status.PROCESS_INSTANCE_NOT_SUB_PROCESS_INSTANCE, notSubProcessRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_INSTANCE_NOT_SUB_PROCESS_INSTANCE, + notSubProcessRes.get(Constants.STATUS)); // sub process processInstance.setIsSubProcess(Flag.YES); @@ -611,13 +617,13 @@ public class ProcessInstanceServiceTest { when(processService.findParentProcessInstance(1)).thenReturn(null); Map subProcessNullRes = processInstanceService.queryParentInstanceBySubId(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUB_PROCESS_INSTANCE_NOT_EXIST, subProcessNullRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUB_PROCESS_INSTANCE_NOT_EXIST, subProcessNullRes.get(Constants.STATUS)); // success putMsg(result, Status.SUCCESS, projectCode); when(processService.findParentProcessInstance(1)).thenReturn(processInstance); Map successRes = processInstanceService.queryParentInstanceBySubId(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } @Test @@ -633,7 +639,7 @@ public class ProcessInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, INSTANCE_DELETE)).thenReturn(result); Map projectAuthFailRes = processInstanceService.deleteProcessInstanceById(loginUser, projectCode, 1); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, projectAuthFailRes.get(Constants.STATUS)); // not sub process ProcessInstance processInstance = getProcessInstance(); @@ -643,9 +649,9 @@ public class ProcessInstanceServiceTest { when(processService.findProcessInstanceDetailById(1)).thenReturn(Optional.ofNullable(processInstance)); try { processInstanceService.deleteProcessInstanceById(loginUser, projectCode, 1); - Assert.fail(); + Assertions.fail(); } catch (ServiceException ex) { - Assert.assertEquals(Status.PROCESS_INSTANCE_STATE_OPERATION_ERROR.getCode(), ex.getCode()); + Assertions.assertEquals(Status.PROCESS_INSTANCE_STATE_OPERATION_ERROR.getCode(), ex.getCode()); } processInstance.setState(WorkflowExecutionStatus.SUCCESS); @@ -661,23 +667,23 @@ public class ProcessInstanceServiceTest { when(processDefineMapper.queryByCode(46L)).thenReturn(processDefinition); try { processInstanceService.deleteProcessInstanceById(loginUser, projectCode, 1); - Assert.fail(); + Assertions.fail(); } catch (ServiceException ex) { - Assert.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST.getCode(), ex.getCode()); + Assertions.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST.getCode(), ex.getCode()); } processDefinition.setProjectCode(projectCode); when(processService.deleteWorkProcessInstanceById(1)).thenReturn(1); Map successRes = processInstanceService.deleteProcessInstanceById(loginUser, projectCode, 1); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); when(processService.deleteWorkProcessInstanceById(1)).thenReturn(0); try { processInstanceService.deleteProcessInstanceById(loginUser, projectCode, 1); - Assert.fail(); + Assertions.fail(); } catch (ServiceException ex) { - Assert.assertEquals(Status.DELETE_PROCESS_INSTANCE_BY_ID_ERROR.getCode(), ex.getCode()); + Assertions.assertEquals(Status.DELETE_PROCESS_INSTANCE_BY_ID_ERROR.getCode(), ex.getCode()); } } @@ -690,12 +696,12 @@ public class ProcessInstanceServiceTest { processInstance.setGlobalParams(""); when(processInstanceMapper.queryDetailById(1)).thenReturn(processInstance); Map successRes = processInstanceService.viewVariables(1L, 1); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); when(processInstanceMapper.queryDetailById(1)).thenReturn(null); Map processNotExist = processInstanceService.viewVariables(1L, 1); - Assert.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST, processNotExist.get(Constants.STATUS)); - + Assertions.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST, processNotExist.get(Constants.STATUS)); } @Test @@ -719,11 +725,11 @@ public class ProcessInstanceServiceTest { .thenReturn(graph); Map successRes = processInstanceService.viewGantt(0L, 1); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); when(processInstanceMapper.queryDetailById(1)).thenReturn(null); Map processNotExist = processInstanceService.viewVariables(1L, 1); - Assert.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST, processNotExist.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_INSTANCE_NOT_EXIST, processNotExist.get(Constants.STATUS)); } /** diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessTaskRelationServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessTaskRelationServiceTest.java index 0829486a86..b1ae0537a0 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessTaskRelationServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessTaskRelationServiceTest.java @@ -52,16 +52,16 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -import org.junit.runner.RunWith; +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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -70,7 +70,8 @@ import com.google.common.collect.Lists; /** * process task instance relation service test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ProcessTaskRelationServiceTest { @InjectMocks @@ -107,7 +108,7 @@ public class ProcessTaskRelationServiceTest { protected User user; protected Exception exception; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -302,7 +303,7 @@ public class ProcessTaskRelationServiceTest { Mockito.when(processTaskRelationMapper.batchInsert(processTaskRelationList)).thenReturn(1); Mockito.when(processTaskRelationLogMapper.batchInsert(processTaskRelationLogList)).thenReturn(1); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -350,8 +351,8 @@ public class ProcessTaskRelationServiceTest { } Map relation = processTaskRelationService .queryDownstreamRelation(user, projectCode, taskCode); - Assert.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); - Assert.assertEquals(2, ((List) relation.get("data")).size()); + Assertions.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); + Assertions.assertEquals(2, ((List) relation.get("data")).size()); } @Test @@ -398,8 +399,8 @@ public class ProcessTaskRelationServiceTest { } Map relation = processTaskRelationService .queryUpstreamRelation(user, projectCode, taskCode); - Assert.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); - Assert.assertEquals(2, ((List) relation.get("data")).size()); + Assertions.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); + Assertions.assertEquals(2, ((List) relation.get("data")).size()); } @Test @@ -430,7 +431,7 @@ public class ProcessTaskRelationServiceTest { .thenReturn(1); Map result1 = processTaskRelationService.deleteDownstreamRelation(user, projectCode, "123", taskCode); - Assert.assertEquals(Status.SUCCESS, result1.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result1.get(Constants.STATUS)); } @Test @@ -460,7 +461,7 @@ public class ProcessTaskRelationServiceTest { processTaskRelationList.stream().map(ProcessTaskRelationLog::new).collect(Collectors.toList()); Mockito.when(processService.saveTaskRelation(user, 1L, 1L, 1, relationLogs, Lists.newArrayList(), Boolean.TRUE)).thenReturn(0); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -497,9 +498,10 @@ public class ProcessTaskRelationServiceTest { .thenReturn(processTaskRelationList); List relationLogs = processTaskRelationList.stream().map(ProcessTaskRelationLog::new).collect(Collectors.toList()); + Mockito.when(processService.saveTaskRelation(user, 1L, 1L, 1, relationLogs, Lists.newArrayList(), Boolean.TRUE)).thenReturn(0); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -530,7 +532,7 @@ public class ProcessTaskRelationServiceTest { processTaskRelationList.stream().map(ProcessTaskRelationLog::new).collect(Collectors.toList()); Mockito.when(processService.saveTaskRelation(user, 1L, 1L, 1, relationLogs, Lists.newArrayList(), Boolean.TRUE)).thenReturn(0); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProjectServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProjectServiceTest.java index eaf8d6cff3..fbf49591a7 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProjectServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProjectServiceTest.java @@ -50,20 +50,23 @@ import java.util.List; import java.util.Map; import java.util.Set; -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.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; /** * project service test **/ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ProjectServiceTest { private static final Logger logger = LoggerFactory.getLogger(ProjectServiceTest.class); @@ -102,19 +105,19 @@ public class ProjectServiceTest { baseServiceLogger)).thenReturn(true); Result result = projectService.createProject(loginUser, projectName, getDesc()); logger.info(result.toString()); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), 10001); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), 10001); // project name exist Mockito.when(projectMapper.queryByName(projectName)).thenReturn(getProject()); result = projectService.createProject(loginUser, projectName, projectName); logger.info(result.toString()); - Assert.assertEquals(Status.PROJECT_ALREADY_EXISTS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.PROJECT_ALREADY_EXISTS.getCode(), result.getCode().intValue()); // success Mockito.when(projectMapper.insert(Mockito.any(Project.class))).thenReturn(1); result = projectService.createProject(loginUser, "test", "test"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @@ -127,14 +130,14 @@ public class ProjectServiceTest { Map result = projectService.checkProjectAndAuth(loginUser, null, projectCode, PROJECT); logger.info(result.toString()); Status status = (Status) result.get(Constants.STATUS); - Assert.assertEquals(Status.PROJECT_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_EXIST, result.get(Constants.STATUS)); Project project = getProject(); // USER_NO_OPERATION_PROJECT_PERM project.setUserId(2); result = projectService.checkProjectAndAuth(loginUser, project, projectCode, PROJECT); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PROJECT_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PROJECT_PERM, result.get(Constants.STATUS)); // success project.setUserId(1); @@ -147,12 +150,12 @@ public class ProjectServiceTest { 0, baseServiceLogger)).thenReturn(true); result = projectService.checkProjectAndAuth(loginUser, project, projectCode, PROJECT); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); Map result2 = new HashMap<>(); result2 = projectService.checkProjectAndAuth(loginUser, null, projectCode, PROJECT); - Assert.assertEquals(Status.PROJECT_NOT_EXIST, result2.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_EXIST, result2.get(Constants.STATUS)); Project project1 = getProject(); // USER_NO_OPERATION_PROJECT_PERM @@ -162,7 +165,7 @@ public class ProjectServiceTest { new Object[]{project.getId()}, loginUser.getId(), PROJECT, baseServiceLogger)).thenReturn(true); result2 = projectService.checkProjectAndAuth(loginUser, project1, projectCode, PROJECT); - Assert.assertEquals(Status.USER_NO_OPERATION_PROJECT_PERM, result2.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PROJECT_PERM, result2.get(Constants.STATUS)); // success project1.setUserId(1); @@ -186,7 +189,7 @@ public class ProjectServiceTest { tempUser.getId(), null, baseServiceLogger)).thenReturn(true); boolean checkResult = projectService.hasProjectAndPerm(tempUser, project, result, null); logger.info(result.toString()); - Assert.assertFalse(checkResult); + Assertions.assertFalse(checkResult); // success result = new HashMap<>(); @@ -200,7 +203,7 @@ public class ProjectServiceTest { 0, baseServiceLogger)).thenReturn(true); checkResult = projectService.hasProjectAndPerm(loginUser, project, result, null); logger.info(result.toString()); - Assert.assertTrue(checkResult); + Assertions.assertTrue(checkResult); } @Test @@ -213,7 +216,7 @@ public class ProjectServiceTest { // PROJECT_NOT_FOUNT Result result = projectService.deleteProject(loginUser, 11L); logger.info(result.toString()); - Assert.assertTrue(Status.PROJECT_NOT_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.PROJECT_NOT_EXIST.getCode() == result.getCode()); loginUser.setId(2); // USER_NO_OPERATION_PROJECT_PERM Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.PROJECTS, new Object[]{1}, @@ -221,7 +224,7 @@ public class ProjectServiceTest { baseServiceLogger)).thenReturn(true); result = projectService.deleteProject(loginUser, 1L); logger.info(result.toString()); - Assert.assertTrue(Status.USER_NO_OPERATION_PROJECT_PERM.getCode() == result.getCode()); + Assertions.assertTrue(Status.USER_NO_OPERATION_PROJECT_PERM.getCode() == result.getCode()); // DELETE_PROJECT_ERROR_DEFINES_NOT_NULL Mockito.when(processDefinitionMapper.queryAllDefinitionList(1L)).thenReturn(getProcessDefinitions()); @@ -233,14 +236,14 @@ public class ProjectServiceTest { .thenReturn(true); result = projectService.deleteProject(loginUser, 1L); logger.info(result.toString()); - Assert.assertTrue(Status.DELETE_PROJECT_ERROR_DEFINES_NOT_NULL.getCode() == result.getCode()); + Assertions.assertTrue(Status.DELETE_PROJECT_ERROR_DEFINES_NOT_NULL.getCode() == result.getCode()); // success Mockito.when(projectMapper.deleteById(1)).thenReturn(1); Mockito.when(processDefinitionMapper.queryAllDefinitionList(1L)).thenReturn(new ArrayList<>()); result = projectService.deleteProject(loginUser, 1L); logger.info(result.toString()); - Assert.assertTrue(Status.SUCCESS.getCode() == result.getCode()); + Assertions.assertTrue(Status.SUCCESS.getCode() == result.getCode()); } @Test @@ -261,16 +264,16 @@ public class ProjectServiceTest { // PROJECT_NOT_FOUNT Result result = projectService.update(loginUser, 1L, projectName, "desc", "testUser"); logger.info(result.toString()); - Assert.assertTrue(Status.PROJECT_NOT_FOUND.getCode() == result.getCode()); + Assertions.assertTrue(Status.PROJECT_NOT_FOUND.getCode() == result.getCode()); // PROJECT_ALREADY_EXISTS result = projectService.update(loginUser, 2L, projectName, "desc", userName); logger.info(result.toString()); - Assert.assertTrue(Status.PROJECT_ALREADY_EXISTS.getCode() == result.getCode()); + Assertions.assertTrue(Status.PROJECT_ALREADY_EXISTS.getCode() == result.getCode()); Mockito.when(userMapper.queryByUserNameAccurately(Mockito.any())).thenReturn(null); result = projectService.update(loginUser, 2L, "test", "desc", "testuser"); - Assert.assertTrue(Status.USER_NOT_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.USER_NOT_EXIST.getCode() == result.getCode()); // success Mockito.when(userMapper.queryByUserNameAccurately(Mockito.any())).thenReturn(new User()); @@ -278,7 +281,7 @@ public class ProjectServiceTest { Mockito.when(projectMapper.updateById(Mockito.any(Project.class))).thenReturn(1); result = projectService.update(loginUser, 2L, "test", "desc", "testUser"); logger.info(result.toString()); - Assert.assertTrue(Status.SUCCESS.getCode() == result.getCode()); + Assertions.assertTrue(Status.SUCCESS.getCode() == result.getCode()); } @@ -293,14 +296,14 @@ public class ProjectServiceTest { Result result = projectService.queryAuthorizedProject(loginUser, 2); logger.info(result.toString()); List projects = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(projects)); // test non-admin user loginUser.setUserType(UserType.GENERAL_USER); loginUser.setId(3); result = projectService.queryAuthorizedProject(loginUser, 2); projects = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(projects)); } @Test @@ -310,14 +313,14 @@ public class ProjectServiceTest { // Failure 1: PROJECT_NOT_FOUND Result result = this.projectService.queryAuthorizedUser(loginUser, 3682329499136L); logger.info("FAILURE 1: {}", result.toString()); - Assert.assertTrue(Status.PROJECT_NOT_FOUND.getCode() == result.getCode()); + Assertions.assertTrue(Status.PROJECT_NOT_FOUND.getCode() == result.getCode()); // Failure 2: USER_NO_OPERATION_PROJECT_PERM loginUser.setId(100); Mockito.when(this.projectMapper.queryByCode(Mockito.anyLong())).thenReturn(this.getProject()); result = this.projectService.queryAuthorizedUser(loginUser, 3682329499136L); logger.info("FAILURE 2: {}", result.toString()); - Assert.assertTrue(Status.USER_NO_OPERATION_PROJECT_PERM.getCode() == result.getCode()); + Assertions.assertTrue(Status.USER_NO_OPERATION_PROJECT_PERM.getCode() == result.getCode()); // SUCCESS loginUser.setUserType(UserType.ADMIN_USER); @@ -331,7 +334,7 @@ public class ProjectServiceTest { result = this.projectService.queryAuthorizedUser(loginUser, 3682329499136L); logger.info("SUCCESS 1: {}", result.toString()); List users = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(users)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(users)); loginUser.setId(1); loginUser.setUserType(UserType.GENERAL_USER); @@ -344,7 +347,7 @@ public class ProjectServiceTest { result = this.projectService.queryAuthorizedUser(loginUser, 3682329499136L); logger.info("SUCCESS 2: {}", result.toString()); users = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(users)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(users)); } @Test @@ -359,7 +362,7 @@ public class ProjectServiceTest { Map result = projectService.queryProjectCreatedByUser(loginUser); logger.info(result.toString()); List projects = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(projects)); } @@ -378,7 +381,7 @@ public class ProjectServiceTest { Mockito.when(projectMapper.selectBatchIds(set)).thenReturn(getList()); result = projectService.queryProjectCreatedAndAuthorizedByUser(loginUser); List notAdminUserResult = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(notAdminUserResult)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(notAdminUserResult)); // admin user loginUser.setUserType(UserType.ADMIN_USER); @@ -388,7 +391,7 @@ public class ProjectServiceTest { result = projectService.queryProjectCreatedAndAuthorizedByUser(loginUser); List projects = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(projects)); } @@ -401,7 +404,7 @@ public class ProjectServiceTest { Result result = projectService.queryAllProjectList(user); logger.info(result.toString()); List projects = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(projects)); } @Test @@ -411,7 +414,7 @@ public class ProjectServiceTest { Result result = projectService.queryAllProjectListForDependent(); logger.info(result.toString()); List projects = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(projects)); } @@ -433,7 +436,7 @@ public class ProjectServiceTest { Result result = projectService.queryUnauthorizedProject(loginUser, 2); logger.info(result.toString()); List projects = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(projects)); // test non-admin user loginUser.setId(2); @@ -446,7 +449,7 @@ public class ProjectServiceTest { result = projectService.queryUnauthorizedProject(loginUser, 3); logger.info(result.toString()); projects = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(projects)); } private Project getProject() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java index a836a19b1e..a6a16cc34e 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java @@ -43,16 +43,17 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; -import org.junit.runner.RunWith; +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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,7 +63,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * queue service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class QueueServiceTest { private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); @@ -86,11 +88,11 @@ public class QueueServiceTest { private static final String NOT_EXISTS = "not_exists"; private static final String NOT_EXISTS_FINAL = "not_exists_final"; - @Before + @BeforeEach public void setUp() { } - @After + @AfterEach public void after() { } @@ -98,11 +100,12 @@ public class QueueServiceTest { public void testQueryList() { Set ids = new HashSet<>(); ids.add(1); - Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.QUEUE, getLoginUser().getId(), queueServiceImplLogger)).thenReturn(ids); + Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.QUEUE, + getLoginUser().getId(), queueServiceImplLogger)).thenReturn(ids); Mockito.when(queueMapper.selectBatchIds(Mockito.anySet())).thenReturn(getQueueList()); Result result = queueService.queryList(getLoginUser()); List queueList = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(queueList)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(queueList)); } @@ -114,31 +117,37 @@ public class QueueServiceTest { page.setRecords(getQueueList()); Set ids = new HashSet<>(); ids.add(1); - Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.QUEUE, getLoginUser().getId(), queueServiceImplLogger)).thenReturn(ids); - Mockito.when(queueMapper.queryQueuePaging(Mockito.any(Page.class), Mockito.anyList(), Mockito.eq(QUEUE_NAME))).thenReturn(page); + Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.QUEUE, + getLoginUser().getId(), queueServiceImplLogger)).thenReturn(ids); + Mockito.when(queueMapper.queryQueuePaging(Mockito.any(Page.class), Mockito.anyList(), Mockito.eq(QUEUE_NAME))) + .thenReturn(page); Result result = queueService.queryList(getLoginUser(), QUEUE_NAME, 1, 10); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @Test public void testCreateQueue() { - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.QUEUE, null, getLoginUser().getId(), YARN_QUEUE_CREATE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.QUEUE, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.QUEUE, null, + getLoginUser().getId(), YARN_QUEUE_CREATE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.QUEUE, null, 0, + baseServiceLogger)).thenReturn(true); // queue is null - Throwable exception = Assertions.assertThrows(ServiceException.class, () -> queueService.createQueue(getLoginUser(), null, QUEUE_NAME)); + Throwable exception = Assertions.assertThrows(ServiceException.class, + () -> queueService.createQueue(getLoginUser(), null, QUEUE_NAME)); String formatter = MessageFormat.format(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getMsg(), Constants.QUEUE); Assertions.assertEquals(formatter, exception.getMessage()); // queueName is null - exception = Assertions.assertThrows(ServiceException.class, () -> queueService.createQueue(getLoginUser(), QUEUE_NAME, null)); + exception = Assertions.assertThrows(ServiceException.class, + () -> queueService.createQueue(getLoginUser(), QUEUE_NAME, null)); formatter = MessageFormat.format(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getMsg(), Constants.QUEUE_NAME); Assertions.assertEquals(formatter, exception.getMessage()); // correct Result result = queueService.createQueue(getLoginUser(), QUEUE_NAME, QUEUE_NAME); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test @@ -146,64 +155,72 @@ public class QueueServiceTest { Mockito.when(queueMapper.selectById(1)).thenReturn(getQUEUE()); Mockito.when(queueMapper.existQueue(EXISTS, null)).thenReturn(true); Mockito.when(queueMapper.existQueue(null, EXISTS)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.QUEUE, null, getLoginUser().getId(), YARN_QUEUE_UPDATE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.QUEUE, new Object[]{0}, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.QUEUE, null, + getLoginUser().getId(), YARN_QUEUE_UPDATE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.QUEUE, new Object[]{0}, 0, + baseServiceLogger)).thenReturn(true); // not exist - Throwable exception = Assertions.assertThrows(ServiceException.class, () -> queueService.updateQueue(getLoginUser(), 0, QUEUE, QUEUE_NAME)); + Throwable exception = Assertions.assertThrows(ServiceException.class, + () -> queueService.updateQueue(getLoginUser(), 0, QUEUE, QUEUE_NAME)); String formatter = MessageFormat.format(Status.QUEUE_NOT_EXIST.getMsg(), QUEUE); Assertions.assertEquals(formatter, exception.getMessage()); - //no need update - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.QUEUE, new Object[]{1}, 0, baseServiceLogger)).thenReturn(true); - exception = Assertions.assertThrows(ServiceException.class, () -> queueService.updateQueue(getLoginUser(), 1, QUEUE_NAME, QUEUE_NAME)); + // no need update + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.QUEUE, new Object[]{1}, 0, + baseServiceLogger)).thenReturn(true); + exception = Assertions.assertThrows(ServiceException.class, + () -> queueService.updateQueue(getLoginUser(), 1, QUEUE_NAME, QUEUE_NAME)); Assertions.assertEquals(Status.NEED_NOT_UPDATE_QUEUE.getMsg(), exception.getMessage()); - //queue exist - exception = Assertions.assertThrows(ServiceException.class, () -> queueService.updateQueue(getLoginUser(), 1, EXISTS, QUEUE_NAME)); + // queue exist + exception = Assertions.assertThrows(ServiceException.class, + () -> queueService.updateQueue(getLoginUser(), 1, EXISTS, QUEUE_NAME)); formatter = MessageFormat.format(Status.QUEUE_VALUE_EXIST.getMsg(), EXISTS); Assertions.assertEquals(formatter, exception.getMessage()); // queueName exist - exception = Assertions.assertThrows(ServiceException.class, () -> queueService.updateQueue(getLoginUser(), 1, NOT_EXISTS, EXISTS)); + exception = Assertions.assertThrows(ServiceException.class, + () -> queueService.updateQueue(getLoginUser(), 1, NOT_EXISTS, EXISTS)); formatter = MessageFormat.format(Status.QUEUE_NAME_EXIST.getMsg(), EXISTS); Assertions.assertEquals(formatter, exception.getMessage()); - //success + // success Mockito.when(userMapper.existUser(Mockito.anyString())).thenReturn(false); Result result = queueService.updateQueue(getLoginUser(), 1, NOT_EXISTS, NOT_EXISTS); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); // success update with same queue name Mockito.when(queueMapper.existQueue(NOT_EXISTS_FINAL, null)).thenReturn(false); result = queueService.updateQueue(getLoginUser(), 1, NOT_EXISTS_FINAL, NOT_EXISTS); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); // success update with same queue value Mockito.when(queueMapper.existQueue(null, NOT_EXISTS_FINAL)).thenReturn(false); result = queueService.updateQueue(getLoginUser(), 1, NOT_EXISTS, NOT_EXISTS_FINAL); - Assert.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), result.getCode().intValue()); } @Test public void testVerifyQueue() { - //queue null - Throwable exception = Assertions.assertThrows(ServiceException.class, () -> queueService.verifyQueue(null, QUEUE_NAME)); + // queue null + Throwable exception = + Assertions.assertThrows(ServiceException.class, () -> queueService.verifyQueue(null, QUEUE_NAME)); String formatter = MessageFormat.format(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getMsg(), Constants.QUEUE); Assertions.assertEquals(formatter, exception.getMessage()); - //queueName null + // queueName null exception = Assertions.assertThrows(ServiceException.class, () -> queueService.verifyQueue(QUEUE_NAME, null)); formatter = MessageFormat.format(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getMsg(), Constants.QUEUE_NAME); Assertions.assertEquals(formatter, exception.getMessage()); - //exist queueName + // exist queueName Mockito.when(queueMapper.existQueue(EXISTS, null)).thenReturn(true); exception = Assertions.assertThrows(ServiceException.class, () -> queueService.verifyQueue(EXISTS, QUEUE_NAME)); formatter = MessageFormat.format(Status.QUEUE_VALUE_EXIST.getMsg(), EXISTS); Assertions.assertEquals(formatter, exception.getMessage()); - //exist queue + // exist queue Mockito.when(queueMapper.existQueue(null, EXISTS)).thenReturn(true); exception = Assertions.assertThrows(ServiceException.class, () -> queueService.verifyQueue(QUEUE, EXISTS)); formatter = MessageFormat.format(Status.QUEUE_NAME_EXIST.getMsg(), EXISTS); @@ -211,7 +228,7 @@ public class QueueServiceTest { // success Result result = queueService.verifyQueue(NOT_EXISTS, NOT_EXISTS); - Assert.assertEquals(result.getCode().intValue(), Status.SUCCESS.getCode()); + Assertions.assertEquals(result.getCode().intValue(), Status.SUCCESS.getCode()); } @Test @@ -221,12 +238,12 @@ public class QueueServiceTest { // queue exists Mockito.when(queueMapper.queryQueueName(QUEUE, QUEUE_NAME)).thenReturn(getQUEUE()); queue = queueService.createQueueIfNotExists(QUEUE, QUEUE_NAME); - Assert.assertEquals(getQUEUE(), queue); + Assertions.assertEquals(getQUEUE(), queue); // queue not exists Mockito.when(queueMapper.queryQueueName(QUEUE, QUEUE_NAME)).thenReturn(null); queue = queueService.createQueueIfNotExists(QUEUE, QUEUE_NAME); - Assert.assertEquals(new Queue(QUEUE_NAME, QUEUE), queue); + Assertions.assertEquals(new Queue(QUEUE_NAME, QUEUE), queue); } /** diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java index 58c1d23d9d..68df168aca 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java @@ -57,16 +57,18 @@ import java.util.Map; import java.util.Random; import java.util.Set; -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.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; 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 org.springframework.mock.web.MockMultipartFile; @@ -78,7 +80,8 @@ import com.google.common.io.Files; /** * resources service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ResourcesServiceTest { private static final Logger logger = LoggerFactory.getLogger(ResourcesServiceTest.class); @@ -122,7 +125,7 @@ public class ResourcesServiceTest { private MockedStatic mockedStaticPropertyUtils; - @Before + @BeforeEach public void setUp() { mockedStaticFileUtils = Mockito.mockStatic(FileUtils.class); mockedStaticFiles = Mockito.mockStatic(Files.class); @@ -132,7 +135,7 @@ public class ResourcesServiceTest { mockedStaticPropertyUtils = Mockito.mockStatic(PropertyUtils.class); } - @After + @AfterEach public void after() { mockedStaticFileUtils.close(); mockedStaticFiles.close(); @@ -160,7 +163,7 @@ public class ResourcesServiceTest { Result result = resourcesService.createResource(user, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, mockMultipartFile, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); // set tenant for user user.setTenantId(1); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); @@ -170,7 +173,7 @@ public class ResourcesServiceTest { result = resourcesService.createResource(user, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, null, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); // RESOURCE_FILE_IS_EMPTY mockMultipartFile = new MockMultipartFile("test.pdf", "".getBytes()); @@ -178,7 +181,7 @@ public class ResourcesServiceTest { result = resourcesService.createResource(user, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, mockMultipartFile, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_FILE_IS_EMPTY.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_FILE_IS_EMPTY.getMsg(), result.getMsg()); // RESOURCE_SUFFIX_FORBID_CHANGE mockMultipartFile = new MockMultipartFile("test.pdf", "test.pdf", "pdf", "test".getBytes()); @@ -187,7 +190,7 @@ public class ResourcesServiceTest { result = resourcesService.createResource(user, "ResourcesServiceTest.jar", "ResourcesServiceTest", ResourceType.FILE, mockMultipartFile, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_SUFFIX_FORBID_CHANGE.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_SUFFIX_FORBID_CHANGE.getMsg(), result.getMsg()); // UDF_RESOURCE_SUFFIX_NOT_JAR Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, @@ -201,7 +204,7 @@ public class ResourcesServiceTest { result = resourcesService.createResource(user, "ResourcesServiceTest.pdf", "ResourcesServiceTest", ResourceType.UDF, mockMultipartFile, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.UDF_RESOURCE_SUFFIX_NOT_JAR.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.UDF_RESOURCE_SUFFIX_NOT_JAR.getMsg(), result.getMsg()); // FULL_FILE_NAME_TOO_LONG Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, @@ -216,7 +219,7 @@ public class ResourcesServiceTest { result = resourcesService.createResource(user, tooLongFileName, tooLongFileName, ResourceType.FILE, mockMultipartFile, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_FULL_NAME_TOO_LONG_ERROR.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_FULL_NAME_TOO_LONG_ERROR.getMsg(), result.getMsg()); } @Test @@ -234,7 +237,7 @@ public class ResourcesServiceTest { Result result = resourcesService.createDirectory(user, "directoryTest", "directory test", ResourceType.FILE, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); // PARENT_RESOURCE_NOT_EXIST user.setId(1); @@ -251,19 +254,19 @@ public class ResourcesServiceTest { result = resourcesService.createDirectory(user, "directoryTest", "directory test", ResourceType.FILE, 1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.PARENT_RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.PARENT_RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // RESOURCE_EXIST Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); Mockito.when(resourcesMapper.existResource("/directoryTest", 0)).thenReturn(true); result = resourcesService.createDirectory(user, "directoryTest", "directory test", ResourceType.FILE, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); // Description_Lingth_ERROR result = resourcesService.createDirectory(user, "directoryTest", "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", ResourceType.FILE, -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.DESCRIPTION_TOO_LONG_ERROR.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.DESCRIPTION_TOO_LONG_ERROR.getMsg(), result.getMsg()); } @Test @@ -282,7 +285,7 @@ public class ResourcesServiceTest { Result result = resourcesService.updateResource(user, 1, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, null); logger.info(result.toString()); - Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); // RESOURCE_NOT_EXIST Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, @@ -294,7 +297,7 @@ public class ResourcesServiceTest { result = resourcesService.updateResource(user, 0, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, null); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // USER_NO_OPERATION_PERM user.setId(2); @@ -306,7 +309,7 @@ public class ResourcesServiceTest { result = resourcesService.updateResource(user, 1, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, null); logger.info(result.toString()); - Assert.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION.getMsg(), result.getMsg()); // RESOURCE_NOT_EXIST user.setId(1); @@ -325,7 +328,7 @@ public class ResourcesServiceTest { } result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", ResourceType.UDF, null); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // SUCCESS user.setId(1); @@ -344,21 +347,21 @@ public class ResourcesServiceTest { result = resourcesService.updateResource(user, 1, "ResourcesServiceTest.jar", "ResourcesServiceTest", ResourceType.FILE, null); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); // RESOURCE_EXIST Mockito.when(resourcesMapper.existResource("/ResourcesServiceTest1.jar", 0)).thenReturn(true); result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", ResourceType.FILE, null); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); // USER_NOT_EXIST Mockito.when(userMapper.selectById(Mockito.anyInt())).thenReturn(null); result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", ResourceType.UDF, null); logger.info(result.toString()); - Assert.assertTrue(Status.USER_NOT_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.USER_NOT_EXIST.getCode() == result.getCode()); // TENANT_NOT_EXIST Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); @@ -366,7 +369,7 @@ public class ResourcesServiceTest { result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", ResourceType.UDF, null); logger.info(result.toString()); - Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); // SUCCESS Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); @@ -374,7 +377,7 @@ public class ResourcesServiceTest { result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest1.jar", ResourceType.UDF, null); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @@ -395,9 +398,9 @@ public class ResourcesServiceTest { .thenReturn(resourcePage); Result result = resourcesService.queryResourceListPaging(loginUser, -1, ResourceType.FILE, "test", 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @@ -413,9 +416,9 @@ public class ResourcesServiceTest { Map result = resourcesService.queryResourceList(loginUser, ResourceType.FILE); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List resourceList = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(resourceList)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(resourceList)); // test udf Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.UDF_FILE, 0, @@ -428,9 +431,9 @@ public class ResourcesServiceTest { loginUser.setUserType(UserType.GENERAL_USER); result = resourcesService.queryResourceList(loginUser, ResourceType.UDF); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); resourceList = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(resourceList.size() == 4); + Assertions.assertTrue(resourceList.size() == 4); } @Test @@ -452,7 +455,7 @@ public class ResourcesServiceTest { // HDFS_NOT_STARTUP Result result = resourcesService.delete(loginUser, 1); logger.info(result.toString()); - Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); // RESOURCE_NOT_EXIST Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); @@ -465,12 +468,12 @@ public class ResourcesServiceTest { result = resourcesService.delete(loginUser, 2); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // USER_NO_OPERATION_PERM result = resourcesService.delete(loginUser, 2); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // TENANT_NOT_EXIST loginUser.setUserType(UserType.ADMIN_USER); @@ -485,7 +488,7 @@ public class ResourcesServiceTest { 0, serviceLogger)).thenReturn(true); result = resourcesService.delete(loginUser, 1); logger.info(result.toString()); - Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); // SUCCESS loginUser.setTenantId(1); @@ -494,11 +497,11 @@ public class ResourcesServiceTest { Mockito.when(resourceUserMapper.deleteResourceUserArray(Mockito.anyInt(), Mockito.any())).thenReturn(1); result = resourcesService.delete(loginUser, 1); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } catch (Exception e) { logger.error("delete error", e); - Assert.assertTrue(false); + Assertions.assertTrue(false); } } @@ -515,7 +518,7 @@ public class ResourcesServiceTest { Mockito.when(resourcesMapper.existResource("/ResourcesServiceTest.jar", 0)).thenReturn(true); Result result = resourcesService.verifyResourceName("/ResourcesServiceTest.jar", ResourceType.FILE, user); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); // TENANT_NOT_EXIST Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); @@ -523,19 +526,19 @@ public class ResourcesServiceTest { result = resourcesService.verifyResourceName("/test.jar", ResourceType.FILE, user); logger.info(result.toString()); - Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); // RESOURCE_FILE_EXIST user.setTenantId(1); result = resourcesService.verifyResourceName("/ResourcesServiceTest.jar", ResourceType.FILE, user); logger.info(result.toString()); - Assert.assertTrue(Status.RESOURCE_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.RESOURCE_EXIST.getCode() == result.getCode()); // SUCCESS result = resourcesService.verifyResourceName("test2", ResourceType.FILE, user); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @@ -552,7 +555,7 @@ public class ResourcesServiceTest { // HDFS_NOT_STARTUP Result result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); // RESOURCE_NOT_EXIST Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); @@ -562,7 +565,7 @@ public class ResourcesServiceTest { result = resourcesService.readResource(getUser(), 2, 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // RESOURCE_SUFFIX_NOT_SUPPORT_VIEW Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, @@ -574,27 +577,27 @@ public class ResourcesServiceTest { Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); // USER_NOT_EXIST Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("jar"); Mockito.when(Files.getFileExtension("ResourcesServiceTest.jar")).thenReturn("jar"); result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.USER_NOT_EXIST.getCode(), (int) result.getCode()); // TENANT_NOT_EXIST Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); // RESOURCE_FILE_NOT_EXIST Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_FILE_NOT_EXIST.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.RESOURCE_FILE_NOT_EXIST.getCode(), (int) result.getCode()); // SUCCESS try { @@ -605,7 +608,7 @@ public class ResourcesServiceTest { } result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @@ -624,7 +627,7 @@ public class ResourcesServiceTest { Result result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); // RESOURCE_SUFFIX_NOT_SUPPORT_VIEW Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); @@ -632,7 +635,7 @@ public class ResourcesServiceTest { result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); // RuntimeException try { @@ -642,7 +645,7 @@ public class ResourcesServiceTest { -1, "/"); } catch (RuntimeException ex) { logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), ex.getMessage()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), ex.getMessage()); } // SUCCESS @@ -656,7 +659,7 @@ public class ResourcesServiceTest { result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, "/"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @@ -713,7 +716,7 @@ public class ResourcesServiceTest { Mockito.when(FileUtils.writeContent2File(Mockito.anyString(), Mockito.anyString())).thenReturn(true); Result result = resourcesService.onlineCreateOrUpdateResourceWithDir(user, fullName, desc, content); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @Test @@ -733,7 +736,7 @@ public class ResourcesServiceTest { AuthorizationType.RESOURCE_FILE_ID, new Object[]{file.getId()}, user.getId(), serviceLogger)) .thenReturn(true); Resource result = resourcesService.queryResourcesFileInfo(userName, file.getFullName()); - Assert.assertEquals(file.getFullName(), result.getFullName()); + Assertions.assertEquals(file.getFullName(), result.getFullName()); } @Test @@ -749,7 +752,7 @@ public class ResourcesServiceTest { Result result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); - Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); // RESOURCE_NOT_EXIST Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, @@ -758,7 +761,7 @@ public class ResourcesServiceTest { Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); result = resourcesService.updateResourceContent(getUser(), 2, "content"); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // RESOURCE_SUFFIX_NOT_SUPPORT_VIEW Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, @@ -770,20 +773,20 @@ public class ResourcesServiceTest { Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("class"); result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); // USER_NOT_EXIST Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("jar"); Mockito.when(Files.getFileExtension("ResourcesServiceTest.jar")).thenReturn("jar"); result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); - Assert.assertTrue(Status.USER_NOT_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.USER_NOT_EXIST.getCode() == result.getCode()); // TENANT_NOT_EXIST Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); - Assert.assertTrue(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getCode() == result.getCode()); // SUCCESS Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); @@ -791,7 +794,7 @@ public class ResourcesServiceTest { Mockito.when(FileUtils.writeContent2File(Mockito.anyString(), Mockito.anyString())).thenReturn(true); result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @Test @@ -810,16 +813,16 @@ public class ResourcesServiceTest { try { // resource null org.springframework.core.io.Resource resource = resourcesService.downloadResource(getUser(), 1); - Assert.assertNull(resource); + Assertions.assertNull(resource); Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); Mockito.when(org.apache.dolphinscheduler.api.utils.FileUtils.file2Resource(Mockito.any())) .thenReturn(resourceMock); resource = resourcesService.downloadResource(getUser(), 1); - Assert.assertNotNull(resource); + Assertions.assertNotNull(resource); } catch (Exception e) { logger.error("DownloadResource error", e); - Assert.assertTrue(false); + Assertions.assertTrue(false); } } @@ -838,9 +841,9 @@ public class ResourcesServiceTest { Mockito.when(resourcesMapper.queryResourceExceptUserId(userId)).thenReturn(getResourceList()); Map result = resourcesService.authorizeResourceTree(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List resources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(resources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(resources)); // test non-admin user user.setId(2); @@ -848,9 +851,9 @@ public class ResourcesServiceTest { Mockito.when(resourcesMapper.queryResourceListAuthored(user.getId(), -1)).thenReturn(getResourceList()); result = resourcesService.authorizeResourceTree(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); resources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(resources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(resources)); } @Test @@ -869,9 +872,9 @@ public class ResourcesServiceTest { Mockito.when(resourcesMapper.queryResourceListById(Mockito.any())).thenReturn(getSingleResourceList()); Map result = resourcesService.unauthorizedFile(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List resources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(resources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(resources)); // test non-admin user user.setId(2); @@ -879,9 +882,9 @@ public class ResourcesServiceTest { Mockito.when(resourcesMapper.queryResourceListAuthored(user.getId(), -1)).thenReturn(getResourceList()); result = resourcesService.unauthorizedFile(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); resources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(resources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(resources)); } @Test @@ -898,7 +901,7 @@ public class ResourcesServiceTest { Map result = resourcesService.unauthorizedUDFFunction(user, userId); logger.info(result.toString()); List udfFuncs = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(udfFuncs)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(udfFuncs)); // test non-admin user user.setId(2); @@ -907,9 +910,9 @@ public class ResourcesServiceTest { .thenReturn(getUdfFuncList()); result = resourcesService.unauthorizedUDFFunction(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); udfFuncs = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(udfFuncs)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(udfFuncs)); } @Test @@ -924,9 +927,9 @@ public class ResourcesServiceTest { Mockito.when(udfFunctionMapper.queryAuthedUdfFunc(userId)).thenReturn(getUdfFuncList()); Map result = resourcesService.authorizedUDFFunction(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List udfFuncs = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(udfFuncs)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(udfFuncs)); // test non-admin user user.setUserType(UserType.GENERAL_USER); @@ -934,9 +937,9 @@ public class ResourcesServiceTest { Mockito.when(udfFunctionMapper.queryAuthedUdfFunc(userId)).thenReturn(getUdfFuncList()); result = resourcesService.authorizedUDFFunction(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); udfFuncs = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(udfFuncs)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(udfFuncs)); } @Test @@ -955,9 +958,9 @@ public class ResourcesServiceTest { Mockito.when(resourcesMapper.queryResourceListById(Mockito.any())).thenReturn(getResourceList()); Map result = resourcesService.authorizedFile(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List resources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(resources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(resources)); // test non-admin user user.setId(2); @@ -967,9 +970,9 @@ public class ResourcesServiceTest { Mockito.when(resourcesMapper.queryResourceListById(Mockito.any())).thenReturn(getResourceList()); result = resourcesService.authorizedFile(user, userId); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); resources = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(resources)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(resources)); } @Test @@ -980,7 +983,7 @@ public class ResourcesServiceTest { // SUCCESS try { List list = storageOperate.vimFile(Mockito.any(), Mockito.anyString(), eq(1), eq(10)); - Assert.assertNotNull(list); + Assertions.assertNotNull(list); } catch (IOException e) { logger.error("hadoop error", e); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SchedulerServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SchedulerServiceTest.java index 5d65d96ea3..4bbbede043 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SchedulerServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SchedulerServiceTest.java @@ -43,20 +43,22 @@ import org.apache.dolphinscheduler.service.process.ProcessService; import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -import org.junit.runner.RunWith; +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 org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; /** * scheduler service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class SchedulerServiceTest extends BaseServiceTestTool { @InjectMocks @@ -107,7 +109,7 @@ public class SchedulerServiceTest extends BaseServiceTestTool { private static final String endTime = "2020-02-01 12:13:14"; private static final String crontab = "0 0 * * * ? *"; - @Before + @BeforeEach public void setUp() { user = new User(); user.setUserName(userName); @@ -139,29 +141,29 @@ public class SchedulerServiceTest extends BaseServiceTestTool { Mockito.when(projectService.hasProjectAndPerm(user, project, result, null)).thenReturn(true); // schedule not exists result = schedulerService.setScheduleState(user, project.getCode(), 2, ReleaseState.ONLINE); - Assert.assertEquals(Status.SCHEDULE_CRON_NOT_EXISTS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SCHEDULE_CRON_NOT_EXISTS, result.get(Constants.STATUS)); // SCHEDULE_CRON_REALEASE_NEED_NOT_CHANGE result = schedulerService.setScheduleState(user, project.getCode(), 1, ReleaseState.OFFLINE); - Assert.assertEquals(Status.SCHEDULE_CRON_REALEASE_NEED_NOT_CHANGE, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SCHEDULE_CRON_REALEASE_NEED_NOT_CHANGE, result.get(Constants.STATUS)); // PROCESS_DEFINE_NOT_EXIST schedule.setProcessDefinitionCode(2); result = schedulerService.setScheduleState(user, project.getCode(), 1, ReleaseState.ONLINE); - Assert.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DEFINE_NOT_EXIST, result.get(Constants.STATUS)); schedule.setProcessDefinitionCode(1); result = schedulerService.setScheduleState(user, project.getCode(), 1, ReleaseState.ONLINE); - Assert.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); processDefinition.setReleaseState(ReleaseState.ONLINE); result = schedulerService.setScheduleState(user, project.getCode(), 1, ReleaseState.ONLINE); - Assert.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); // SUCCESS result = schedulerService.setScheduleState(user, project.getCode(), 1, ReleaseState.ONLINE); - Assert.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); } @Test diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SessionServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SessionServiceTest.java index 0203cede9d..5c6aba6fb4 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SessionServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SessionServiceTest.java @@ -32,15 +32,15 @@ import java.util.Calendar; import java.util.Date; import java.util.List; -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.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mock.web.MockCookie; @@ -49,7 +49,7 @@ import org.springframework.mock.web.MockHttpServletRequest; /** * session service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class SessionServiceTest { private static final Logger logger = LoggerFactory.getLogger(SessionServiceTest.class); @@ -62,12 +62,12 @@ public class SessionServiceTest { private String sessionId = "aaaaaaaaaaaaaaaaaa"; - @Before + @BeforeEach public void setUp() { } - @After - public void after(){ + @AfterEach + public void after() { } /** @@ -77,25 +77,25 @@ public class SessionServiceTest { public void testGetSession() { Mockito.when(sessionMapper.selectById(sessionId)).thenReturn(getSession()); - // get sessionId from header + // get sessionId from header MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); - mockHttpServletRequest.addHeader(Constants.SESSION_ID,sessionId); - mockHttpServletRequest.addHeader("HTTP_X_FORWARDED_FOR","127.0.0.1"); - //query + mockHttpServletRequest.addHeader(Constants.SESSION_ID, sessionId); + mockHttpServletRequest.addHeader("HTTP_X_FORWARDED_FOR", "127.0.0.1"); + // query Session session = sessionService.getSession(mockHttpServletRequest); - Assert.assertNotNull(session); - logger.info("session ip {}",session.getIp()); + Assertions.assertNotNull(session); + logger.info("session ip {}", session.getIp()); // get sessionId from cookie mockHttpServletRequest = new MockHttpServletRequest(); - mockHttpServletRequest.addHeader("HTTP_X_FORWARDED_FOR","127.0.0.1"); - MockCookie mockCookie = new MockCookie(Constants.SESSION_ID,sessionId); + mockHttpServletRequest.addHeader("HTTP_X_FORWARDED_FOR", "127.0.0.1"); + MockCookie mockCookie = new MockCookie(Constants.SESSION_ID, sessionId); mockHttpServletRequest.setCookies(mockCookie); - //query + // query session = sessionService.getSession(mockHttpServletRequest); - Assert.assertNotNull(session); - logger.info("session ip {}",session.getIp()); - Assert.assertEquals(session.getIp(),"127.0.0.1"); + Assertions.assertNotNull(session); + logger.info("session ip {}", session.getIp()); + Assertions.assertEquals(session.getIp(), "127.0.0.1"); } /** @@ -110,7 +110,7 @@ public class SessionServiceTest { Mockito.when(sessionMapper.queryByUserId(1)).thenReturn(getSessions()); String sessionId = sessionService.createSession(user, ip); logger.info("createSessionId is " + sessionId); - Assert.assertTrue(!StringUtils.isEmpty(sessionId)); + Assertions.assertTrue(!StringUtils.isEmpty(sessionId)); } /** @@ -124,9 +124,9 @@ public class SessionServiceTest { User user = new User(); user.setId(userId); - Mockito.when(sessionMapper.queryByUserIdAndIp(userId,ip)).thenReturn(getSession()); + Mockito.when(sessionMapper.queryByUserIdAndIp(userId, ip)).thenReturn(getSession()); - sessionService.signOut(ip,user); + sessionService.signOut(ip, user); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskDefinitionServiceImplTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskDefinitionServiceImplTest.java index c63684ebc0..e25fd071b8 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskDefinitionServiceImplTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskDefinitionServiceImplTest.java @@ -58,17 +58,16 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -import org.junit.runner.RunWith; +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; -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class TaskDefinitionServiceImplTest { @InjectMocks @@ -114,7 +113,7 @@ public class TaskDefinitionServiceImplTest { protected User user; protected Exception exception; - @Before + @BeforeEach public void before() { User loginUser = new User(); loginUser.setId(1); @@ -148,7 +147,7 @@ public class TaskDefinitionServiceImplTest { Mockito.when(taskPluginManager.checkTaskParameters(Mockito.any())).thenReturn(true); Map relation = taskDefinitionService .createTaskDefinition(user, PROJECT_CODE, createTaskDefinitionJson); - Assert.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); } @Test @@ -161,6 +160,7 @@ public class TaskDefinitionServiceImplTest { + "\\\\\\\"failedNode\\\\\\\":[\\\\\\\"\\\\\\\"]}\\\",\\\"dependence\\\":{}}\",\"flag\":0,\"taskPriority\":0," + "\"workerGroup\":\"default\",\"failRetryTimes\":0,\"failRetryInterval\":0,\"timeoutFlag\":0," + "\"timeoutNotifyStrategy\":0,\"timeout\":0,\"delayTime\":0,\"resourceIds\":\"\"}"; + Project project = getProject(); Mockito.when(projectMapper.queryByCode(PROJECT_CODE)).thenReturn(project); @@ -176,7 +176,7 @@ public class TaskDefinitionServiceImplTest { Mockito.when(taskDefinitionLogMapper.queryMaxVersionForDefinition(TASK_CODE)).thenReturn(1); Mockito.when(taskPluginManager.checkTaskParameters(Mockito.any())).thenReturn(true); result = taskDefinitionService.updateTaskDefinition(user, PROJECT_CODE, TASK_CODE, taskDefinitionJson); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -196,7 +196,7 @@ public class TaskDefinitionServiceImplTest { Map relation = taskDefinitionService .queryTaskDefinitionByName(user, PROJECT_CODE, PROCESS_DEFINITION_CODE, taskName); - Assert.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); } @Test @@ -231,6 +231,7 @@ public class TaskDefinitionServiceImplTest { Mockito.when(projectMapper.queryByCode(PROJECT_CODE)).thenReturn(project); Map result = new HashMap<>(); + putMsg(result, Status.SUCCESS, PROJECT_CODE); Mockito.when( projectService.checkProjectAndAuth(user, project, PROJECT_CODE, WORKFLOW_SWITCH_TO_THIS_VERSION)) @@ -246,7 +247,7 @@ public class TaskDefinitionServiceImplTest { Map relation = taskDefinitionService .switchVersion(user, PROJECT_CODE, TASK_CODE, VERSION); - Assert.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, relation.get(Constants.STATUS)); } private void putMsg(Map result, Status status, Object... statusParams) { @@ -269,7 +270,7 @@ public class TaskDefinitionServiceImplTest { + "\"workerGroup\":\"default\",\"failRetryTimes\":0,\"failRetryInterval\":0,\"timeoutFlag\":0," + "\"timeoutNotifyStrategy\":0,\"timeout\":0,\"delayTime\":0,\"resourceIds\":\"\"}]"; List taskDefinitionLogs = JSONUtils.toList(taskDefinitionJson, TaskDefinitionLog.class); - Assert.assertFalse(taskDefinitionLogs.isEmpty()); + Assertions.assertFalse(taskDefinitionLogs.isEmpty()); String taskJson = "[{\"name\":\"shell1\",\"description\":\"\",\"taskType\":\"SHELL\",\"taskParams\":{\"resourceList\":[]," + "\"localParams\":[],\"rawScript\":\"echo 1\",\"conditionResult\":{\"successNode\":[\"\"],\"failedNode\":[\"\"]},\"dependence\":{}}," @@ -279,23 +280,23 @@ public class TaskDefinitionServiceImplTest { + ":[\"\"],\"failedNode\":[\"\"]},\"dependence\":{}},\"flag\":\"NORMAL\",\"taskPriority\":\"MEDIUM\",\"workerGroup\":\"default\"," + "\"failRetryTimes\":\"0\",\"failRetryInterval\":\"1\",\"timeoutFlag\":\"CLOSE\",\"timeoutNotifyStrategy\":\"\",\"timeout\":null,\"delayTime\":\"0\"}]"; taskDefinitionLogs = JSONUtils.toList(taskJson, TaskDefinitionLog.class); - Assert.assertFalse(taskDefinitionLogs.isEmpty()); + Assertions.assertFalse(taskDefinitionLogs.isEmpty()); String taskParams = "{\"resourceList\":[],\"localParams\":[{\"prop\":\"datetime\",\"direct\":\"IN\",\"type\":\"VARCHAR\"," + "\"value\":\"${system.datetime}\"}],\"rawScript\":\"echo ${datetime}\",\"conditionResult\":\"{\\\"successNode\\\":[\\\"\\\"]," + "\\\"failedNode\\\":[\\\"\\\"]}\",\"dependence\":{}}"; Map parameters = JSONUtils.parseObject(taskParams, Map.class); - Assert.assertNotNull(parameters); + Assertions.assertNotNull(parameters); String params = "{\"resourceList\":[],\"localParams\":[],\"rawScript\":\"echo 1\",\"conditionResult\":{\"successNode\":[\"\"],\"failedNode\":[\"\"]},\"dependence\":{}}"; Map parameters1 = JSONUtils.parseObject(params, Map.class); - Assert.assertNotNull(parameters1); + Assertions.assertNotNull(parameters1); } @Test public void genTaskCodeList() { Map genTaskCodeList = taskDefinitionService.genTaskCodeList(10); - Assert.assertEquals(Status.SUCCESS, genTaskCodeList.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, genTaskCodeList.get(Constants.STATUS)); } @Test @@ -309,7 +310,7 @@ public class TaskDefinitionServiceImplTest { Mockito.when(projectService.checkProjectAndAuth(user, project, PROJECT_CODE, null)).thenReturn(result); Map map = taskDefinitionService.releaseTaskDefinition(user, PROJECT_CODE, TASK_CODE, ReleaseState.OFFLINE); - Assert.assertEquals(Status.TASK_DEFINE_NOT_EXIST, map.get(Constants.STATUS)); + Assertions.assertEquals(Status.TASK_DEFINE_NOT_EXIST, map.get(Constants.STATUS)); // process definition offline putMsg(result, Status.SUCCESS); @@ -327,17 +328,17 @@ public class TaskDefinitionServiceImplTest { .thenReturn(taskDefinitionLog); Map offlineTaskResult = taskDefinitionService.releaseTaskDefinition(user, PROJECT_CODE, TASK_CODE, ReleaseState.OFFLINE); - Assert.assertEquals(Status.SUCCESS, offlineTaskResult.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, offlineTaskResult.get(Constants.STATUS)); // process definition online, resource exist Map onlineTaskResult = taskDefinitionService.releaseTaskDefinition(user, PROJECT_CODE, TASK_CODE, ReleaseState.ONLINE); - Assert.assertEquals(Status.SUCCESS, onlineTaskResult.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, onlineTaskResult.get(Constants.STATUS)); // release error code Map failResult = taskDefinitionService.releaseTaskDefinition(user, PROJECT_CODE, TASK_CODE, ReleaseState.getEnum(2)); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, failResult.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, failResult.get(Constants.STATUS)); } @Test diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskGroupQueueServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskGroupQueueServiceTest.java index cf5dd7cc31..26c901f588 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskGroupQueueServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskGroupQueueServiceTest.java @@ -33,13 +33,13 @@ import java.util.Date; import java.util.List; import java.util.Map; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,7 +49,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * project service test **/ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class TaskGroupQueueServiceTest { private static final Logger logger = LoggerFactory.getLogger(TaskGroupQueueServiceTest.class); @@ -97,9 +97,10 @@ public class TaskGroupQueueServiceTest { List records = new ArrayList<>(); records.add(getTaskGroupQueue()); page.setRecords(records); - Mockito.when(taskGroupQueueMapper.queryTaskGroupQueuePaging(Mockito.any(Page.class), Mockito.eq(10))).thenReturn(page); + Mockito.when(taskGroupQueueMapper.queryTaskGroupQueuePaging(Mockito.any(Page.class), Mockito.eq(10))) + .thenReturn(page); Map result = taskGroupQueueService.doQuery(user, 1, 1, 10); PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskGroupServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskGroupServiceTest.java index 027f9c1860..93fb961a9f 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskGroupServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskGroupServiceTest.java @@ -38,13 +38,15 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -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.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; @@ -54,7 +56,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * project service test **/ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class TaskGroupServiceTest { private static final Logger logger = LoggerFactory.getLogger(TaskGroupServiceTest.class); @@ -100,8 +103,8 @@ public class TaskGroupServiceTest { } private TaskGroup getTaskGroup() { - TaskGroup taskGroup = new TaskGroup(taskGroupName,0, taskGroupDesc, - 100, 1,1); + TaskGroup taskGroup = new TaskGroup(taskGroupName, 0, taskGroupDesc, + 100, 1, 1); return taskGroup; } @@ -115,18 +118,20 @@ public class TaskGroupServiceTest { public void forceStartTask() { User loginUser = getLoginUser(); Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TASK_GROUP, null, - loginUser.getId(), ApiFuncIdentificationConstant.TASK_GROUP_QUEUE_START, serviceLogger)).thenReturn(false); + loginUser.getId(), ApiFuncIdentificationConstant.TASK_GROUP_QUEUE_START, serviceLogger)) + .thenReturn(false); Map objectMap = taskGroupService.forceStartTask(loginUser, 1); - Assert.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION, objectMap.get(Constants.STATUS)); + Assertions.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION, objectMap.get(Constants.STATUS)); } @Test public void modifyPriority() { User loginUser = getLoginUser(); Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TASK_GROUP, null, - loginUser.getId(), ApiFuncIdentificationConstant.TASK_GROUP_QUEUE_PRIORITY, serviceLogger)).thenReturn(false); + loginUser.getId(), ApiFuncIdentificationConstant.TASK_GROUP_QUEUE_PRIORITY, serviceLogger)) + .thenReturn(false); Map objectMap = taskGroupService.modifyPriority(loginUser, 1, 1); - Assert.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION, objectMap.get(Constants.STATUS)); + Assertions.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION, objectMap.get(Constants.STATUS)); } @Test @@ -137,8 +142,8 @@ public class TaskGroupServiceTest { loginUser.getId(), ApiFuncIdentificationConstant.TASK_GROUP_CREATE, serviceLogger)).thenReturn(true); Mockito.when(taskGroupMapper.insert(taskGroup)).thenReturn(1); Mockito.when(taskGroupMapper.queryByName(loginUser.getId(), taskGroupName)).thenReturn(null); - Map result = taskGroupService.createTaskGroup(loginUser,0L, taskGroupName, taskGroupDesc, 100); - Assert.assertNotNull(result); + Map result = taskGroupService.createTaskGroup(loginUser, 0L, taskGroupName, taskGroupDesc, 100); + Assertions.assertNotNull(result); } @@ -148,7 +153,7 @@ public class TaskGroupServiceTest { TaskGroup taskGroup = getTaskGroup(); Mockito.when(taskGroupMapper.selectById(1)).thenReturn(taskGroup); Map result = taskGroupService.queryTaskGroupById(loginUser, 1); - Assert.assertNotNull(result.get(Constants.DATA_LIST)); + Assertions.assertNotNull(result.get(Constants.DATA_LIST)); } @Test @@ -162,12 +167,12 @@ public class TaskGroupServiceTest { Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.TASK_GROUP, null, 0, serviceLogger)).thenReturn(true); Mockito.when(taskGroupMapper.queryTaskGroupPaging(Mockito.any(Page.class), Mockito.anyList(), - Mockito.eq(null), Mockito.eq(0))).thenReturn(page); + Mockito.eq(null), Mockito.eq(0))).thenReturn(page); // query all - Map result = taskGroupService.queryAllTaskGroup(loginUser, null, null,1,10); + Map result = taskGroupService.queryAllTaskGroup(loginUser, null, null, 1, 10); PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); - Assert.assertNotNull(pageInfo.getTotalList()); + Assertions.assertNotNull(pageInfo.getTotalList()); } @Test @@ -186,7 +191,7 @@ public class TaskGroupServiceTest { Mockito.when(taskGroupMapper.updateById(taskGroup)).thenReturn(1); Map result = taskGroupService.updateTaskGroup(loginUser, 1, "newName", "desc", 100); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); taskGroup.setStatus(0); } @@ -198,22 +203,22 @@ public class TaskGroupServiceTest { TaskGroup taskGroup = getTaskGroup(); Mockito.when(taskGroupMapper.selectById(1)).thenReturn(taskGroup); - //close failed + // close failed Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TASK_GROUP, null, loginUser.getId(), ApiFuncIdentificationConstant.TASK_GROUP_CLOSE, serviceLogger)).thenReturn(true); Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.TASK_GROUP, null, 0, serviceLogger)).thenReturn(true); Map result = taskGroupService.closeTaskGroup(loginUser, 1); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); taskGroup.setStatus(0); Mockito.when(taskGroupMapper.selectById(1)).thenReturn(taskGroup); result = taskGroupService.closeTaskGroup(loginUser, 1); - Assert.assertEquals(Status.TASK_GROUP_STATUS_CLOSED, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.TASK_GROUP_STATUS_CLOSED, result.get(Constants.STATUS)); taskGroup.setStatus(1); Mockito.when(taskGroupMapper.selectById(1)).thenReturn(taskGroup); result = taskGroupService.startTaskGroup(loginUser, 1); - Assert.assertEquals(Status.TASK_GROUP_STATUS_OPENED, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.TASK_GROUP_STATUS_OPENED, result.get(Constants.STATUS)); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskInstanceServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskInstanceServiceTest.java index dd06ce66ef..8aab2d6ed5 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskInstanceServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TaskInstanceServiceTest.java @@ -19,13 +19,11 @@ package org.apache.dolphinscheduler.api.service; import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.FORCED_SUCCESS; import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.TASK_INSTANCE; - import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; import org.apache.dolphinscheduler.api.ApiApplicationServer; -import org.apache.dolphinscheduler.api.dto.gantt.Task; import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.api.service.impl.ProjectServiceImpl; import org.apache.dolphinscheduler.api.service.impl.TaskInstanceServiceImpl; @@ -53,13 +51,15 @@ import java.util.List; import java.util.Map; import java.util.Optional; -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.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.springframework.boot.test.context.SpringBootTest; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; @@ -67,7 +67,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * task instance service test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) @SpringBootTest(classes = ApiApplicationServer.class) public class TaskInstanceServiceTest { @@ -104,42 +105,42 @@ public class TaskInstanceServiceTest { when(projectMapper.queryByCode(projectCode)).thenReturn(project); when(projectService.checkProjectAndAuth(loginUser, project, projectCode, TASK_INSTANCE)).thenReturn(result); Result projectAuthFailRes = taskInstanceService.queryTaskListPaging(loginUser, - projectCode, - 0, - "", - "", - "", - "test_user", - "2019-02-26 19:48:00", - "2019-02-26 19:48:22", - "", - null, - "", - TaskExecuteType.BATCH, - 1, - 20); - Assert.assertEquals(Status.PROJECT_NOT_FOUND.getCode(), (int) projectAuthFailRes.getCode()); + projectCode, + 0, + "", + "", + "", + "test_user", + "2019-02-26 19:48:00", + "2019-02-26 19:48:22", + "", + null, + "", + TaskExecuteType.BATCH, + 1, + 20); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND.getCode(), (int) projectAuthFailRes.getCode()); // data parameter check putMsg(result, Status.SUCCESS, projectCode); when(projectMapper.queryByCode(projectCode)).thenReturn(project); when(projectService.checkProjectAndAuth(loginUser, project, projectCode, TASK_INSTANCE)).thenReturn(result); Result dataParameterRes = taskInstanceService.queryTaskListPaging(loginUser, - projectCode, - 1, - "", - "", - "", - "test_user", - "20200101 00:00:00", - "2020-01-02 00:00:00", - "", - TaskExecutionStatus.SUCCESS, - "192.168.xx.xx", - TaskExecuteType.BATCH, - 1, - 20); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), (int) dataParameterRes.getCode()); + projectCode, + 1, + "", + "", + "", + "test_user", + "20200101 00:00:00", + "2020-01-02 00:00:00", + "", + TaskExecutionStatus.SUCCESS, + "192.168.xx.xx", + TaskExecuteType.BATCH, + 1, + 20); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), (int) dataParameterRes.getCode()); // project putMsg(result, Status.SUCCESS, projectCode); @@ -155,48 +156,62 @@ public class TaskInstanceServiceTest { when(projectService.checkProjectAndAuth(loginUser, project, projectCode, TASK_INSTANCE)).thenReturn(result); when(usersService.queryUser(loginUser.getId())).thenReturn(loginUser); when(usersService.getUserIdByName(loginUser.getUserName())).thenReturn(loginUser.getId()); - when(taskInstanceMapper.queryTaskInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), eq(1), eq(""), eq(""), eq(""), - eq(0), Mockito.any(), eq("192.168.xx.xx"), eq(TaskExecuteType.BATCH), eq(start), eq(end))).thenReturn(pageReturn); + when(taskInstanceMapper.queryTaskInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), eq(1), + eq(""), eq(""), eq(""), + eq(0), Mockito.any(), eq("192.168.xx.xx"), eq(TaskExecuteType.BATCH), eq(start), eq(end))) + .thenReturn(pageReturn); when(usersService.queryUser(processInstance.getExecutorId())).thenReturn(loginUser); when(processService.findProcessInstanceDetailById(taskInstance.getProcessInstanceId())) .thenReturn(Optional.of(processInstance)); Result successRes = taskInstanceService.queryTaskListPaging(loginUser, projectCode, 1, "", "", "", - "test_user", "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) successRes.getCode()); - - //executor name empty - when(taskInstanceMapper.queryTaskInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), eq(1), eq(""), eq(""), eq(""), - eq(0), Mockito.any(), eq("192.168.xx.xx"), eq(TaskExecuteType.BATCH), eq(start), eq(end))).thenReturn(pageReturn); + "test_user", "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", TaskExecutionStatus.SUCCESS, + "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) successRes.getCode()); + + // executor name empty + when(taskInstanceMapper.queryTaskInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), eq(1), + eq(""), eq(""), eq(""), + eq(0), Mockito.any(), eq("192.168.xx.xx"), eq(TaskExecuteType.BATCH), eq(start), eq(end))) + .thenReturn(pageReturn); Result executorEmptyRes = taskInstanceService.queryTaskListPaging(loginUser, projectCode, 1, "", "", "", - "", "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) executorEmptyRes.getCode()); + "", "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", + TaskExecuteType.BATCH, 1, 20); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) executorEmptyRes.getCode()); // executor null when(usersService.queryUser(loginUser.getId())).thenReturn(null); when(usersService.getUserIdByName(loginUser.getUserName())).thenReturn(-1); Result executorNullRes = taskInstanceService.queryTaskListPaging(loginUser, projectCode, 1, "", "", "", - "test_user", "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) executorNullRes.getCode()); - - //start/end date null - when(taskInstanceMapper.queryTaskInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), eq(1), eq(""), eq(""), eq(""), - eq(0), Mockito.any(), eq("192.168.xx.xx"), eq(TaskExecuteType.BATCH), any(), any())).thenReturn(pageReturn); + "test_user", "2020-01-01 00:00:00", "2020-01-02 00:00:00", "", TaskExecutionStatus.SUCCESS, + "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) executorNullRes.getCode()); + + // start/end date null + when(taskInstanceMapper.queryTaskInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), eq(1), + eq(""), eq(""), eq(""), + eq(0), Mockito.any(), eq("192.168.xx.xx"), eq(TaskExecuteType.BATCH), any(), any())) + .thenReturn(pageReturn); Result executorNullDateRes = taskInstanceService.queryTaskListPaging(loginUser, projectCode, 1, "", "", "", - "", null, null, "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) executorNullDateRes.getCode()); - - //start date error format - when(taskInstanceMapper.queryTaskInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), eq(1), eq(""), eq(""), eq(""), - eq(0), Mockito.any(), eq("192.168.xx.xx"), eq(TaskExecuteType.BATCH), any(), any())).thenReturn(pageReturn); - - Result executorErrorStartDateRes = taskInstanceService.queryTaskListPaging(loginUser, projectCode, 1, "", "", "", - "", "error date", null, "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), (int) executorErrorStartDateRes.getCode()); + "", null, null, "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) executorNullDateRes.getCode()); + + // start date error format + when(taskInstanceMapper.queryTaskInstanceListPaging(Mockito.any(Page.class), eq(project.getCode()), eq(1), + eq(""), eq(""), eq(""), + eq(0), Mockito.any(), eq("192.168.xx.xx"), eq(TaskExecuteType.BATCH), any(), any())) + .thenReturn(pageReturn); + + Result executorErrorStartDateRes = taskInstanceService.queryTaskListPaging(loginUser, projectCode, 1, "", "", + "", + "", "error date", null, "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), + (int) executorErrorStartDateRes.getCode()); Result executorErrorEndDateRes = taskInstanceService.queryTaskListPaging(loginUser, projectCode, 1, "", "", "", - "", null, "error date", "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), (int) executorErrorEndDateRes.getCode()); + "", null, "error date", "", TaskExecutionStatus.SUCCESS, "192.168.xx.xx", TaskExecuteType.BATCH, 1, 20); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode(), + (int) executorErrorEndDateRes.getCode()); } /** @@ -285,7 +300,7 @@ public class TaskInstanceServiceTest { putMsg(mockFailure, Status.USER_NO_OPERATION_PROJECT_PERM, user.getUserName(), projectCode); when(projectService.checkProjectAndAuth(user, project, projectCode, FORCED_SUCCESS)).thenReturn(mockFailure); Map authFailRes = taskInstanceService.forceTaskSuccess(user, projectCode, taskId); - Assert.assertNotSame(Status.SUCCESS, authFailRes.get(Constants.STATUS)); + Assertions.assertNotSame(Status.SUCCESS, authFailRes.get(Constants.STATUS)); // test task not found when(projectService.checkProjectAndAuth(user, project, projectCode, FORCED_SUCCESS)).thenReturn(mockSuccess); @@ -294,7 +309,7 @@ public class TaskInstanceServiceTest { taskDefinition.setProjectCode(projectCode); when(taskDefinitionMapper.queryByCode(task.getTaskCode())).thenReturn(taskDefinition); Map taskNotFoundRes = taskInstanceService.forceTaskSuccess(user, projectCode, taskId); - Assert.assertEquals(Status.TASK_INSTANCE_NOT_FOUND, taskNotFoundRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.TASK_INSTANCE_NOT_FOUND, taskNotFoundRes.get(Constants.STATUS)); // test task instance state error task.setState(TaskExecutionStatus.SUCCESS); @@ -304,7 +319,7 @@ public class TaskInstanceServiceTest { when(projectMapper.queryByCode(projectCode)).thenReturn(project); when(projectService.checkProjectAndAuth(user, project, projectCode, FORCED_SUCCESS)).thenReturn(result); Map taskStateErrorRes = taskInstanceService.forceTaskSuccess(user, projectCode, taskId); - Assert.assertEquals(Status.TASK_INSTANCE_STATE_OPERATION_ERROR, taskStateErrorRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.TASK_INSTANCE_STATE_OPERATION_ERROR, taskStateErrorRes.get(Constants.STATUS)); // test error task.setState(TaskExecutionStatus.FAILURE); @@ -313,7 +328,7 @@ public class TaskInstanceServiceTest { when(projectMapper.queryByCode(projectCode)).thenReturn(project); when(projectService.checkProjectAndAuth(user, project, projectCode, FORCED_SUCCESS)).thenReturn(result); Map errorRes = taskInstanceService.forceTaskSuccess(user, projectCode, taskId); - Assert.assertEquals(Status.FORCE_TASK_SUCCESS_ERROR, errorRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.FORCE_TASK_SUCCESS_ERROR, errorRes.get(Constants.STATUS)); // test success task.setState(TaskExecutionStatus.FAILURE); @@ -322,6 +337,6 @@ public class TaskInstanceServiceTest { when(projectMapper.queryByCode(projectCode)).thenReturn(project); when(projectService.checkProjectAndAuth(user, project, projectCode, FORCED_SUCCESS)).thenReturn(result); Map successRes = taskInstanceService.forceTaskSuccess(user, projectCode, taskId); - Assert.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, successRes.get(Constants.STATUS)); } -} \ No newline at end of file +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java index 30142be13d..8b38bd101c 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java @@ -50,14 +50,15 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.Assert; -import org.junit.Test; import org.junit.jupiter.api.Assertions; -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.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; @@ -67,7 +68,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * tenant service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class TenantServiceTest { private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); @@ -122,22 +124,22 @@ public class TenantServiceTest { "this_is_a_very_long_string_this_is_a_very_long_string_this_is_a_very_long_string_this_is_a_very_long_string"; exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.createTenant(loginUser, longStr, 1, tenantDesc)); - Assert.assertEquals(Status.TENANT_FULL_NAME_TOO_LONG_ERROR.getMsg(), exception.getMessage()); + Assertions.assertEquals(Status.TENANT_FULL_NAME_TOO_LONG_ERROR.getMsg(), exception.getMessage()); // check tenant code invalid exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.createTenant(getLoginUser(), "%!1111", 1, tenantDesc)); - Assert.assertEquals(Status.CHECK_OS_TENANT_CODE_ERROR.getMsg(), exception.getMessage()); + Assertions.assertEquals(Status.CHECK_OS_TENANT_CODE_ERROR.getMsg(), exception.getMessage()); // check exist exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.createTenant(loginUser, tenantCode, 1, tenantDesc)); formatter = MessageFormat.format(Status.OS_TENANT_CODE_EXIST.getMsg(), tenantCode); - Assert.assertEquals(formatter, exception.getMessage()); + Assertions.assertEquals(formatter, exception.getMessage()); // success result = tenantService.createTenant(loginUser, "test", 1, tenantDesc); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -152,7 +154,7 @@ public class TenantServiceTest { // success Result result = tenantService.verifyTenantCode("s00000000000l887888885554444sfjdskfjslakslkdf"); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @Test @@ -169,7 +171,7 @@ public class TenantServiceTest { .thenReturn(page); Result result = tenantService.queryTenantList(getLoginUser(), tenantDesc, 1, 10); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @@ -189,11 +191,11 @@ public class TenantServiceTest { // success Map result = tenantService.updateTenant(getLoginUser(), 1, tenantCode, 1, tenantDesc); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); // success update with same tenant code result = tenantService.updateTenant(getLoginUser(), 1, tenantCode, 1, tenantDesc); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -237,7 +239,7 @@ public class TenantServiceTest { Mockito.when(tenantMapper.queryById(4)).thenReturn(getTenant(4)); Mockito.when(tenantMapper.deleteById(4)).thenReturn(1); Map result = tenantService.deleteTenantById(getLoginUser(), 4); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -251,7 +253,7 @@ public class TenantServiceTest { // success Result result = tenantService.verifyTenantCode("s00000000000l887888885554444sfjdskfjslakslkdf"); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @Test @@ -262,13 +264,13 @@ public class TenantServiceTest { Mockito.when(tenantMapper.existTenant(tenantCode)).thenReturn(true); Mockito.when(tenantMapper.queryByTenantCode(tenantCode)).thenReturn(getTenant()); tenant = tenantService.createTenantIfNotExists(tenantCode, tenantDesc, queue, queueName); - Assert.assertEquals(getTenant(), tenant); + Assertions.assertEquals(getTenant(), tenant); // Tenant not exists Mockito.when(tenantMapper.existTenant(tenantCode)).thenReturn(false); Mockito.when(queueService.createQueueIfNotExists(queue, queueName)).thenReturn(getQueue()); tenant = tenantService.createTenantIfNotExists(tenantCode, tenantDesc, queue, queueName); - Assert.assertEquals(new Tenant(tenantCode, tenantDesc, getQueue().getId()), tenant); + Assertions.assertEquals(new Tenant(tenantCode, tenantDesc, getQueue().getId()), tenant); } /** diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UdfFuncServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UdfFuncServiceTest.java index 31145857d0..29ce54afad 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UdfFuncServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UdfFuncServiceTest.java @@ -44,16 +44,18 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -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.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; 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; @@ -63,7 +65,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * udf func service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class UdfFuncServiceTest { private static final Logger logger = LoggerFactory.getLogger(UdfFuncServiceTest.class); @@ -82,7 +85,7 @@ public class UdfFuncServiceTest { @Mock private UDFUserMapper udfUserMapper; - @Before + @BeforeEach public void setUp() { mockedStaticPropertyUtils = Mockito.mockStatic(PropertyUtils.class); } @@ -107,21 +110,21 @@ public class UdfFuncServiceTest { "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, Integer.MAX_VALUE); logger.info(result.toString()); - Assert.assertEquals(Status.HDFS_NOT_STARTUP.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.HDFS_NOT_STARTUP.getMsg(), result.getMsg()); // resource not exist Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); result = udfFuncService.createUdfFunction(getLoginUser(), "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, Integer.MAX_VALUE); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // success Mockito.when(resourceMapper.selectById(1)).thenReturn(getResource()); result = udfFuncService.createUdfFunction(getLoginUser(), "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 1); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @Test @@ -135,7 +138,7 @@ public class UdfFuncServiceTest { // resource not exist Result result = udfFuncService.queryUdfFuncDetail(getLoginUser(), 2); logger.info(result.toString()); - Assert.assertTrue(Status.RESOURCE_NOT_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.RESOURCE_NOT_EXIST.getCode() == result.getCode()); // success Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); @@ -143,7 +146,7 @@ public class UdfFuncServiceTest { serviceLogger)).thenReturn(true); result = udfFuncService.queryUdfFuncDetail(getLoginUser(), 1); logger.info(result.toString()); - Assert.assertTrue(Status.SUCCESS.getCode() == result.getCode()); + Assertions.assertTrue(Status.SUCCESS.getCode() == result.getCode()); } @Test @@ -162,7 +165,7 @@ public class UdfFuncServiceTest { "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 1); logger.info(result.toString()); - Assert.assertTrue(Status.UDF_FUNCTION_NOT_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.UDF_FUNCTION_NOT_EXIST.getCode() == result.getCode()); // HDFS_NOT_STARTUP Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{1}, 0, @@ -171,7 +174,7 @@ public class UdfFuncServiceTest { "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 1); logger.info(result.toString()); - Assert.assertTrue(Status.HDFS_NOT_STARTUP.getCode() == result.getCode()); + Assertions.assertTrue(Status.HDFS_NOT_STARTUP.getCode() == result.getCode()); // RESOURCE_NOT_EXIST Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, @@ -184,7 +187,7 @@ public class UdfFuncServiceTest { "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 12); logger.info(result.toString()); - Assert.assertTrue(Status.RESOURCE_NOT_EXIST.getCode() == result.getCode()); + Assertions.assertTrue(Status.RESOURCE_NOT_EXIST.getCode() == result.getCode()); // success Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, @@ -193,7 +196,7 @@ public class UdfFuncServiceTest { "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 1); logger.info(result.toString()); - Assert.assertTrue(Status.SUCCESS.getCode() == result.getCode()); + Assertions.assertTrue(Status.SUCCESS.getCode() == result.getCode()); } @@ -216,7 +219,7 @@ public class UdfFuncServiceTest { Result result = udfFuncService.queryUdfFuncListPaging(getLoginUser(), "test", 1, 10); logger.info(result.toString()); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); + Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @Test @@ -237,9 +240,9 @@ public class UdfFuncServiceTest { .thenReturn(getList()); Result result = udfFuncService.queryUdfFuncList(user, UdfType.HIVE.ordinal()); logger.info(result.toString()); - Assert.assertTrue(Status.SUCCESS.getCode() == result.getCode()); + Assertions.assertTrue(Status.SUCCESS.getCode() == result.getCode()); List udfFuncList = (List) result.getData(); - Assert.assertTrue(CollectionUtils.isNotEmpty(udfFuncList)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(udfFuncList)); } @Test @@ -253,7 +256,7 @@ public class UdfFuncServiceTest { Mockito.when(udfUserMapper.deleteByUdfFuncId(Mockito.anyInt())).thenReturn(1); Result result = udfFuncService.delete(getLoginUser(), 122); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @Test @@ -268,11 +271,11 @@ public class UdfFuncServiceTest { Mockito.when(udfFuncMapper.queryUdfByIdStr(null, "UdfFuncServiceTest")).thenReturn(getList()); Result result = udfFuncService.verifyUdfFuncByName(getLoginUser(), "test"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); // exist result = udfFuncService.verifyUdfFuncByName(getLoginUser(), "UdfFuncServiceTest"); logger.info(result.toString()); - Assert.assertEquals(Status.UDF_FUNCTION_EXISTS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.UDF_FUNCTION_EXISTS.getMsg(), result.getMsg()); } private Set getSetIds() { @@ -326,7 +329,7 @@ public class UdfFuncServiceTest { return udfFunc; } - @After + @AfterEach public void after() { mockedStaticPropertyUtils.close(); } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UiPluginServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UiPluginServiceTest.java index e1f44583f0..3002d9a20f 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UiPluginServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UiPluginServiceTest.java @@ -26,19 +26,19 @@ import org.apache.dolphinscheduler.dao.mapper.PluginDefineMapper; import java.util.Collections; import java.util.Map; -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; /** * ui plugin service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class UiPluginServiceTest { @InjectMocks @@ -49,7 +49,7 @@ public class UiPluginServiceTest { private PluginDefine pluginDefine; - @Before + @BeforeEach public void before() { String pluginParams = "[{\"field\":\"receivers\",\"props\":null,\"type\"}]"; pluginDefine = new PluginDefine("email-alert", "alert", pluginParams); @@ -58,29 +58,30 @@ public class UiPluginServiceTest { @Test public void testQueryPlugins1() { Map result = uiPluginService.queryUiPluginsByType(PluginType.REGISTER); - Assert.assertEquals(Status.PLUGIN_NOT_A_UI_COMPONENT, result.get("status")); + Assertions.assertEquals(Status.PLUGIN_NOT_A_UI_COMPONENT, result.get("status")); } @Test public void testQueryPlugins2() { Map result = uiPluginService.queryUiPluginsByType(PluginType.ALERT); Mockito.when(pluginDefineMapper.queryByPluginType(PluginType.ALERT.getDesc())).thenReturn(null); - Assert.assertEquals(Status.QUERY_PLUGINS_RESULT_IS_NULL, result.get("status")); + Assertions.assertEquals(Status.QUERY_PLUGINS_RESULT_IS_NULL, result.get("status")); - Mockito.when(pluginDefineMapper.queryByPluginType(PluginType.ALERT.getDesc())).thenReturn(Collections.singletonList(pluginDefine)); + Mockito.when(pluginDefineMapper.queryByPluginType(PluginType.ALERT.getDesc())) + .thenReturn(Collections.singletonList(pluginDefine)); result = uiPluginService.queryUiPluginsByType(PluginType.ALERT); - Assert.assertEquals(Status.SUCCESS, result.get("status")); + Assertions.assertEquals(Status.SUCCESS, result.get("status")); } @Test public void testQueryPluginDetailById() { Mockito.when(pluginDefineMapper.queryDetailById(1)).thenReturn(null); Map result = uiPluginService.queryUiPluginDetailById(1); - Assert.assertEquals(Status.QUERY_PLUGIN_DETAIL_RESULT_IS_NULL, result.get("status")); + Assertions.assertEquals(Status.QUERY_PLUGIN_DETAIL_RESULT_IS_NULL, result.get("status")); Mockito.when(pluginDefineMapper.queryDetailById(1)).thenReturn(pluginDefine); result = uiPluginService.queryUiPluginDetailById(1); - Assert.assertEquals(Status.SUCCESS, result.get("status")); + Assertions.assertEquals(Status.SUCCESS, result.get("status")); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java index 73002855a0..9c02aa970f 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java @@ -58,15 +58,17 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -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.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; @@ -77,7 +79,8 @@ import com.google.common.collect.Lists; /** * users service test */ -@RunWith(MockitoJUnitRunner.Silent.class) +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class UsersServiceTest { private static final Logger logger = LoggerFactory.getLogger(UsersServiceTest.class); @@ -128,12 +131,12 @@ public class UsersServiceTest { private static final Logger serviceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); - @Before + @BeforeEach public void before() { Mockito.when(resourcePermissionCheckService.functionDisabled()).thenReturn(false); } - @After + @AfterEach public void after() { } @@ -143,7 +146,7 @@ public class UsersServiceTest { String userName = "user1"; String email = "user1@ldap.com"; User user = usersService.createUser(UserType.ADMIN_USER, userName, email); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); } @Test @@ -161,43 +164,43 @@ public class UsersServiceTest { Map result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); userName = "userTest0001"; userPassword = "userTest000111111111111111"; // password error result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); userPassword = "userTest0001"; email = "1q.com"; // email error result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); email = "122222@qq.com"; phone = "2233"; // phone error result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); phone = "13456432345"; // tenantId not exists result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName, state); logger.info(result.toString()); - Assert.assertEquals(Status.TENANT_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.TENANT_NOT_EXIST, result.get(Constants.STATUS)); // success Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); result = usersService.createUser(user, userName, userPassword, email, 1, phone, queueName, state); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } catch (Exception e) { logger.error(Status.CREATE_USER_ERROR.getMsg(), e); - Assert.assertTrue(false); + Assertions.assertTrue(false); } } @@ -209,20 +212,20 @@ public class UsersServiceTest { .thenReturn(getGeneralUser()); User queryUser = usersService.queryUser(userName, userPassword); logger.info(queryUser.toString()); - Assert.assertTrue(queryUser != null); + Assertions.assertTrue(queryUser != null); } @Test public void testSelectByIds() { List ids = new ArrayList<>(); List users = usersService.queryUser(ids); - Assert.assertTrue(users.isEmpty()); + Assertions.assertTrue(users.isEmpty()); ids.add(1); List userList = new ArrayList<>(); userList.add(new User()); when(userMapper.selectByIds(ids)).thenReturn(userList); List userList1 = usersService.queryUser(ids); - Assert.assertFalse(userList1.isEmpty()); + Assertions.assertFalse(userList1.isEmpty()); } @Test @@ -234,17 +237,17 @@ public class UsersServiceTest { // user name null int userId = usersService.getUserIdByName(""); - Assert.assertEquals(0, userId); + Assertions.assertEquals(0, userId); // user not exist when(usersService.queryUser(user.getUserName())).thenReturn(null); int userNotExistId = usersService.getUserIdByName(user.getUserName()); - Assert.assertEquals(-1, userNotExistId); + Assertions.assertEquals(-1, userNotExistId); // user exist when(usersService.queryUser(user.getUserName())).thenReturn(user); Integer userExistId = usersService.getUserIdByName(user.getUserName()); - Assert.assertEquals(user.getId(), userExistId); + Assertions.assertEquals(user.getId(), userExistId); } @Test @@ -259,7 +262,7 @@ public class UsersServiceTest { serviceLogger)).thenReturn(false); Map result = usersService.queryUserList(user); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // success Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.ACCESS_TOKEN, null, 1, @@ -270,7 +273,7 @@ public class UsersServiceTest { when(userMapper.queryEnabledUsers()).thenReturn(getUserList()); result = usersService.queryUserList(user); List userList = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(userList.size() > 0); + Assertions.assertTrue(userList.size() > 0); } @Test @@ -283,14 +286,14 @@ public class UsersServiceTest { // no operate Result result = usersService.queryUserList(user, "userTest", 1, 10); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM.getCode(), (int) result.getCode()); // success user.setUserType(UserType.ADMIN_USER); result = usersService.queryUserList(user, "userTest", 1, 10); - Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); + Assertions.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); PageInfo pageInfo = (PageInfo) result.getData(); - Assert.assertTrue(pageInfo.getTotalList().size() > 0); + Assertions.assertTrue(pageInfo.getTotalList().size() > 0); } @Test @@ -301,7 +304,7 @@ public class UsersServiceTest { // user not exist Map result = usersService.updateUser(getLoginUser(), 0, userName, userPassword, "3443@qq.com", 1, "13457864543", "queue", 1, "Asia/Shanghai"); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); logger.info(result.toString()); // success @@ -310,10 +313,10 @@ public class UsersServiceTest { result = usersService.updateUser(getLoginUser(), 1, userName, userPassword, "32222s@qq.com", 1, "13457864543", "queue", 1, "Asia/Shanghai"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } catch (Exception e) { logger.error("update user error", e); - Assert.fail(); + Assertions.fail(); } } @@ -324,30 +327,30 @@ public class UsersServiceTest { when(userMapper.queryTenantCodeByUserId(1)).thenReturn(getUser()); when(userMapper.selectById(1)).thenReturn(getUser()); when(userMapper.deleteById(1)).thenReturn(1); - //no operate + // no operate Map result = usersService.deleteUserById(loginUser, 3); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // user not exist loginUser.setUserType(UserType.ADMIN_USER); result = usersService.deleteUserById(loginUser, 3); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // user is project owner Mockito.when(projectMapper.queryProjectCreatedByUser(1)).thenReturn(Lists.newArrayList(new Project())); result = usersService.deleteUserById(loginUser, 1); - Assert.assertEquals(Status.TRANSFORM_PROJECT_OWNERSHIP, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.TRANSFORM_PROJECT_OWNERSHIP, result.get(Constants.STATUS)); // success Mockito.when(projectMapper.queryProjectCreatedByUser(1)).thenReturn(null); result = usersService.deleteUserById(loginUser, 1); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } catch (Exception e) { logger.error("delete user error", e); - Assert.assertTrue(false); + Assertions.assertTrue(false); } } @@ -364,13 +367,13 @@ public class UsersServiceTest { when(userMapper.selectById(userId)).thenReturn(null); Map result = usersService.grantProject(loginUser, userId, projectIds); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // SUCCESS when(userMapper.selectById(userId)).thenReturn(getUser()); result = usersService.grantProject(loginUser, userId, projectIds); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -387,33 +390,33 @@ public class UsersServiceTest { User loginUser = new User(); Map result = this.usersService.grantProjectByCode(loginUser, 999, projectCode); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // ERROR: PROJECT_NOT_FOUNT result = this.usersService.grantProjectByCode(loginUser, authorizer, 999); logger.info(result.toString()); - Assert.assertEquals(Status.PROJECT_NOT_FOUND, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.PROJECT_NOT_FOUND, result.get(Constants.STATUS)); // ERROR: USER_NO_OPERATION_PERM loginUser.setId(999); loginUser.setUserType(UserType.GENERAL_USER); result = this.usersService.grantProjectByCode(loginUser, authorizer, projectCode); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // SUCCESS: USER IS PROJECT OWNER loginUser.setId(projectCreator); loginUser.setUserType(UserType.GENERAL_USER); result = this.usersService.grantProjectByCode(loginUser, authorizer, projectCode); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); // SUCCESS: USER IS ADMINISTRATOR loginUser.setId(999); loginUser.setUserType(UserType.ADMIN_USER); result = this.usersService.grantProjectByCode(loginUser, authorizer, projectCode); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -427,13 +430,13 @@ public class UsersServiceTest { loginUser.setId(0); Map result = this.usersService.revokeProject(loginUser, 1, projectCode); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // user not exist loginUser.setUserType(UserType.ADMIN_USER); result = this.usersService.revokeProject(loginUser, 2, projectCode); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // success Project project = new Project(); @@ -441,7 +444,7 @@ public class UsersServiceTest { Mockito.when(this.projectMapper.queryByCode(Mockito.anyLong())).thenReturn(project); result = this.usersService.revokeProject(loginUser, 1, projectCode); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -454,13 +457,13 @@ public class UsersServiceTest { loginUser.setUserType(UserType.ADMIN_USER); Map result = usersService.grantResources(loginUser, 2, resourceIds); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // success when(resourceMapper.selectById(Mockito.anyInt())).thenReturn(getResource()); when(resourceUserMapper.deleteResourceUser(1, 0)).thenReturn(1); result = usersService.grantResources(loginUser, 1, resourceIds); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @@ -474,12 +477,12 @@ public class UsersServiceTest { loginUser.setUserType(UserType.ADMIN_USER); Map result = usersService.grantUDFFunction(loginUser, 2, udfIds); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // success when(udfUserMapper.deleteByUserId(1)).thenReturn(1); result = usersService.grantUDFFunction(loginUser, 1, udfIds); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -492,12 +495,12 @@ public class UsersServiceTest { loginUser.setUserType(UserType.ADMIN_USER); Map result = usersService.grantNamespaces(loginUser, 2, namespaceIds); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // success when(k8sNamespaceUserMapper.deleteNamespaceRelation(0, 1)).thenReturn(1); result = usersService.grantNamespaces(loginUser, 1, namespaceIds); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -512,21 +515,21 @@ public class UsersServiceTest { when(userMapper.selectById(userId)).thenReturn(null); Map result = usersService.grantDataSource(loginUser, userId, datasourceIds); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // test admin user when(userMapper.selectById(userId)).thenReturn(getUser()); when(datasourceUserMapper.deleteByUserId(Mockito.anyInt())).thenReturn(1); result = usersService.grantDataSource(loginUser, userId, datasourceIds); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); // test non-admin user loginUser.setId(2); loginUser.setUserType(UserType.GENERAL_USER); result = usersService.grantDataSource(loginUser, userId, datasourceIds); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @@ -545,10 +548,10 @@ public class UsersServiceTest { // get admin user Map result = usersService.getUserInfo(loginUser); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); User tempUser = (User) result.get(Constants.DATA_LIST); // check userName - Assert.assertEquals("admin", tempUser.getUserName()); + Assertions.assertEquals("admin", tempUser.getUserName()); // get general user loginUser.setUserType(null); @@ -557,10 +560,10 @@ public class UsersServiceTest { when(alertGroupMapper.queryByUserId(1)).thenReturn(getAlertGroups()); result = usersService.getUserInfo(loginUser); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); tempUser = (User) result.get(Constants.DATA_LIST); // check userName - Assert.assertEquals("userTest0001", tempUser.getUserName()); + Assertions.assertEquals("userTest0001", tempUser.getUserName()); } @Test @@ -569,15 +572,15 @@ public class UsersServiceTest { // no operate Map result = usersService.queryAllGeneralUsers(loginUser); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // success loginUser.setUserType(UserType.ADMIN_USER); when(userMapper.queryAllGeneralUser()).thenReturn(getUserList()); result = usersService.queryAllGeneralUsers(loginUser); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List userList = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(CollectionUtils.isNotEmpty(userList)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(userList)); } @Test @@ -585,12 +588,12 @@ public class UsersServiceTest { // not exist user Result result = usersService.verifyUserName("admin89899"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); // exist user when(userMapper.queryByUserNameAccurately("userTest0001")).thenReturn(getUser()); result = usersService.verifyUserName("userTest0001"); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NAME_EXIST.getMsg(), result.getMsg()); + Assertions.assertEquals(Status.USER_NAME_EXIST.getMsg(), result.getMsg()); } @Test @@ -602,11 +605,11 @@ public class UsersServiceTest { Map result = usersService.unauthorizedUser(loginUser, 2); logger.info(result.toString()); loginUser.setUserType(UserType.ADMIN_USER); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // success result = usersService.unauthorizedUser(loginUser, 2); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test @@ -616,14 +619,14 @@ public class UsersServiceTest { // no operate Map result = usersService.authorizedUser(loginUser, 2); logger.info(result.toString()); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // success loginUser.setUserType(UserType.ADMIN_USER); result = usersService.authorizedUser(loginUser, 2); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); List userList = (List) result.get(Constants.DATA_LIST); logger.info(result.toString()); - Assert.assertTrue(CollectionUtils.isNotEmpty(userList)); + Assertions.assertTrue(CollectionUtils.isNotEmpty(userList)); } @Test @@ -635,33 +638,33 @@ public class UsersServiceTest { try { // userName error Map result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); userName = "userTest0002"; userPassword = "userTest000111111111111111"; // password error result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); userPassword = "userTest0002"; email = "1q.com"; // email error result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); // repeatPassword error email = "7400@qq.com"; repeatPassword = "userPassword"; result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); // success repeatPassword = "userTest0002"; result = usersService.registerUser(userName, userPassword, repeatPassword, email); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } catch (Exception e) { - Assert.assertTrue(false); + Assertions.assertTrue(false); } } @@ -673,30 +676,30 @@ public class UsersServiceTest { try { // not admin Map result = usersService.activateUser(user, userName); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // userName error user.setUserType(UserType.ADMIN_USER); result = usersService.activateUser(user, userName); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); // user not exist userName = "userTest10013"; result = usersService.activateUser(user, userName); - Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); // user state error userName = "userTest0001"; when(userMapper.queryByUserNameAccurately(userName)).thenReturn(getUser()); result = usersService.activateUser(user, userName); - Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); // success when(userMapper.queryByUserNameAccurately(userName)).thenReturn(getDisabledUser()); result = usersService.activateUser(user, userName); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } catch (Exception e) { - Assert.assertTrue(false); + Assertions.assertTrue(false); } } @@ -713,7 +716,7 @@ public class UsersServiceTest { try { // not admin Map result = usersService.batchActivateUser(user, userNames); - Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + Assertions.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); // batch activate user names user.setUserType(UserType.ADMIN_USER); @@ -727,11 +730,11 @@ public class UsersServiceTest { Map failedData = (Map) responseData.get("failed"); int totalFailed = (Integer) failedData.get("sum"); - Assert.assertEquals(1, totalSuccess); - Assert.assertEquals(3, totalFailed); - Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + Assertions.assertEquals(1, totalSuccess); + Assertions.assertEquals(3, totalFailed); + Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } catch (Exception e) { - Assert.assertTrue(false); + Assertions.assertTrue(false); } } @@ -752,13 +755,13 @@ public class UsersServiceTest { Mockito.when(userMapper.queryByUserNameAccurately(userName)).thenReturn(getUser()); Mockito.when(tenantMapper.queryByTenantCode(tenantCode)).thenReturn(getTenant()); user = usersService.createUserIfNotExists(userName, userPassword, email, phone, tenantCode, queueName, stat); - Assert.assertEquals(getUser(), user); + Assertions.assertEquals(getUser(), user); // User not exists Mockito.when(userMapper.existUser(userName)).thenReturn(false); Mockito.when(tenantMapper.queryByTenantCode(tenantCode)).thenReturn(getTenant()); user = usersService.createUserIfNotExists(userName, userPassword, email, phone, tenantCode, queueName, stat); - Assert.assertNotNull(user); + Assertions.assertNotNull(user); } /** diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkFlowLineageServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkFlowLineageServiceTest.java index fc7eee3a5f..707a566bf6 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkFlowLineageServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkFlowLineageServiceTest.java @@ -35,18 +35,18 @@ import java.util.List; import java.util.Map; import java.util.Set; -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.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; /** * work flow lineage service test */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class WorkFlowLineageServiceTest { @InjectMocks @@ -81,10 +81,11 @@ public class WorkFlowLineageServiceTest { Project project = getProject("test"); String name = "test"; when(projectMapper.queryByCode(1L)).thenReturn(project); - when(workFlowLineageMapper.queryWorkFlowLineageByName(Mockito.anyLong(), Mockito.any())).thenReturn(getWorkFlowLineages()); + when(workFlowLineageMapper.queryWorkFlowLineageByName(Mockito.anyLong(), Mockito.any())) + .thenReturn(getWorkFlowLineages()); Map result = workFlowLineageService.queryWorkFlowLineageByName(1L, name); List workFlowLineageList = (List) result.get(Constants.DATA_LIST); - Assert.assertTrue(workFlowLineageList.size() > 0); + Assertions.assertTrue(workFlowLineageList.size() > 0); } @Test @@ -114,10 +115,12 @@ public class WorkFlowLineageServiceTest { Map result = workFlowLineageService.queryWorkFlowLineage(1L); Map workFlowLists = (Map) result.get(Constants.DATA_LIST); - Collection workFlowLineageList = (Collection) workFlowLists.get(Constants.WORKFLOW_LIST); - Set workFlowRelations = (Set) workFlowLists.get(Constants.WORKFLOW_RELATION_LIST); - Assert.assertTrue(workFlowLineageList.size() > 0); - Assert.assertTrue(workFlowRelations.size() > 0); + Collection workFlowLineageList = + (Collection) workFlowLists.get(Constants.WORKFLOW_LIST); + Set workFlowRelations = + (Set) workFlowLists.get(Constants.WORKFLOW_RELATION_LIST); + Assertions.assertTrue(workFlowLineageList.size() > 0); + Assertions.assertTrue(workFlowRelations.size() > 0); } private List getWorkFlowLineages() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java index f25c82f19a..5929725cfd 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java @@ -34,19 +34,16 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -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.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ActiveProfiles(value = {ProfileType.H2}) -@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ApiApplicationServer.class) public class WorkerGroupServiceTest { @@ -66,8 +63,8 @@ public class WorkerGroupServiceTest { private User loginUSer; - @Before - public void init(){ + @BeforeEach + public void init() { loginUSer = new User(); loginUSer.setUserType(UserType.ADMIN_USER); } @@ -76,7 +73,7 @@ public class WorkerGroupServiceTest { public void testQueryAllGroup() { Map result = workerGroupService.queryAllGroup(loginUSer); List workerGroups = (List) result.get(Constants.DATA_LIST); - Assert.assertEquals(workerGroups.size(), 1); + Assertions.assertEquals(workerGroups.size(), 1); } /** @@ -91,15 +88,17 @@ public class WorkerGroupServiceTest { Mockito.when(workerGroupMapper.selectById(2)).thenReturn(wg2); Mockito.when(processInstanceMapper.queryByWorkerGroupNameAndStatus(wg2.getName(), org.apache.dolphinscheduler.service.utils.Constants.NOT_TERMINATED_STATES)).thenReturn(getProcessInstanceList()); Map result = workerGroupService.deleteWorkerGroupById(user, 1); - Assert.assertEquals(Status.DELETE_WORKER_GROUP_NOT_EXIST.getCode(), ((Status) result.get(Constants.STATUS)).getCode()); + Assertions.assertEquals(Status.DELETE_WORKER_GROUP_NOT_EXIST.getCode(), + ((Status) result.get(Constants.STATUS)).getCode()); result = workerGroupService.deleteWorkerGroupById(user, 2); - Assert.assertEquals(Status.DELETE_WORKER_GROUP_BY_ID_FAIL.getCode(), ((Status) result.get(Constants.STATUS)).getCode()); + Assertions.assertEquals(Status.DELETE_WORKER_GROUP_BY_ID_FAIL.getCode(), + ((Status) result.get(Constants.STATUS)).getCode()); // correct WorkerGroup wg3 = getWorkerGroup(3); Mockito.when(workerGroupMapper.selectById(3)).thenReturn(wg3); Mockito.when(processInstanceMapper.queryByWorkerGroupNameAndStatus(wg3.getName(), org.apache.dolphinscheduler.service.utils.Constants.NOT_TERMINATED_STATES)).thenReturn(new ArrayList<>()); result = workerGroupService.deleteWorkerGroupById(user, 3); - Assert.assertEquals(Status.SUCCESS.getMsg(), result.get(Constants.MSG)); + Assertions.assertEquals(Status.SUCCESS.getMsg(), result.get(Constants.MSG)); } /** @@ -115,8 +114,8 @@ public class WorkerGroupServiceTest { public void testQueryAllGroupWithDefault() { Map result = workerGroupService.queryAllGroup(loginUSer); List workerGroups = (List) result.get(Constants.DATA_LIST); - Assert.assertEquals(1, workerGroups.size()); - Assert.assertEquals("default", workerGroups.toArray()[0]); + Assertions.assertEquals(1, workerGroups.size()); + Assertions.assertEquals("default", workerGroups.toArray()[0]); } /** diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/CheckUtilsTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/CheckUtilsTest.java index a3a414dab9..e394d24764 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/CheckUtilsTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/CheckUtilsTest.java @@ -17,16 +17,13 @@ package org.apache.dolphinscheduler.api.utils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - import org.apache.dolphinscheduler.api.enums.Status; import org.apache.dolphinscheduler.common.Constants; import java.util.Map; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class CheckUtilsTest { @@ -35,9 +32,9 @@ public class CheckUtilsTest { */ @Test public void testCheckUserName() { - assertTrue(CheckUtils.checkUserName("test01")); - assertFalse(CheckUtils.checkUserName(null)); - assertFalse(CheckUtils.checkUserName("test01@abc")); + Assertions.assertTrue(CheckUtils.checkUserName("test01")); + Assertions.assertFalse(CheckUtils.checkUserName(null)); + Assertions.assertFalse(CheckUtils.checkUserName("test01@abc")); } /** @@ -45,10 +42,10 @@ public class CheckUtilsTest { */ @Test public void testCheckEmail() { - assertTrue(CheckUtils.checkEmail("test01@gmail.com")); - assertFalse(CheckUtils.checkEmail("test01@gmail")); - assertFalse(CheckUtils.checkEmail("test01@gmail.")); - assertTrue(CheckUtils.checkEmail("test01@gmail.edu.cn")); + Assertions.assertTrue(CheckUtils.checkEmail("test01@gmail.com")); + Assertions.assertFalse(CheckUtils.checkEmail("test01@gmail")); + Assertions.assertFalse(CheckUtils.checkEmail("test01@gmail.")); + Assertions.assertTrue(CheckUtils.checkEmail("test01@gmail.edu.cn")); } /** @@ -58,16 +55,16 @@ public class CheckUtilsTest { public void testCheckDesc() { Map objectMap = CheckUtils.checkDesc("I am desc"); Status status = (Status) objectMap.get(Constants.STATUS); - assertEquals(status.getCode(), Status.SUCCESS.getCode()); + Assertions.assertEquals(status.getCode(), Status.SUCCESS.getCode()); } @Test public void testCheckOtherParams() { - assertFalse(CheckUtils.checkOtherParams(null)); - assertFalse(CheckUtils.checkOtherParams("")); - assertTrue(CheckUtils.checkOtherParams("xxx")); - assertFalse(CheckUtils.checkOtherParams("{}")); - assertFalse(CheckUtils.checkOtherParams("{\"key1\":111}")); + Assertions.assertFalse(CheckUtils.checkOtherParams(null)); + Assertions.assertFalse(CheckUtils.checkOtherParams("")); + Assertions.assertTrue(CheckUtils.checkOtherParams("xxx")); + Assertions.assertFalse(CheckUtils.checkOtherParams("{}")); + Assertions.assertFalse(CheckUtils.checkOtherParams("{\"key1\":111}")); } /** @@ -75,13 +72,13 @@ public class CheckUtilsTest { */ @Test public void testCheckPassword() { - assertFalse(CheckUtils.checkPassword(null)); - assertFalse(CheckUtils.checkPassword("a")); - assertFalse(CheckUtils.checkPassword("1234567890abcderfasdf2")); - assertTrue(CheckUtils.checkPassword("123456")); - assertFalse(CheckUtils.checkPasswordLength("1")); - assertTrue(CheckUtils.checkPasswordLength("dolphinscheduler123")); - assertFalse(CheckUtils.checkPasswordLength("dolphinscheduler123456")); + Assertions.assertFalse(CheckUtils.checkPassword(null)); + Assertions.assertFalse(CheckUtils.checkPassword("a")); + Assertions.assertFalse(CheckUtils.checkPassword("1234567890abcderfasdf2")); + Assertions.assertTrue(CheckUtils.checkPassword("123456")); + Assertions.assertFalse(CheckUtils.checkPasswordLength("1")); + Assertions.assertTrue(CheckUtils.checkPasswordLength("dolphinscheduler123")); + Assertions.assertFalse(CheckUtils.checkPasswordLength("dolphinscheduler123456")); } /** @@ -90,9 +87,9 @@ public class CheckUtilsTest { @Test public void testCheckPhone() { // phone can be null - assertTrue(CheckUtils.checkPhone(null)); - assertFalse(CheckUtils.checkPhone("14567134578654")); - assertTrue(CheckUtils.checkPhone("17362537263")); + Assertions.assertTrue(CheckUtils.checkPhone(null)); + Assertions.assertFalse(CheckUtils.checkPhone("14567134578654")); + Assertions.assertTrue(CheckUtils.checkPhone("17362537263")); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/FileUtilsTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/FileUtilsTest.java index a50629e647..59b88625c4 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/FileUtilsTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/FileUtilsTest.java @@ -18,8 +18,17 @@ package org.apache.dolphinscheduler.api.utils; import org.apache.http.entity.ContentType; -import org.junit.*; -import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Path; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,32 +36,18 @@ import org.springframework.core.io.Resource; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; -import java.io.*; - -import static org.junit.Assert.*; - public class FileUtilsTest { private static final Logger logger = LoggerFactory.getLogger(FileUtilsTest.class); - @Rule - public TemporaryFolder folder = null; + @TempDir + public Path folder; - private String rootPath = null; + private String rootPath; - @Before + @BeforeEach public void setUp() throws Exception { - - folder = new TemporaryFolder(); - folder.create(); - - rootPath = folder.getRoot().getAbsolutePath(); - } - - @After - public void tearDown() throws Exception { - - folder.delete(); + rootPath = folder.toString(); } /** @@ -62,52 +57,54 @@ public class FileUtilsTest { @Test public void testCopyFile() throws IOException { - //Define dest file path + // Define dest file path String src = rootPath + System.getProperty("file.separator") + "src.txt"; String destFilename = rootPath + System.getProperty("file.separator") + "data.txt"; - logger.info("destFilename: "+destFilename); + logger.info("destFilename: " + destFilename); - //Define InputStream for MultipartFile + // Define InputStream for MultipartFile String data = "data text"; org.apache.commons.io.FileUtils.writeStringToFile(new File(src), data); - //Use Mockito to mock MultipartFile + // Use Mockito to mock MultipartFile MultipartFile file = Mockito.mock(MultipartFile.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(file.getInputStream()).thenReturn(new FileInputStream(src)); - //Invoke copyFile - FileUtils.copyInputStreamToFile(file,destFilename); + // Invoke copyFile + FileUtils.copyInputStreamToFile(file, destFilename); - //Test file exists + // Test file exists File destFile = new File(destFilename); - assertTrue(destFile.exists()); + Assertions.assertTrue(destFile.exists()); } @Test public void testFile2Resource() throws IOException { - //Define dest file path - String destFilename = rootPath + System.getProperty("file.separator") + "data.txt"; - logger.info("destFilename: "+destFilename); + // Define dest file path + String destFilename = rootPath + System.getProperty("file.separator") + "resource.txt"; + logger.info("destFilename: " + destFilename); - //Define test resource - File file = folder.newFile("resource.txt"); + // Define test resource + File file = new File(destFilename); + org.apache.commons.io.FileUtils.writeStringToFile(file, "test data", Charset.defaultCharset()); - //Invoke file2Resource and test not null - Resource resource = FileUtils.file2Resource(file.getAbsolutePath()); - assertNotNull(resource); + // Invoke file2Resource and test not null + Resource resource = FileUtils.file2Resource(file.toString()); + Assertions.assertNotNull(resource); - //Invoke file2Resource and test null - Resource resource1 = FileUtils.file2Resource(file.getAbsolutePath()+"abc"); - assertNull(resource1); + // Invoke file2Resource and test null + Resource resource1 = FileUtils.file2Resource(file + "abc"); + Assertions.assertNull(resource1); } @Test public void testFile2String() throws IOException { String content = "123"; - org.apache.commons.io.FileUtils.writeStringToFile(new File("/tmp/task.json"),content); + org.apache.commons.io.FileUtils.writeStringToFile(new File("/tmp/task.json"), content, + Charset.defaultCharset()); File file = new File("/tmp/task.json"); FileInputStream fileInputStream = new FileInputStream("/tmp/task.json"); @@ -116,10 +113,10 @@ public class FileUtilsTest { String resultStr = FileUtils.file2String(multipartFile); - Assert.assertEquals(content, resultStr); + Assertions.assertEquals(content, resultStr); boolean delete = file.delete(); - Assert.assertTrue(delete); + Assertions.assertTrue(delete); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/RegexUtilsTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/RegexUtilsTest.java index f37b057fcf..b41a72dad6 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/RegexUtilsTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/RegexUtilsTest.java @@ -17,8 +17,8 @@ package org.apache.dolphinscheduler.api.utils; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; /** * RegexUtils test case @@ -28,43 +28,43 @@ public class RegexUtilsTest { @Test public void testIsValidLinuxUserName() { String name1 = "10000"; - Assert.assertTrue(RegexUtils.isValidLinuxUserName(name1)); + Assertions.assertTrue(RegexUtils.isValidLinuxUserName(name1)); String name2 = "00hayden"; - Assert.assertTrue(RegexUtils.isValidLinuxUserName(name2)); + Assertions.assertTrue(RegexUtils.isValidLinuxUserName(name2)); String name3 = "hayde123456789123456789123456789"; - Assert.assertFalse(RegexUtils.isValidLinuxUserName(name3)); + Assertions.assertFalse(RegexUtils.isValidLinuxUserName(name3)); String name4 = "hayd123456789123456789123456789"; - Assert.assertTrue(RegexUtils.isValidLinuxUserName(name4)); + Assertions.assertTrue(RegexUtils.isValidLinuxUserName(name4)); String name5 = "h"; - Assert.assertTrue(RegexUtils.isValidLinuxUserName(name5)); + Assertions.assertTrue(RegexUtils.isValidLinuxUserName(name5)); String name6 = "hayden"; - Assert.assertTrue(RegexUtils.isValidLinuxUserName(name6)); + Assertions.assertTrue(RegexUtils.isValidLinuxUserName(name6)); String name7 = "00hayden_0"; - Assert.assertTrue(RegexUtils.isValidLinuxUserName(name2)); + Assertions.assertTrue(RegexUtils.isValidLinuxUserName(name2)); String name8 = "00hayden.8"; - Assert.assertTrue(RegexUtils.isValidLinuxUserName(name2)); + Assertions.assertTrue(RegexUtils.isValidLinuxUserName(name2)); } @Test public void testEscapeNRT() { String result1 = RegexUtils.escapeNRT("abc\n"); - Assert.assertEquals("abc_", result1); + Assertions.assertEquals("abc_", result1); String result2 = RegexUtils.escapeNRT("abc\r"); - Assert.assertEquals("abc_", result2); + Assertions.assertEquals("abc_", result2); String result3 = RegexUtils.escapeNRT("abc\t"); - Assert.assertEquals("abc_", result3); + Assertions.assertEquals("abc_", result3); String result4 = RegexUtils.escapeNRT(null); - Assert.assertNull(result4); + Assertions.assertNull(result4); } } diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/ResultTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/ResultTest.java index 6301a44468..9c3217c0f0 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/ResultTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/utils/ResultTest.java @@ -16,17 +16,12 @@ */ package org.apache.dolphinscheduler.api.utils; -import com.fasterxml.jackson.core.type.TypeReference; import org.apache.dolphinscheduler.api.enums.Status; -import org.apache.dolphinscheduler.common.Constants; -import org.apache.dolphinscheduler.common.utils.JSONUtils; -import org.junit.Assert; -import org.junit.Test; import java.util.HashMap; -import java.util.Map; -import static org.junit.Assert.*; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; public class ResultTest { @@ -35,18 +30,18 @@ public class ResultTest { HashMap map = new HashMap<>(); map.put("testdata", "test"); Result ret = Result.success(map); - Assert.assertEquals(Status.SUCCESS.getCode(), ret.getCode().intValue()); + Assertions.assertEquals(Status.SUCCESS.getCode(), ret.getCode().intValue()); } @Test public void error() { Result ret = Result.error(Status.ACCESS_TOKEN_NOT_EXIST); - Assert.assertEquals(Status.ACCESS_TOKEN_NOT_EXIST.getCode(), ret.getCode().intValue()); + Assertions.assertEquals(Status.ACCESS_TOKEN_NOT_EXIST.getCode(), ret.getCode().intValue()); } @Test public void errorWithArgs() { Result ret = Result.errorWithArgs(Status.INTERNAL_SERVER_ERROR_ARGS, "test internal server error"); - Assert.assertEquals(Status.INTERNAL_SERVER_ERROR_ARGS.getCode(), ret.getCode().intValue()); + Assertions.assertEquals(Status.INTERNAL_SERVER_ERROR_ARGS.getCode(), ret.getCode().intValue()); } }