Browse Source

[Migrate][Test] Migrate all UT cases from jUnit 4 to jUnit 5 in alert and api module (#12337)

* Migrate all UT cases from jUnit 4 to jUnit 5 in alert and api module

* Fix potential problems
3.2.0-release
Eric Gao 2 years ago committed by GitHub
parent
commit
224508850e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 9
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkAlertChannelFactoryTest.java
  2. 13
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-dingtalk/src/test/java/org/apache/dolphinscheduler/plugin/alert/dingtalk/DingTalkSenderTest.java
  3. 9
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelFactoryTest.java
  4. 102
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/EmailAlertChannelTest.java
  5. 75
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/ExcelUtilsTest.java
  6. 33
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/MailUtilsTest.java
  7. 29
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-email/src/test/java/org/apache/dolphinscheduler/plugin/alert/email/template/DefaultHTMLTemplateTest.java
  8. 8
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuAlertChannelFactoryTest.java
  9. 55
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-feishu/src/test/java/org/apache/dolphinscheduler/plugin/alert/feishu/FeiShuSenderTest.java
  10. 12
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelFactoryTest.java
  11. 8
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpAlertChannelTest.java
  12. 6
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-http/src/test/java/org/apache/dolphinscheduler/plugin/alert/http/HttpSenderTest.java
  13. 10
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutyAlertChannelFactoryTest.java
  14. 13
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-pagerduty/src/test/java/org/apache/dolphinscheduler/plugin/alert/pagerduty/PagerDutySenderTest.java
  15. 5
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ProcessUtilsTest.java
  16. 8
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptAlertChannelFactoryTest.java
  17. 14
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-script/src/test/java/org/apache/dolphinscheduler/plugin/alert/script/ScriptSenderTest.java
  18. 10
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackAlertChannelFactoryTest.java
  19. 8
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-slack/src/test/java/org/apache/dolphinscheduler/plugin/alert/slack/SlackSenderTest.java
  20. 11
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramAlertChannelFactoryTest.java
  21. 26
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-telegram/src/test/java/org/apache/dolphinscheduler/plugin/alert/telegram/TelegramSenderTest.java
  22. 10
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsAlertChannelFactoryTest.java
  23. 50
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-webexteams/src/test/java/org/apache/dolphinscheduler/plugin/alert/webexteams/WebexTeamsSenderTest.java
  24. 8
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatAlertChannelFactoryTest.java
  25. 48
      dolphinscheduler-alert/dolphinscheduler-alert-plugins/dolphinscheduler-alert-wechat/src/test/java/org/apache/dolphinscheduler/plugin/alert/wechat/WeChatSenderTest.java
  26. 39
      dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/AlertPluginManagerTest.java
  27. 24
      dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/processor/AlertRequestProcessorTest.java
  28. 20
      dolphinscheduler-alert/dolphinscheduler-alert-server/src/test/java/org/apache/dolphinscheduler/alert/runner/AlertSenderServiceTest.java
  29. 10
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/aspect/AccessLogAspectTest.java
  30. 13
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/audit/AuditSubscriberTest.java
  31. 11
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/AuditConfigurationTest.java
  32. 14
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/configuration/TrafficConfigurationTest.java
  33. 16
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AbstractControllerTest.java
  34. 35
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenControllerTest.java
  35. 34
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AccessTokenV2ControllerTest.java
  36. 40
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertGroupControllerTest.java
  37. 226
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AlertPluginInstanceControllerTest.java
  38. 8
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/AuditLogControllerTest.java
  39. 109
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ClusterControllerTest.java
  40. 2
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java
  41. 35
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataQualityControllerTest.java
  42. 201
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataSourceControllerTest.java
  43. 58
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/EnvironmentControllerTest.java
  44. 143
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ExecutorControllerTest.java
  45. 106
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/K8sNamespaceControllerTest.java
  46. 23
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoggerControllerTest.java
  47. 13
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/LoginControllerTest.java
  48. 41
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/MonitorControllerTest.java
  49. 45
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessDefinitionControllerTest.java
  50. 41
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java
  51. 12
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java
  52. 33
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectControllerTest.java
  53. 37
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProjectV2ControllerTest.java
  54. 45
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueControllerTest.java
  55. 113
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/QueueV2ControllerTest.java
  56. 40
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java
  57. 20
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/SchedulerControllerTest.java
  58. 20
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupControllerTest.java
  59. 6
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskGroupQueueControllerTest.java
  60. 14
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TaskInstanceControllerTest.java
  61. 57
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/TenantControllerTest.java
  62. 52
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UiPluginControllerTest.java
  63. 53
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/UsersControllerTest.java
  64. 20
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkFlowLineageControllerTest.java
  65. 14
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java
  66. 17
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkflowV2ControllerTest.java
  67. 32
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/filter/ResourceFilterTest.java
  68. 43
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/dto/resources/visitor/ResourceTreeVisitorTest.java
  69. 15
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/ExecuteTypeTest.java
  70. 22
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/enums/StatusTest.java
  71. 16
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ApiExceptionHandlerTest.java
  72. 16
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/exceptions/ServiceExceptionTest.java
  73. 6
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LocaleChangeInterceptorTest.java
  74. 21
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/LoginHandlerInterceptorTest.java
  75. 20
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java
  76. 27
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/k8s/K8sManagerTest.java
  77. 48
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/permission/ResourcePermissionCheckServiceTest.java
  78. 47
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/python/PythonGatewayTest.java
  79. 11
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigLDAPTest.java
  80. 6
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/SecurityConfigPasswordTest.java
  81. 46
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapAuthenticatorTest.java
  82. 49
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/ldap/LdapServiceTest.java
  83. 17
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/security/impl/pwd/PasswordAuthenticatorTest.java
  84. 75
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AccessTokenServiceTest.java
  85. 46
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java
  86. 58
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertPluginInstanceServiceTest.java
  87. 19
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AuditServiceTest.java
  88. 26
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java
  89. 70
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ClusterServiceTest.java
  90. 43
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java
  91. 66
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java
  92. 28
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqExecuteResultServiceTest.java
  93. 21
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DqRuleServiceTest.java
  94. 63
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentServiceTest.java
  95. 20
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/EnvironmentWorkerGroupRelationServiceTest.java
  96. 78
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ExecutorServiceTest.java
  97. 61
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/K8SNamespaceServiceTest.java
  98. 27
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java
  99. 67
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/MonitorServiceTest.java
  100. 95
      dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProcessDefinitionServiceTest.java
  101. Some files were not shown because too many files have changed in this diff Show More

9
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<PluginParams> 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);
}
}

13
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<String, String> 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());
}
}

9
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<PluginParams> 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);
}
}

102
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<PluginParams> 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<ParamsOptions> 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);

75
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();
}
}
}

33
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<String, String> 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() {

29
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
+ "<thead>"
+ "<tr><th>mysql service name</th><th>mysql address</th><th>database client connections</th><th>port</th><th>no index of number</th></tr>"
+ "</thead>"+System.getProperty("line.separator")
+ "<tr><td>mysql200</td><td>192.168.xx.xx</td><td>190</td><td>3306</td><td>80</td></tr>"
+ "<tr><td>mysql210</td><td>192.168.xx.xx</td><td>90</td><td>3306</td><td>10</td></tr>"
+ EmailConstants.TABLE_BODY_HTML_TAIL;
+ "<thead>"
+ "<tr><th>mysql service name</th><th>mysql address</th><th>database client connections</th><th>port</th><th>no index of number</th></tr>"
+ "</thead>" + System.getProperty("line.separator")
+ "<tr><td>mysql200</td><td>192.168.xx.xx</td><td>190</td><td>3306</td><td>80</td></tr>"
+ "<tr><td>mysql210</td><td>192.168.xx.xx</td><td>90</td><td>3306</td><td>10</td></tr>"
+ EmailConstants.TABLE_BODY_HTML_TAIL;
}
private String generateMockTextTypeResultByHand() {
return EmailConstants.HTML_HEADER_PREFIX
+ "<tr><td>{\"mysql service name\":\"mysql200\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"190\",\"port\":\"3306\",\"no index of number\":\"80\"}</td></tr>"
+ "<tr><td>{\"mysql service name\":\"mysql210\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"90\",\"port\":\"3306\",\"no index of number\":\"10\"}</td></tr>"
+ EmailConstants.TABLE_BODY_HTML_TAIL;
+ "<tr><td>{\"mysql service name\":\"mysql200\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"190\",\"port\":\"3306\",\"no index of number\":\"80\"}</td></tr>"
+ "<tr><td>{\"mysql service name\":\"mysql210\",\"mysql address\":\"192.168.xx.xx\",\"database client connections\":\"90\",\"port\":\"3306\",\"no index of number\":\"10\"}</td></tr>"
+ EmailConstants.TABLE_BODY_HTML_TAIL;
}
}

8
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<PluginParams> 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);
}
}

55
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<String, String> 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()));
}
}

12
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<PluginParams> 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);
}
}

8
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());
}
/**

6
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());
}
}

10
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<PluginParams> 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);
}
}

13
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<String, String> 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());
}
}

5
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"};

8
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<PluginParams> 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);
}
}

14
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<String, String> 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());
}
}

10
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<PluginParams> 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);
}
}

8
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<String, String> 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);
}
}

11
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<PluginParams> 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);
}
}

26
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<String, String> 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());
}
}

10
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<PluginParams> 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);
}
}

50
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<String, String> 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());
}
}

8
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<PluginParams> 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);
}
}

48
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<String, String> 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());
}
}

39
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));
}
}

24
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);
}
}

20
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);
}

10
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);
}
}

13
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));
}
}
}

11
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());
}
}
}

14
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()));
}
}

16
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<String, Object> 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);

35
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());
}
}

34
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());
}
}

40
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<AlertGroup>().lambda().eq(AlertGroup::getGroupName, defaultTestAlertGroupName));
alertGroupMapper.delete(
new QueryWrapper<AlertGroup>().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<String, String> 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());
}
}

226
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<String, Object> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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());
}
}

8
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());
}
}
}

109
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<Result<String>>() {
});
.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<Result<String>>() {
});
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<String, String> 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());
}
}

2
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;

35
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<String, Object> 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<DqRule> pageInfo = new PageInfo<>(1,10);
PageInfo<DqRule> 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<DqRule> pageInfo = new PageInfo<>(1,10);
PageInfo<DqRule> 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());
}
}

201
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<String, Object> 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<String, Object> 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<String, String> 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<String, String> 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<String, Object> 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<String, String> 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<String, String> 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<String, String> 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());
}
}

58
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<String, String> 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<String>>() {});
Result result = JSONUtils.parseObject(mvcResult.getResponse().getContentAsString(),
new TypeReference<Result<String>>() {
});
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<String, String> 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<String, String> 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<String, String> 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());
}
}

143
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<String, Object> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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);
}

106
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());
}
}
}

23
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<String, String> 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<String, String> 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());
}
}

13
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<String, String> data = (Map<String, String>) 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());
}
}

41
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());
}

45
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<String, Object> 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<ProcessDefinition> 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<PageInfo<ProcessDefinition>> 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());
}
}

41
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());
}
}

12
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());
}
}

33
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();

37
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<Resource>(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() {

45
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<String, String> 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<String, String> 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());
}

113
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());
}

40
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());
}
}

20
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());
}
}

20
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());
}

6
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());
}
}

14
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<String, String> 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());
}
}

57
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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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());
}
}

52
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<String, Object> 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<String, String> 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());
}
}

53
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<String, String> 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<String, String> 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<String, String> 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());
}
}

20
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<String, Object> 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());
}
}

14
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());
}
}

17
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<ProcessDefinition> 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<ProcessDefinition> resourceResponse =
workflowV2Controller.updateWorkflow(user, 1L, workflowUpdateRequest);
Assert.assertEquals(this.getProcessDefinition(newName), resourceResponse.getData());
Assertions.assertEquals(this.getProcessDefinition(newName), resourceResponse.getData());
}
@Test

32
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<Resource> 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<Resource> resourceList = resourceFilter.filter();
Assert.assertNotNull(resourceList);
Assertions.assertNotNull(resourceList);
resourceList.forEach(t -> logger.info(t.toString()));
}
}
}

43
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<Resource> 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<Resource> 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));
}
}
}

15
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));
}
}

22
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<Status> 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());
}
}

16
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());
}
}
}

16
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());
}
}

6
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));
}
}

21
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));
}
}

20
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));
}
}

27
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;
}
}
}

48
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<Object> resourcePermissionCheckService;
@InjectMocks
ResourcePermissionCheckServiceImpl resourcePermissionCheckServices;
protected static final Map<AuthorizationType, ResourcePermissionCheckServiceImpl.ResourceAcquisitionAndPermissionCheck<?>> RESOURCE_LIST_MAP = new ConcurrentHashMap<>();
protected static final Map<AuthorizationType, ResourcePermissionCheckServiceImpl.ResourceAcquisitionAndPermissionCheck<?>> 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<Project> 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

47
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<String, Long> result = pythonGateway.getCodeAndVersion(project.getName(), processDefinition.getName(), taskDefinition.getName());
Assert.assertEquals(result.get("code").longValue(), taskDefinition.getCode());
Map<String, Long> 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<String, Object> result = pythonGateway.getDependentInfo(project.getName(), processDefinition.getName(), taskDefinition.getName());
Assert.assertEquals((long) result.get("taskDefinitionCode"), taskDefinition.getCode());
Map<String, Object> 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() {

11
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);
}
}

6
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);
}
}

46
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<Map<String, String>> 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);
}
}

49
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);
}
}

17
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);
}
}

75
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<AccessToken> pageInfo = (PageInfo<AccessToken>) 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<AccessToken>) 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<String, Object> 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<String, Object> result = accessTokenService.generateToken(getLoginUser(), Integer.MAX_VALUE,getDate());
Map<String, Object> 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<String, Object> 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<String, Object> result = accessTokenService.updateToken(getLoginUser(), 1,Integer.MAX_VALUE,getDate(),"token");
Map<String, Object> 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() {

46
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<String, Object> result = alertGroupService.queryAlertgroup(getLoginUser());
logger.info(result.toString());
List<AlertGroup> alertGroups = (List<AlertGroup>) 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<AlertGroup> pageInfo = (PageInfo<AlertGroup>) 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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);
}
/**

58
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<String, Object> 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<String> 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<String, Object> 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<String, Object> 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<String, Object> result = alertPluginInstanceService.queryAll();
Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
}
}

19
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<AuditLog> getLists() {
@ -88,4 +89,4 @@ public class AuditServiceTest {
auditLog.setResourceType(0);
return auditLog;
}
}
}

26
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<String, Object> 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));
}

70
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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> result = clusterService.queryAllClusterList();
logger.info(result.toString());
Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
List<Cluster> list = (List<Cluster>) (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<Cluster> pageInfo = (PageInfo<Cluster>) 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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() {

43
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<String, Object> 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<String, Object> 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());

66
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<String, Object> result = dataSourceService.unauthDatasource(loginUser, userId);
logger.info(result.toString());
List<DataSource> dataSources = (List<DataSource>) 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<DataSource>) result.get(Constants.DATA_LIST);
Assert.assertTrue(CollectionUtils.isNotEmpty(dataSources));
Assertions.assertTrue(CollectionUtils.isNotEmpty(dataSources));
}
@Test
@ -288,14 +288,14 @@ public class DataSourceServiceTest {
Map<String, Object> result = dataSourceService.authedDatasource(loginUser, userId);
logger.info(result.toString());
List<DataSource> dataSources = (List<DataSource>) 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<String, Object> 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<String, Object> 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<String, Object> 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<DataSource> 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<CommonUtils> 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());
}
}

28
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<DqExecuteResult> 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<DqExecuteResult> getExecuteResultList() {

21
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<String, Object> 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<String, Object> 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<String, Object> 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<DataSource> dataSourceList() {

63
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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<Environment> list = (List<Environment>) (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<Environment> pageInfo = (PageInfo<Environment>) 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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() {

20
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<String, Object> 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<String, Object> result = relationService.queryAllEnvironmentWorkerGroupRelationList();
logger.info(result.toString());
Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS));
Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
}
}

78
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<String, Object> 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<String, Object> 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<Long> ids = new ArrayList<>();
@ -442,7 +452,7 @@ public class ExecutorServiceTest {
.thenReturn(processDefinitionList);
Map<String, Object> result = executorService.startCheckByProcessDefinedCode(1L);
Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
Assertions.assertEquals(Status.SUCCESS, result.get(Constants.STATUS));
}
private List<Server> 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));
}
}

61
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<K8sNamespace> pageInfo = (PageInfo<K8sNamespace>) result.getData();
Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList()));
Assertions.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList()));
}
@Test
@ -107,20 +110,20 @@ public class K8SNamespaceServiceTest {
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> result = k8sNamespaceService.queryAuthorizedNamespace(loginUser, 2);
logger.info(result.toString());
List<K8sNamespace> namespaces = (List<K8sNamespace>) 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<K8sNamespace>) result.get(Constants.DATA_LIST);
Assert.assertTrue(CollectionUtils.isEmpty(namespaces));
Assertions.assertTrue(CollectionUtils.isEmpty(namespaces));
}
@Test
@ -209,16 +212,16 @@ public class K8SNamespaceServiceTest {
Map<String, Object> result = k8sNamespaceService.queryUnauthorizedNamespace(loginUser, 2);
logger.info(result.toString());
List<K8sNamespace> namespaces = (List<K8sNamespace>) 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<K8sNamespace>) 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<K8sNamespace> result = k8sNamespaceService.queryNamespaceAvailable(getLoginUser());
Assert.assertEquals(result.get(0).getClusterName(), cluster.getName());
Assertions.assertEquals(result.get(0).getClusterName(), cluster.getName());
}
private User getLoginUser() {

27
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

67
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<String,Object> result = monitorService.queryDatabaseState(user);
Map<String, Object> 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<MonitorRecord> monitorRecordList = (List<MonitorRecord>) result.get(Constants.DATA_LIST);
Assert.assertTrue(CollectionUtils.isNotEmpty(monitorRecordList));
Assertions.assertTrue(CollectionUtils.isNotEmpty(monitorRecordList));
mockPermissionCheck(ApiFuncIdentificationConstant.MONITOR_DATABASES_VIEW, false);
Map<String,Object> noPermission = monitorService.queryDatabaseState(user);
Assert.assertEquals(Status.SUCCESS,noPermission.get(Constants.STATUS));
Map<String, Object> 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<String, Object> 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<String,Object> noPermission = monitorService.queryMaster(user);
Assert.assertEquals(Status.SUCCESS,noPermission.get(Constants.STATUS));
Map<String, Object> 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<String, Object> 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<String,Object> noPermission = monitorService.queryWorker(user);
Assert.assertEquals(Status.SUCCESS,noPermission.get(Constants.STATUS));
Map<String, Object> noPermission = monitorService.queryWorker(user);
Assertions.assertEquals(Status.SUCCESS, noPermission.get(Constants.STATUS));
}
@Test
public void testGetServerListFromZK() {
//TODO need zk
/*List<Server> serverList = monitorService.getServerListFromZK(true);*/
/*logger.info(serverList.toString());*/
public void testGetServerListFromZK() {
// TODO need zk
/* List<Server> 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<MonitorRecord> 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;
}

95
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<String, Object> 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<String, Object> 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<String, Object> result = new HashMap<>();
@ -250,7 +249,7 @@ public class ProcessDefinitionServiceTest extends BaseServiceTestTool {
PageInfo<ProcessDefinition> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<TaskDefinitionLog> taskDefinitionLogs = JSONUtils.toList(taskDefinitionJson, TaskDefinitionLog.class);
Map<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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<String, Object> 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

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save