diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/AlertServer.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/AlertServer.java index ee38f3d3c9..a41498e258 100644 --- a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/AlertServer.java +++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/AlertServer.java @@ -39,19 +39,15 @@ public class AlertServer { private AlertSender alertSender; - private static volatile AlertServer instance; + private static AlertServer instance; public AlertServer() { } - public static AlertServer getInstance(){ + public synchronized static AlertServer getInstance(){ if (null == instance) { - synchronized (AlertServer.class) { - if(null == instance) { - instance = new AlertServer(); - } - } + instance = new AlertServer(); } return instance; } @@ -63,6 +59,7 @@ public class AlertServer { Thread.sleep(Constants.ALERT_SCAN_INTERVEL); } catch (InterruptedException e) { logger.error(e.getMessage(),e); + Thread.currentThread().interrupt(); } List alerts = alertDao.listWaitExecutionAlert(); alertSender = new AlertSender(alerts, alertDao); diff --git a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtils.java b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtils.java index a11d37f3d3..15e7e18855 100644 --- a/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtils.java +++ b/dolphinscheduler-alert/src/main/java/org/apache/dolphinscheduler/alert/utils/EnterpriseWeChatUtils.java @@ -86,20 +86,24 @@ public class EnterpriseWeChatUtils { String resp; CloseableHttpClient httpClient = HttpClients.createDefault(); - HttpGet httpGet = new HttpGet(enterpriseWeChatTokenUrlReplace); - CloseableHttpResponse response = httpClient.execute(httpGet); try { - HttpEntity entity = response.getEntity(); - resp = EntityUtils.toString(entity, Constants.UTF_8); - EntityUtils.consume(entity); + HttpGet httpGet = new HttpGet(enterpriseWeChatTokenUrlReplace); + CloseableHttpResponse response = httpClient.execute(httpGet); + try { + HttpEntity entity = response.getEntity(); + resp = EntityUtils.toString(entity, Constants.UTF_8); + EntityUtils.consume(entity); + } finally { + response.close(); + } + + Map map = JSON.parseObject(resp, + new TypeToken>() { + }.getType()); + return map.get("access_token").toString(); } finally { - response.close(); + httpClient.close(); } - - Map map = JSON.parseObject(resp, - new TypeToken>() { - }.getType()); - return map.get("access_token").toString(); } /** @@ -167,20 +171,25 @@ public class EnterpriseWeChatUtils { public static String sendEnterpriseWeChat(String charset, String data, String token) throws IOException { String enterpriseWeChatPushUrlReplace = enterpriseWeChatPushUrl.replaceAll("\\$token", token); - CloseableHttpClient httpclient = HttpClients.createDefault(); - HttpPost httpPost = new HttpPost(enterpriseWeChatPushUrlReplace); - httpPost.setEntity(new StringEntity(data, charset)); - CloseableHttpResponse response = httpclient.execute(httpPost); - String resp; + CloseableHttpClient httpClient = HttpClients.createDefault(); try { - HttpEntity entity = response.getEntity(); - resp = EntityUtils.toString(entity, charset); - EntityUtils.consume(entity); + HttpPost httpPost = new HttpPost(enterpriseWeChatPushUrlReplace); + httpPost.setEntity(new StringEntity(data, charset)); + CloseableHttpResponse response = httpClient.execute(httpPost); + String resp; + try { + HttpEntity entity = response.getEntity(); + resp = EntityUtils.toString(entity, charset); + EntityUtils.consume(entity); + } finally { + response.close(); + } + logger.info("Enterprise WeChat send [{}], param:{}, resp:{}", + enterpriseWeChatPushUrl, data, resp); + return resp; } finally { - response.close(); + httpClient.close(); } - logger.info("Enterprise WeChat send [{}], param:{}, resp:{}", enterpriseWeChatPushUrl, data, resp); - return resp; } /** diff --git a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/WorkerGroupService.java b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/WorkerGroupService.java index 925d01bd09..2d0743a5ab 100644 --- a/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/WorkerGroupService.java +++ b/dolphinscheduler-api/src/main/java/org/apache/dolphinscheduler/api/service/WorkerGroupService.java @@ -76,6 +76,11 @@ public class WorkerGroupService extends BaseService { WorkerGroup workerGroup = null; if(id != 0){ workerGroup = workerGroupMapper.selectById(id); + //check exist + if (workerGroup == null){ + workerGroup = new WorkerGroup(); + workerGroup.setCreateTime(now); + } }else{ workerGroup = new WorkerGroup(); workerGroup.setCreateTime(now); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AccessTokenServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AccessTokenServiceTest.java new file mode 100644 index 0000000000..a9a5f67b0b --- /dev/null +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AccessTokenServiceTest.java @@ -0,0 +1,181 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dolphinscheduler.api.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.commons.lang3.time.DateUtils; +import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.utils.PageInfo; +import org.apache.dolphinscheduler.common.Constants; +import org.apache.dolphinscheduler.common.enums.UserType; +import org.apache.dolphinscheduler.dao.entity.AccessToken; +import org.apache.dolphinscheduler.dao.entity.User; +import org.apache.dolphinscheduler.dao.mapper.AccessTokenMapper; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class AccessTokenServiceTest { + + + private static final Logger logger = LoggerFactory.getLogger(AccessTokenServiceTest.class); + + + @InjectMocks + private AccessTokenService accessTokenService ; + + @Mock + private AccessTokenMapper accessTokenMapper; + + @Before + public void setUp() { + + } + + + @After + public void after(){ + + } + + + + @Test + public void testQueryAccessTokenList(){ + + IPage tokenPage = new Page<>(); + tokenPage.setRecords(getList()); + tokenPage.setTotal(1L); + when(accessTokenMapper.selectAccessTokenPage(any(Page.class),eq("zhangsan"),eq(0))).thenReturn(tokenPage); + + User user =new User(); + Map result = accessTokenService.queryAccessTokenList(user,"zhangsan",1,10); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); + Assert.assertTrue(pageInfo.getTotalCount()>0); + } + + @Test + public void testCreateToken(){ + + + when(accessTokenMapper.insert(any(AccessToken.class))).thenReturn(2); + Map result = accessTokenService.createToken(1,getDate(),"AccessTokenServiceTest"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } + + @Test + public void testGenerateToken(){ + + Map result = accessTokenService.generateToken(Integer.MAX_VALUE,getDate()); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + String token = (String) result.get(Constants.DATA_LIST); + Assert.assertNotNull(token); + } + + @Test + public void testDelAccessTokenById(){ + + when(accessTokenMapper.selectById(1)).thenReturn(getEntity()); + User userLogin = new User(); + // not exist + Map result = accessTokenService.delAccessTokenById(userLogin,0); + logger.info(result.toString()); + Assert.assertEquals(Status.ACCESS_TOKEN_NOT_EXIST,result.get(Constants.STATUS)); + // no operate + result = accessTokenService.delAccessTokenById(userLogin,1); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM,result.get(Constants.STATUS)); + //success + userLogin.setId(1); + userLogin.setUserType(UserType.ADMIN_USER); + result = accessTokenService.delAccessTokenById(userLogin,1); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } + + @Test + public void testUpdateToken(){ + + when(accessTokenMapper.selectById(1)).thenReturn(getEntity()); + Map result = accessTokenService.updateToken(1,Integer.MAX_VALUE,getDate(),"token"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + // not exist + result = accessTokenService.updateToken(2,Integer.MAX_VALUE,getDate(),"token"); + logger.info(result.toString()); + Assert.assertEquals(Status.ACCESS_TOKEN_NOT_EXIST,result.get(Constants.STATUS)); + + } + + /** + * create entity + * @return + */ + private AccessToken getEntity(){ + AccessToken accessToken = new AccessToken(); + accessToken.setId(1); + accessToken.setUserId(1); + accessToken.setToken("AccessTokenServiceTest"); + Date date = DateUtils.addDays(new Date(),30); + accessToken.setExpireTime(date); + return accessToken; + } + + /** + * entity list + * @return + */ + private List getList(){ + + List list = new ArrayList<>(); + list.add(getEntity()); + return list; + } + + + + /** + * get dateStr + * @return + */ + private String getDate(){ + Date date = DateUtils.addDays(new Date(),30); + return org.apache.dolphinscheduler.common.utils.DateUtils.dateToString(date); + } +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java new file mode 100644 index 0000000000..4a31902af9 --- /dev/null +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/AlertGroupServiceTest.java @@ -0,0 +1,219 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dolphinscheduler.api.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.utils.PageInfo; +import org.apache.dolphinscheduler.api.utils.Result; +import org.apache.dolphinscheduler.common.Constants; +import org.apache.dolphinscheduler.common.enums.AlertType; +import org.apache.dolphinscheduler.common.enums.UserType; +import org.apache.dolphinscheduler.common.utils.CollectionUtils; +import org.apache.dolphinscheduler.dao.entity.AlertGroup; +import org.apache.dolphinscheduler.dao.entity.User; +import org.apache.dolphinscheduler.dao.mapper.AlertGroupMapper; +import org.apache.dolphinscheduler.dao.mapper.UserAlertGroupMapper; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +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 org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; + +@RunWith(MockitoJUnitRunner.class) +public class AlertGroupServiceTest { + + private static final Logger logger = LoggerFactory.getLogger(AlertGroupServiceTest.class); + + @InjectMocks + private AlertGroupService alertGroupService; + @Mock + private AlertGroupMapper alertGroupMapper; + @Mock + private UserAlertGroupMapper userAlertGroupMapper; + + private String groupName = "AlertGroupServiceTest"; + + @Before + public void setUp() { + } + + + @After + public void after(){ + + } + + + + @Test + public void testQueryAlertgroup(){ + + Mockito.when(alertGroupMapper.queryAllGroupList()).thenReturn(getList()); + HashMap result= alertGroupService.queryAlertgroup(); + logger.info(result.toString()); + List alertGroups = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(alertGroups)); + } + @Test + public void testListPaging(){ + IPage page = new Page<>(1,10); + page.setTotal(1L); + page.setRecords(getList()); + Mockito.when(alertGroupMapper.queryAlertGroupPage(any(Page.class),eq(groupName))).thenReturn(page); + User user = new User(); + // no operate + Map result = alertGroupService.listPaging(user,groupName,1,10); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM,result.get(Constants.STATUS)); + //success + user.setUserType(UserType.ADMIN_USER); + result = alertGroupService.listPaging(user,groupName,1,10); + logger.info(result.toString()); + PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getLists())); + + } + @Test + public void testCreateAlertgroup(){ + + + Mockito.when(alertGroupMapper.insert(any(AlertGroup.class))).thenReturn(2); + User user = new User(); + //no operate + Map result = alertGroupService.createAlertgroup(user,groupName, AlertType.EMAIL,groupName); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM,result.get(Constants.STATUS)); + user.setUserType(UserType.ADMIN_USER); + //success + result = alertGroupService.createAlertgroup(user,groupName, AlertType.EMAIL,groupName); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } + @Test + public void testUpdateAlertgroup(){ + + User user = new User(); + // no operate + Map result = alertGroupService.updateAlertgroup(user,1,groupName, AlertType.SMS,groupName); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM,result.get(Constants.STATUS)); + user.setUserType(UserType.ADMIN_USER); + // not exist + result = alertGroupService.updateAlertgroup(user,1,groupName, AlertType.SMS,groupName); + logger.info(result.toString()); + Assert.assertEquals(Status.ALERT_GROUP_NOT_EXIST,result.get(Constants.STATUS)); + //success + Mockito.when(alertGroupMapper.selectById(2)).thenReturn(getEntity()); + result = alertGroupService.updateAlertgroup(user,2,groupName, AlertType.SMS,groupName); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + + } + @Test + public void testDelAlertgroupById(){ + + User user = new User(); + // no operate + Map result = alertGroupService.delAlertgroupById(user,1); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM,result.get(Constants.STATUS)); + user.setUserType(UserType.ADMIN_USER); + // not exist + result = alertGroupService.delAlertgroupById(user,2); + logger.info(result.toString()); + Assert.assertEquals(Status.ALERT_GROUP_NOT_EXIST,result.get(Constants.STATUS)); + //success + Mockito.when(alertGroupMapper.selectById(2)).thenReturn(getEntity()); + result = alertGroupService.delAlertgroupById(user,2); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + + + } + @Test + public void testGrantUser(){ + + Map result = alertGroupService.grantUser(getLoginUser(),1,"123,321"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } + @Test + public void testVerifyGroupName(){ + //group name not exist + Result result = alertGroupService.verifyGroupName(getLoginUser(), groupName); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS.getMsg(),result.getMsg()); + Mockito.when(alertGroupMapper.queryByGroupName(groupName)).thenReturn(getList()); + + //group name exist + result = alertGroupService.verifyGroupName(getLoginUser(), groupName); + logger.info(result.toString()); + Assert.assertEquals(Status.ALERT_GROUP_EXIST.getMsg(),result.getMsg()); + } + + + /** + * create admin user + * @return + */ + private User getLoginUser(){ + + User loginUser = new User(); + loginUser.setUserType(UserType.ADMIN_USER); + loginUser.setId(99999999); + return loginUser; + } + + /** + * get list + * @return + */ + private List getList(){ + List alertGroups = new ArrayList<>(); + alertGroups.add(getEntity()); + return alertGroups; + } + + /** + * get entity + * @return + */ + private AlertGroup getEntity(){ + AlertGroup alertGroup = new AlertGroup(); + alertGroup.setId(1); + alertGroup.setGroupName(groupName); + alertGroup.setGroupType(AlertType.EMAIL); + return alertGroup; + } + +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/MonitorServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/MonitorServiceTest.java new file mode 100644 index 0000000000..b155d5959a --- /dev/null +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/MonitorServiceTest.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dolphinscheduler.api.service; + +import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.common.Constants; +import org.apache.dolphinscheduler.common.enums.DbType; +import org.apache.dolphinscheduler.common.model.Server; +import org.apache.dolphinscheduler.common.utils.CollectionUtils; +import org.apache.dolphinscheduler.dao.MonitorDBDao; +import org.apache.dolphinscheduler.dao.entity.MonitorRecord; +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 org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@RunWith(MockitoJUnitRunner.class) +public class MonitorServiceTest { + + private static final Logger logger = LoggerFactory.getLogger(MonitorServiceTest.class); + + @InjectMocks + private MonitorService monitorService; + @Mock + private MonitorDBDao monitorDBDao; + + + @Test + public void testQueryDatabaseState(){ + + Mockito.when(monitorDBDao.queryDatabaseState()).thenReturn(getList()); + Map result = monitorService.queryDatabaseState(null); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + List monitorRecordList = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(monitorRecordList)); + } + @Test + public void testQueryMaster(){ + //TODO need zk +// Map result = monitorService.queryMaster(null); +// logger.info(result.toString()); +// Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } + @Test + public void testQueryZookeeperState(){ + //TODO need zk +// Map result = monitorService.queryZookeeperState(null); +// logger.info(result.toString()); +// Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } + + @Test + public void testGetServerListFromZK(){ + //TODO need zk +// List serverList = monitorService.getServerListFromZK(true); +// logger.info(serverList.toString()); + } + + private List getList(){ + List monitorRecordList = new ArrayList<>(); + monitorRecordList.add(getEntity()); + return monitorRecordList; + } + + private MonitorRecord getEntity(){ + MonitorRecord monitorRecord = new MonitorRecord(); + monitorRecord.setDbType(DbType.MYSQL); + return monitorRecord; + } + + private List getServerList(){ + List servers = new ArrayList<>(); + servers.add(new Server()); + return servers; + } + +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProjectServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProjectServiceTest.java new file mode 100644 index 0000000000..51f9e148d1 --- /dev/null +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ProjectServiceTest.java @@ -0,0 +1,356 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dolphinscheduler.api.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.utils.PageInfo; +import org.apache.dolphinscheduler.common.Constants; +import org.apache.dolphinscheduler.common.enums.UserType; +import org.apache.dolphinscheduler.common.utils.CollectionUtils; +import org.apache.dolphinscheduler.dao.entity.ProcessDefinition; +import org.apache.dolphinscheduler.dao.entity.Project; +import org.apache.dolphinscheduler.dao.entity.ProjectUser; +import org.apache.dolphinscheduler.dao.entity.User; +import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper; +import org.apache.dolphinscheduler.dao.mapper.ProjectMapper; +import org.apache.dolphinscheduler.dao.mapper.ProjectUserMapper; +import org.apache.dolphinscheduler.dao.mapper.UserMapper; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +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 org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RunWith(MockitoJUnitRunner.class) +public class ProjectServiceTest { + + + private static final Logger logger = LoggerFactory.getLogger(ProjectServiceTest.class); + + @InjectMocks + private ProjectService projectService; + @Mock + private ProjectMapper projectMapper; + @Mock + private UserMapper userMapper; + @Mock + private ProjectUserMapper projectUserMapper; + @Mock + private ProcessDefinitionMapper processDefinitionMapper; + + + + private String projectName = "ProjectServiceTest"; + + private String userName = "ProjectServiceTest"; + + @Before + public void setUp() { + + } + + + @After + public void after(){ + + } + + @Test + public void testCreateProject(){ + + User loginUser = getLoginUser(); + loginUser.setId(1); + Map result = projectService.createProject(loginUser, projectName, getDesc()); + logger.info(result.toString()); + Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR,result.get(Constants.STATUS)); + + //project name exist + Mockito.when(projectMapper.queryByName(projectName)).thenReturn(getProject()); + result = projectService.createProject(loginUser, projectName, projectName); + logger.info(result.toString()); + Assert.assertEquals(Status.PROJECT_ALREADY_EXISTS,result.get(Constants.STATUS)); + + //success + Mockito.when(projectMapper.insert(Mockito.any(Project.class))).thenReturn(1); + result = projectService.createProject(loginUser, "test", "test"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + + + } + @Test + public void testQueryById(){ + + //not exist + Map result = projectService.queryById(Integer.MAX_VALUE); + Assert.assertEquals(Status.PROJECT_NOT_FOUNT,result.get(Constants.STATUS)); + logger.info(result.toString()); + + //success + Mockito.when(projectMapper.selectById(1)).thenReturn(getProject()); + result = projectService.queryById(1); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + + } + @Test + public void testCheckProjectAndAuth(){ + + Mockito.when(projectUserMapper.queryProjectRelation(1, 1)).thenReturn(getProjectUser()); + User loginUser = getLoginUser(); + + Map result = projectService.checkProjectAndAuth(loginUser,null,projectName); + logger.info(result.toString()); + Status status = (Status)result.get(Constants.STATUS); + Assert.assertEquals(Status.PROJECT_NOT_FOUNT,result.get(Constants.STATUS)); + + Project project = getProject(); + //USER_NO_OPERATION_PROJECT_PERM + project.setUserId(2); + result = projectService.checkProjectAndAuth(loginUser,project,projectName); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PROJECT_PERM,result.get(Constants.STATUS)); + + //success + project.setUserId(1); + result = projectService.checkProjectAndAuth(loginUser,project,projectName); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + + } + + @Test + public void testHasProjectAndPerm(){ + + // Mockito.when(projectUserMapper.queryProjectRelation(1, 1)).thenReturn(getProjectUser()); + User loginUser = getLoginUser(); + Project project = getProject(); + Map result = new HashMap<>(); + // not exist user + User tempUser = new User(); + tempUser.setId(Integer.MAX_VALUE); + boolean checkResult = projectService.hasProjectAndPerm(tempUser,project,result); + logger.info(result.toString()); + Assert.assertFalse(checkResult); + + //success + result = new HashMap<>(); + project.setUserId(1); + checkResult = projectService.hasProjectAndPerm(loginUser,project,result); + logger.info(result.toString()); + Assert.assertTrue(checkResult); + } + @Test + public void testQueryProjectListPaging(){ + + IPage page = new Page<>(1,10); + page.setRecords(getList()); + page.setTotal(1L); + Mockito.when(projectMapper.queryProjectListPaging(Mockito.any(Page.class), Mockito.eq(1), Mockito.eq(projectName))).thenReturn(page); + User loginUser = getLoginUser(); + + // project owner + Map result = projectService.queryProjectListPaging(loginUser,10,1,projectName); + logger.info(result.toString()); + PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getLists())); + + //admin + Mockito.when(projectMapper.queryProjectListPaging(Mockito.any(Page.class), Mockito.eq(0), Mockito.eq(projectName))).thenReturn(page); + loginUser.setUserType(UserType.ADMIN_USER); + result = projectService.queryProjectListPaging(loginUser,10,1,projectName); + logger.info(result.toString()); + pageInfo = (PageInfo) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getLists())); + } + @Test + public void testDeleteProject(){ + + Mockito.when(projectMapper.selectById(1)).thenReturn(getProject()); + User loginUser = getLoginUser(); + //PROJECT_NOT_FOUNT + Map result= projectService.deleteProject(loginUser,12); + logger.info(result.toString()); + Assert.assertEquals(Status.PROJECT_NOT_FOUNT,result.get(Constants.STATUS)); + loginUser.setId(2); + //USER_NO_OPERATION_PROJECT_PERM + result= projectService.deleteProject(loginUser,1); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PROJECT_PERM,result.get(Constants.STATUS)); + + //DELETE_PROJECT_ERROR_DEFINES_NOT_NULL + Mockito.when(processDefinitionMapper.queryAllDefinitionList(1)).thenReturn(getProcessDefinitions()); + loginUser.setUserType(UserType.ADMIN_USER); + result= projectService.deleteProject(loginUser,1); + logger.info(result.toString()); + Assert.assertEquals(Status.DELETE_PROJECT_ERROR_DEFINES_NOT_NULL,result.get(Constants.STATUS)); + + //success + Mockito.when(projectMapper.deleteById(1)).thenReturn(1); + Mockito.when(processDefinitionMapper.queryAllDefinitionList(1)).thenReturn(new ArrayList<>()); + result= projectService.deleteProject(loginUser,1); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + + + } + + @Test + public void testUpdate(){ + + User loginUser = getLoginUser(); + Project project = getProject(); + project.setId(2); + Mockito.when(projectMapper.queryByName(projectName)).thenReturn(project); + Mockito.when( projectMapper.selectById(1)).thenReturn(getProject()); + // PROJECT_NOT_FOUNT + Map result = projectService.update(loginUser,12,projectName,"desc"); + logger.info(result.toString()); + Assert.assertEquals(Status.PROJECT_NOT_FOUNT,result.get(Constants.STATUS)); + + //PROJECT_ALREADY_EXISTS + result = projectService.update(loginUser,1,projectName,"desc"); + logger.info(result.toString()); + Assert.assertEquals(Status.PROJECT_ALREADY_EXISTS,result.get(Constants.STATUS)); + + //success + project.setUserId(1); + Mockito.when(projectMapper.updateById(Mockito.any(Project.class))).thenReturn(1); + result = projectService.update(loginUser,1,"test","desc"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + + } + @Test + public void testQueryAuthorizedProject(){ + + User loginUser = getLoginUser(); + + Mockito.when(projectMapper.queryAuthedProjectListByUserId(1)).thenReturn(getList()); + //USER_NO_OPERATION_PERM + Map result = projectService.queryAuthorizedProject(loginUser,3); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM,result.get(Constants.STATUS)); + + //success + loginUser.setUserType(UserType.ADMIN_USER); + result = projectService.queryAuthorizedProject(loginUser,1); + logger.info(result.toString()); + List projects = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + + } + @Test + public void testQueryAllProjectList(){ + + Mockito.when(projectMapper.selectList(null)).thenReturn(getList()); + Mockito.when(processDefinitionMapper.selectList(null)).thenReturn(getProcessDefinitions()); + + Map result = projectService.queryAllProjectList(); + logger.info(result.toString()); + List projects = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + + } + @Test + public void testQueryUnauthorizedProject(){ + // Mockito.when(projectMapper.queryAuthedProjectListByUserId(1)).thenReturn(getList()); + Mockito.when(projectMapper.queryProjectExceptUserId(2)).thenReturn(getList()); + + User loginUser = new User(); + loginUser.setUserType(UserType.ADMIN_USER); + + Map result = projectService.queryUnauthorizedProject(loginUser,2); + logger.info(result.toString()); + List projects = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(projects)); + } + + + private Project getProject(){ + Project project = new Project(); + project.setId(1); + project.setName(projectName); + project.setUserId(1); + return project; + } + + private List getList(){ + List list = new ArrayList<>(); + list.add(getProject()); + return list; + } + + + /** + * create admin user + * @return + */ + private User getLoginUser(){ + + User loginUser = new User(); + loginUser.setUserType(UserType.GENERAL_USER); + loginUser.setUserName(userName); + loginUser.setId(1); + return loginUser; + + } + + /** + * get project user + + */ + private ProjectUser getProjectUser(){ + ProjectUser projectUser = new ProjectUser(); + projectUser.setProjectId(1); + projectUser.setUserId(1); + return projectUser; + } + + private List getProcessDefinitions(){ + List list = new ArrayList<>(); + ProcessDefinition processDefinition = new ProcessDefinition(); + processDefinition.setProjectId(1); + list.add(processDefinition); + return list; + } + + + + + private String getDesc(){ + return "projectUserMapper.deleteProjectRelation(projectId,userId)projectUserMappe" + + ".deleteProjectRelation(projectId,userId)projectUserMappe" + + "r.deleteProjectRelation(projectId,userId)projectUserMapper" + + ".deleteProjectRelation(projectId,userId)projectUserMapper.deleteProjectRelation(projectId,userId)"; + } + + +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java new file mode 100644 index 0000000000..dbae95b181 --- /dev/null +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/QueueServiceTest.java @@ -0,0 +1,208 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dolphinscheduler.api.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.utils.PageInfo; +import org.apache.dolphinscheduler.api.utils.Result; +import org.apache.dolphinscheduler.common.Constants; +import org.apache.dolphinscheduler.common.enums.UserType; +import org.apache.dolphinscheduler.common.utils.CollectionUtils; +import org.apache.dolphinscheduler.dao.entity.Queue; +import org.apache.dolphinscheduler.dao.entity.User; +import org.apache.dolphinscheduler.dao.mapper.QueueMapper; +import org.apache.dolphinscheduler.dao.mapper.UserMapper; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +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 org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@RunWith(MockitoJUnitRunner.class) +public class QueueServiceTest { + + private static final Logger logger = LoggerFactory.getLogger(QueueServiceTest.class); + + @InjectMocks + private QueueService queueService; + @Mock + private QueueMapper queueMapper; + @Mock + private UserMapper userMapper; + private String queueName = "QueueServiceTest"; + + @Before + public void setUp() { + } + + + @After + public void after(){ + } + + @Test + public void testQueryList(){ + + Mockito.when(queueMapper.selectList(null)).thenReturn(getQueueList()); + Map result = queueService.queryList(getLoginUser()); + logger.info(result.toString()); + List queueList = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(queueList)); + + } + @Test + public void testQueryListPage(){ + + IPage page = new Page<>(1,10); + page.setTotal(1L); + page.setRecords(getQueueList()); + Mockito.when(queueMapper.queryQueuePaging(Mockito.any(Page.class), Mockito.eq(queueName))).thenReturn(page); + Map result = queueService.queryList(getLoginUser(),queueName,1,10); + logger.info(result.toString()); + PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getLists())); + } + @Test + public void testCreateQueue(){ + + // queue is null + Map result = queueService.createQueue(getLoginUser(),null,queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR,result.get(Constants.STATUS)); + // queueName is null + result = queueService.createQueue(getLoginUser(),queueName,null); + logger.info(result.toString()); + Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR,result.get(Constants.STATUS)); + // correct + result = queueService.createQueue(getLoginUser(),queueName,queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + + } + @Test + public void testUpdateQueue(){ + + Mockito.when(queueMapper.selectById(1)).thenReturn(getQueue()); + Mockito.when(queueMapper.queryAllQueueList("test", null)).thenReturn(getQueueList()); + Mockito.when(queueMapper.queryAllQueueList(null, "test")).thenReturn(getQueueList()); + Mockito.when(userMapper.queryUserListByQueue(queueName)).thenReturn(getUserList()); + + // not exist + Map result = queueService.updateQueue(getLoginUser(),0,"queue",queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.QUEUE_NOT_EXIST.getCode(),((Status)result.get(Constants.STATUS)).getCode()); + //no need update + result = queueService.updateQueue(getLoginUser(),1,queueName,queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.NEED_NOT_UPDATE_QUEUE.getCode(),((Status)result.get(Constants.STATUS)).getCode()); + //queue exist + result = queueService.updateQueue(getLoginUser(),1,"test",queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.QUEUE_VALUE_EXIST.getCode(),((Status)result.get(Constants.STATUS)).getCode()); + // queueName exist + result = queueService.updateQueue(getLoginUser(),1,"test1","test"); + logger.info(result.toString()); + Assert.assertEquals(Status.QUEUE_NAME_EXIST.getCode(),((Status)result.get(Constants.STATUS)).getCode()); + //success + result = queueService.updateQueue(getLoginUser(),1,"test1","test1"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS.getCode(),((Status)result.get(Constants.STATUS)).getCode()); + + } + @Test + public void testVerifyQueue(){ + + Mockito.when(queueMapper.queryAllQueueList(queueName, null)).thenReturn(getQueueList()); + Mockito.when(queueMapper.queryAllQueueList(null, queueName)).thenReturn(getQueueList()); + + //queue null + Result result = queueService.verifyQueue(null,queueName); + logger.info(result.toString()); + Assert.assertEquals(result.getCode().intValue(), Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode()); + + //queueName null + result = queueService.verifyQueue(queueName,null); + logger.info(result.toString()); + Assert.assertEquals(result.getCode().intValue(), Status.REQUEST_PARAMS_NOT_VALID_ERROR.getCode()); + + //exist queueName + result = queueService.verifyQueue(queueName,queueName); + logger.info(result.toString()); + Assert.assertEquals(result.getCode().intValue(), Status.QUEUE_NAME_EXIST.getCode()); + + //exist queue + result = queueService.verifyQueue(queueName,"test"); + logger.info(result.toString()); + Assert.assertEquals(result.getCode().intValue(), Status.QUEUE_VALUE_EXIST.getCode()); + + // success + result = queueService.verifyQueue("test","test"); + logger.info(result.toString()); + Assert.assertEquals(result.getCode().intValue(), Status.SUCCESS.getCode()); + + + } + /** + * create admin user + * @return + */ + private User getLoginUser(){ + + User loginUser = new User(); + loginUser.setUserType(UserType.ADMIN_USER); + loginUser.setId(99999999); + return loginUser; + } + + private List getUserList(){ + List list = new ArrayList<>(); + list.add(getLoginUser()); + return list; + } + + + /** + * get queue + * @return + */ + private Queue getQueue(){ + Queue queue = new Queue(); + queue.setId(1); + queue.setQueue(queueName); + queue.setQueueName(queueName); + return queue; + } + + private List getQueueList(){ + List queueList = new ArrayList<>(); + queueList.add(getQueue()); + return queueList; + } + +} diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SessionServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SessionServiceTest.java index 1920586706..72545a347c 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SessionServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SessionServiceTest.java @@ -16,37 +16,130 @@ */ package org.apache.dolphinscheduler.api.service; -import org.apache.dolphinscheduler.api.ApiApplicationServer; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.enums.UserType; +import org.apache.dolphinscheduler.dao.entity.Session; import org.apache.dolphinscheduler.dao.entity.User; -import org.apache.commons.lang3.StringUtils; +import org.apache.dolphinscheduler.dao.mapper.SessionMapper; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.mock.web.MockCookie; +import org.springframework.mock.web.MockHttpServletRequest; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ApiApplicationServer.class) +@RunWith(MockitoJUnitRunner.class) public class SessionServiceTest { private static final Logger logger = LoggerFactory.getLogger(SessionServiceTest.class); - @Autowired + @InjectMocks private SessionService sessionService; + @Mock + private SessionMapper sessionMapper; + + private String sessionId ="aaaaaaaaaaaaaaaaaa"; + + @Before + public void setUp() { + } + + + @After + public void after(){ + } + + /** + * create session + */ + @Test + public void testGetSession(){ + + + Mockito.when(sessionMapper.selectById(sessionId)).thenReturn(getSession()); + // get sessionId from header + MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addHeader(Constants.SESSION_ID,sessionId); + mockHttpServletRequest.addHeader("HTTP_X_FORWARDED_FOR","127.0.0.1"); + //query + Session session = sessionService.getSession(mockHttpServletRequest); + Assert.assertNotNull(session); + logger.info("session ip {}",session.getIp()); + + // get sessionId from cookie + mockHttpServletRequest = new MockHttpServletRequest(); + mockHttpServletRequest.addHeader("HTTP_X_FORWARDED_FOR","127.0.0.1"); + MockCookie mockCookie = new MockCookie(Constants.SESSION_ID,sessionId); + mockHttpServletRequest.setCookies(mockCookie); + //query + session = sessionService.getSession(mockHttpServletRequest); + Assert.assertNotNull(session); + logger.info("session ip {}",session.getIp()); + Assert.assertEquals(session.getIp(),"127.0.0.1"); + + + } + + /** + * create session + */ + @Test + public void testCreateSession(){ + + String ip = "127.0.0.1"; + User user = new User(); + user.setUserType(UserType.GENERAL_USER); + user.setId(1); + Mockito.when(sessionMapper.queryByUserId(1)).thenReturn(getSessions()); + String sessionId = sessionService.createSession(user, ip); + logger.info("createSessionId is "+sessionId); + Assert.assertTrue(StringUtils.isNotEmpty(sessionId)); + } + /** + * sign out + * remove ip restrictions + */ @Test - public void createSession(){ + public void testSignOut(){ + + int userId = 88888888; + String ip = "127.0.0.1"; + User user = new User(); + user.setId(userId); + sessionService.signOut(ip ,user); - User loginUser = new User(); - loginUser.setId(1); - loginUser.setUserType(UserType.GENERAL_USER); + } - String session = sessionService.createSession(loginUser, "127.0.0.1"); - Assert.assertTrue(StringUtils.isNotEmpty(session)); + private Session getSession(){ + Session session = new Session(); + session.setId(sessionId); + session.setIp("127.0.0.1"); + session.setLastLoginTime(DateUtils.addDays(new Date(),40)); + session.setUserId(1); + return session; } + + private List getSessions(){ + List sessionList = new ArrayList<>(); + sessionList.add(getSession()); + return sessionList; + } + + } \ No newline at end of file diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java index ddd604ea88..31c8c0222d 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/TenantServiceTest.java @@ -16,38 +16,241 @@ */ package org.apache.dolphinscheduler.api.service; -import org.apache.dolphinscheduler.api.ApiApplicationServer; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.utils.PageInfo; +import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.enums.UserType; +import org.apache.dolphinscheduler.common.utils.CollectionUtils; +import org.apache.dolphinscheduler.dao.entity.ProcessDefinition; +import org.apache.dolphinscheduler.dao.entity.ProcessInstance; +import org.apache.dolphinscheduler.dao.entity.Tenant; import org.apache.dolphinscheduler.dao.entity.User; +import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper; +import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapper; +import org.apache.dolphinscheduler.dao.mapper.TenantMapper; +import org.apache.dolphinscheduler.dao.mapper.UserMapper; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import java.util.ArrayList; +import java.util.List; import java.util.Map; -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ApiApplicationServer.class) +@RunWith(MockitoJUnitRunner.class) public class TenantServiceTest { private static final Logger logger = LoggerFactory.getLogger(TenantServiceTest.class); - @Autowired + @InjectMocks private TenantService tenantService; + @Mock + private TenantMapper tenantMapper; + @Mock + private ProcessDefinitionMapper processDefinitionMapper; + @Mock + private ProcessInstanceMapper processInstanceMapper; + @Mock + private UserMapper userMapper; + + private String tenantCode ="TenantServiceTest"; + private String tenantName ="TenantServiceTest"; + + + @Test + public void testCreateTenant(){ + + User loginUser = getLoginUser(); + Mockito.when(tenantMapper.queryByTenantCode(tenantCode)).thenReturn(getList()); + try { + //check tenantCode + Map result = tenantService.createTenant(getLoginUser(), "%!1111", tenantName, 1, "TenantServiceTest"); + logger.info(result.toString()); + Assert.assertEquals(Status.VERIFY_TENANT_CODE_ERROR,result.get(Constants.STATUS)); + + //check exist + result = tenantService.createTenant(loginUser, tenantCode, tenantName, 1, "TenantServiceTest"); + logger.info(result.toString()); + Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR,result.get(Constants.STATUS)); + + // success + result = tenantService.createTenant(loginUser, "test", "test", 1, "TenantServiceTest"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } catch (Exception e) { + logger.error("create tenant error",e); + Assert.assertTrue(false); + } + } + + @Test + public void testQueryTenantListPage(){ + + IPage page = new Page<>(1,10); + page.setRecords(getList()); + page.setTotal(1L); + Mockito.when(tenantMapper.queryTenantPaging(Mockito.any(Page.class), Mockito.eq("TenantServiceTest"))).thenReturn(page); + Map result = tenantService.queryTenantList(getLoginUser(), "TenantServiceTest", 1, 10); + logger.info(result.toString()); + PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getLists())); + + } + + @Test + public void testUpdateTenant(){ + + Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); + try { + // id not exist + Map result = tenantService.updateTenant(getLoginUser(), 912222, tenantCode, tenantName, 1, "desc"); + logger.info(result.toString()); + // success + Assert.assertEquals(Status.TENANT_NOT_EXIST,result.get(Constants.STATUS)); + result = tenantService.updateTenant(getLoginUser(), 1, tenantCode, "TenantServiceTest001", 1, "desc"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } catch (Exception e) { + logger.error("update tenant error",e); + Assert.assertTrue(false); + } + + } @Test - public void queryTenantList(){ + public void testDeleteTenantById(){ + + Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); + Mockito.when(processInstanceMapper.queryByTenantIdAndStatus(1, Constants.NOT_TERMINATED_STATES)).thenReturn(getInstanceList()); + Mockito.when(processDefinitionMapper.queryDefinitionListByTenant(2)).thenReturn(getDefinitionsList()); + Mockito.when( userMapper.queryUserListByTenant(3)).thenReturn(getUserList()); + + try { + //TENANT_NOT_EXIST + Map result = tenantService.deleteTenantById(getLoginUser(),12); + logger.info(result.toString()); + Assert.assertEquals(Status.TENANT_NOT_EXIST,result.get(Constants.STATUS)); + + //DELETE_TENANT_BY_ID_FAIL + result = tenantService.deleteTenantById(getLoginUser(),1); + logger.info(result.toString()); + Assert.assertEquals(Status.DELETE_TENANT_BY_ID_FAIL,result.get(Constants.STATUS)); + + //DELETE_TENANT_BY_ID_FAIL_DEFINES + Mockito.when(tenantMapper.queryById(2)).thenReturn(getTenant(2)); + result = tenantService.deleteTenantById(getLoginUser(),2); + logger.info(result.toString()); + Assert.assertEquals(Status.DELETE_TENANT_BY_ID_FAIL_DEFINES,result.get(Constants.STATUS)); + + //DELETE_TENANT_BY_ID_FAIL_USERS + Mockito.when(tenantMapper.queryById(3)).thenReturn(getTenant(3)); + result = tenantService.deleteTenantById(getLoginUser(),3); + logger.info(result.toString()); + Assert.assertEquals(Status.DELETE_TENANT_BY_ID_FAIL_USERS,result.get(Constants.STATUS)); + + // success + Mockito.when(tenantMapper.queryById(4)).thenReturn(getTenant(4)); + result = tenantService.deleteTenantById(getLoginUser(),4); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS,result.get(Constants.STATUS)); + } catch (Exception e) { + logger.error("delete tenant error",e); + Assert.assertTrue(false); + } + } + + @Test + public void testQueryTenantList(){ + + Mockito.when( tenantMapper.selectList(null)).thenReturn(getList()); + Map result = tenantService.queryTenantList(getLoginUser()); + logger.info(result.toString()); + List tenantList = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(tenantList)); + } + + @Test + public void testVerifyTenantCode(){ + + Mockito.when(tenantMapper.queryByTenantCode(tenantCode)).thenReturn(getList()); + // tenantCode not exist + Result result = tenantService.verifyTenantCode("s00000000000l887888885554444sfjdskfjslakslkdf"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS.getMsg(),result.getMsg()); + // tenantCode exist + result = tenantService.verifyTenantCode(getTenant().getTenantCode()); + logger.info(result.toString()); + Assert.assertEquals(Status.TENANT_NAME_EXIST.getMsg(),result.getMsg()); + } + + + /** + * get user + * @return + */ + private User getLoginUser(){ User loginUser = new User(); loginUser.setUserType(UserType.ADMIN_USER); - Map map = tenantService.queryTenantList(loginUser); - Assert.assertEquals(Status.SUCCESS, map.get(Constants.STATUS)); - logger.info(map.toString()); + return loginUser; + } + /** + * get list + * @return + */ + private List getList(){ + List tenantList = new ArrayList<>(); + tenantList.add(getTenant()); + return tenantList; } + + /** + * get tenant + * @return + */ + private Tenant getTenant(){ + return getTenant(1); + } + /** + * get tenant + * @return + */ + private Tenant getTenant(int id){ + Tenant tenant = new Tenant(); + tenant.setId(id); + tenant.setTenantCode(tenantCode); + tenant.setTenantName(tenantName); + return tenant; + } + + private List getUserList(){ + List userList = new ArrayList<>(); + userList.add(getLoginUser()); + return userList; + } + + private List getInstanceList(){ + List processInstances = new ArrayList<>(); + ProcessInstance processInstance = new ProcessInstance(); + processInstances.add(processInstance); + return processInstances; + } + + private List getDefinitionsList(){ + List processDefinitions = new ArrayList<>(); + ProcessDefinition processDefinition = new ProcessDefinition(); + processDefinitions.add(processDefinition); + return processDefinitions; + } + + } \ No newline at end of file diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java index 21f0f7f3b3..30aabe93f2 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UsersServiceTest.java @@ -16,39 +16,449 @@ */ package org.apache.dolphinscheduler.api.service; -import org.apache.dolphinscheduler.api.ApiApplicationServer; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.utils.PageInfo; +import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.enums.UserType; +import org.apache.dolphinscheduler.common.utils.CollectionUtils; +import org.apache.dolphinscheduler.common.utils.EncryptionUtils; +import org.apache.dolphinscheduler.dao.entity.Tenant; import org.apache.dolphinscheduler.dao.entity.User; +import org.apache.dolphinscheduler.dao.mapper.*; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; +import java.util.ArrayList; +import java.util.List; import java.util.Map; -@RunWith(SpringRunner.class) -@SpringBootTest(classes = ApiApplicationServer.class) +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) public class UsersServiceTest { private static final Logger logger = LoggerFactory.getLogger(UsersServiceTest.class); - @Autowired + @InjectMocks private UsersService usersService; + @Mock + private UserMapper userMapper; + @Mock + private TenantMapper tenantMapper; + @Mock + private ProjectUserMapper projectUserMapper; + @Mock + private ResourceUserMapper resourcesUserMapper; + @Mock + private UDFUserMapper udfUserMapper; + @Mock + private DataSourceUserMapper datasourceUserMapper; + @Mock + private AlertGroupMapper alertGroupMapper; + + private String queueName ="UsersServiceTestQueue"; + + + @Before + public void before(){ + + + } + @After + public void after(){ + + } + + + @Test + public void testCreateUser(){ + + User user = new User(); + user.setUserType(UserType.ADMIN_USER); + String userName = "userTest0001~"; + String userPassword = "userTest"; + String email = "123@qq.com"; + int tenantId = Integer.MAX_VALUE; + String phone= "13456432345"; + try { + //userName error + Map result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + + userName = "userTest0001"; + userPassword = "userTest000111111111111111"; + //password error + result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + + userPassword = "userTest0001"; + email = "1q.com"; + //email error + result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + + email = "122222@qq.com"; + phone ="2233"; + //phone error + result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.REQUEST_PARAMS_NOT_VALID_ERROR, result.get(Constants.STATUS)); + + phone = "13456432345"; + //tenantId not exists + result = usersService.createUser(user, userName, userPassword, email, tenantId, phone, queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.TENANT_NOT_EXIST, result.get(Constants.STATUS)); + //success + Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); + result = usersService.createUser(user, userName, userPassword, email, 1, phone, queueName); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + + } catch (Exception e) { + logger.error(Status.CREATE_USER_ERROR.getMsg(),e); + Assert.assertTrue(false); + } + } + + @Test + public void testQueryUser(){ + + String userName = "userTest0001"; + String userPassword = "userTest0001"; + when(userMapper.queryUserByNamePassword(userName,EncryptionUtils.getMd5(userPassword))).thenReturn(getGeneralUser()); + User queryUser = usersService.queryUser(userName, userPassword); + logger.info(queryUser.toString()); + Assert.assertTrue(queryUser!=null); + } + + + + @Test + public void testQueryUserList(){ + + + User user = new User(); + + //no operate + Map result = usersService.queryUserList(user); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + + //success + user.setUserType(UserType.ADMIN_USER); + when(userMapper.selectList(null )).thenReturn(getUserList()); + result = usersService.queryUserList(user); + List userList = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(userList.size()>0); + } + + @Test + public void testQueryUserListPage(){ + + + User user = new User(); + IPage page = new Page<>(1,10); + page.setRecords(getUserList()); + when(userMapper.queryUserPaging(any(Page.class), eq("userTest"))).thenReturn(page); + + //no operate + Map result = usersService.queryUserList(user,"userTest",1,10); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + + //success + user.setUserType(UserType.ADMIN_USER); + result = usersService.queryUserList(user,"userTest",1,10); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); + Assert.assertTrue(pageInfo.getLists().size()>0); + } + + @Test + public void testUpdateUser(){ + + String userName = "userTest0001"; + String userPassword = "userTest0001"; + try { + //user not exist + Map result = usersService.updateUser(0,userName,userPassword,"3443@qq.com",1,"13457864543","queue"); + Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + logger.info(result.toString()); + + //success + when(userMapper.selectById(1)).thenReturn(getUser()); + result = usersService.updateUser(1,userName,userPassword,"32222s@qq.com",1,"13457864543","queue"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + } catch (Exception e) { + logger.error("update user error",e); + Assert.assertTrue(false); + } + } + + @Test + public void testDeleteUserById(){ + + User loginUser = new User(); + try { + when(userMapper.queryTenantCodeByUserId(1)).thenReturn(getUser()); + when(userMapper.selectById(1)).thenReturn(getUser()); + + //no operate + Map result = usersService.deleteUserById(loginUser,3); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + + // user not exist + loginUser.setUserType(UserType.ADMIN_USER); + result = usersService.deleteUserById(loginUser,3); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + + //success + result = usersService.deleteUserById(loginUser,1); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + } catch (Exception e) { + logger.error("delete user error",e); + Assert.assertTrue(false); + } + + + } + + @Test + public void testGrantProject(){ + + when(userMapper.selectById(1)).thenReturn(getUser()); + User loginUser = new User(); + String projectIds= "100000,120000"; + Map result = usersService.grantProject(loginUser, 1, projectIds); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + //user not exist + loginUser.setUserType(UserType.ADMIN_USER); + result = usersService.grantProject(loginUser, 2, projectIds); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + //success + result = usersService.grantProject(loginUser, 1, projectIds); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + } + + @Test + public void testGrantResources(){ + + String resourceIds = "100000,120000"; + when(userMapper.selectById(1)).thenReturn(getUser()); + User loginUser = new User(); + Map result = usersService.grantResources(loginUser, 1, resourceIds); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + //user not exist + loginUser.setUserType(UserType.ADMIN_USER); + result = usersService.grantResources(loginUser, 2, resourceIds); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + //success + result = usersService.grantResources(loginUser, 1, resourceIds); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + } + + + @Test + public void testGrantUDFFunction(){ + + String udfIds = "100000,120000"; + when(userMapper.selectById(1)).thenReturn(getUser()); + User loginUser = new User(); + Map result = usersService.grantUDFFunction(loginUser, 1, udfIds); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + //user not exist + loginUser.setUserType(UserType.ADMIN_USER); + result = usersService.grantUDFFunction(loginUser, 2, udfIds); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + //success + result = usersService.grantUDFFunction(loginUser, 1, udfIds); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + } + + @Test + public void testGrantDataSource(){ + + String datasourceIds = "100000,120000"; + when(userMapper.selectById(1)).thenReturn(getUser()); + User loginUser = new User(); + Map result = usersService.grantDataSource(loginUser, 1, datasourceIds); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + //user not exist + loginUser.setUserType(UserType.ADMIN_USER); + result = usersService.grantDataSource(loginUser, 2, datasourceIds); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NOT_EXIST, result.get(Constants.STATUS)); + //success + result = usersService.grantDataSource(loginUser, 1, datasourceIds); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + + } + @Test public void getUserInfo(){ User loginUser = new User(); - loginUser.setId(19); - loginUser.setUserType(UserType.GENERAL_USER); - Map map = usersService.getUserInfo(loginUser); - Assert.assertEquals(Status.SUCCESS, map.get(Constants.STATUS)); - logger.info(map.toString()); + loginUser.setUserName("admin"); + loginUser.setUserType(UserType.ADMIN_USER); + // get admin user + Map result = usersService.getUserInfo(loginUser); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + User tempUser = (User) result.get(Constants.DATA_LIST); + //check userName + Assert.assertEquals("admin",tempUser.getUserName()); + //get general user + loginUser.setUserType(null); + loginUser.setId(1); + when(userMapper.queryDetailsById(1)).thenReturn(getGeneralUser()); + result = usersService.getUserInfo(loginUser); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + tempUser = (User) result.get(Constants.DATA_LIST); + //check userName + Assert.assertEquals("userTest0001",tempUser.getUserName()); } + + + @Test + public void testQueryAllGeneralUsers(){ + + User loginUser = new User(); + //no operate + Map result = usersService.queryAllGeneralUsers(loginUser); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + //success + loginUser.setUserType(UserType.ADMIN_USER); + when(userMapper.queryAllGeneralUser()).thenReturn(getUserList()); + result = usersService.queryAllGeneralUsers(loginUser); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + List userList = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(userList)); + } + + @Test + public void testVerifyUserName(){ + + //not exist user + Result result = usersService.verifyUserName("admin89899"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + //exist user + when(userMapper.queryByUserNameAccurately("userTest0001")).thenReturn(getUser()); + result = usersService.verifyUserName("userTest0001"); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NAME_EXIST.getMsg(), result.getMsg()); + } + + @Test + public void testUnauthorizedUser(){ + + User loginUser = new User(); + when(userMapper.selectList(null )).thenReturn(getUserList()); + when( userMapper.queryUserListByAlertGroupId(2)).thenReturn(getUserList()); + //no operate + Map result = usersService.unauthorizedUser(loginUser, 2); + logger.info(result.toString()); + loginUser.setUserType(UserType.ADMIN_USER); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + //success + result = usersService.unauthorizedUser(loginUser, 2); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + } + + + @Test + public void testAuthorizedUser(){ + + User loginUser = new User(); + when(userMapper.queryUserListByAlertGroupId(2)).thenReturn(getUserList()); + //no operate + Map result = usersService.authorizedUser(loginUser, 2); + logger.info(result.toString()); + Assert.assertEquals(Status.USER_NO_OPERATION_PERM, result.get(Constants.STATUS)); + //success + loginUser.setUserType(UserType.ADMIN_USER); + result = usersService.authorizedUser(loginUser, 2); + Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); + List userList = (List) result.get(Constants.DATA_LIST); + logger.info(result.toString()); + Assert.assertTrue(CollectionUtils.isNotEmpty(userList)); + } + + /** + * get user + * @return + */ + private User getGeneralUser(){ + + User user = new User(); + user.setUserType(UserType.GENERAL_USER); + user.setUserName("userTest0001"); + user.setUserPassword("userTest0001"); + return user; + } + + + private List getUserList(){ + List userList = new ArrayList<>(); + userList.add(getGeneralUser()); + return userList; + } + + /** + * get user + */ + private User getUser(){ + + User user = new User(); + user.setUserType(UserType.ADMIN_USER); + user.setUserName("userTest0001"); + user.setUserPassword("userTest0001"); + return user; + } + + + private Tenant getTenant(){ + Tenant tenant = new Tenant(); + tenant.setId(1); + return tenant; + } + } \ No newline at end of file diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java new file mode 100644 index 0000000000..2c535054a7 --- /dev/null +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/WorkerGroupServiceTest.java @@ -0,0 +1,173 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.dolphinscheduler.api.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.apache.dolphinscheduler.api.enums.Status; +import org.apache.dolphinscheduler.api.utils.PageInfo; +import org.apache.dolphinscheduler.common.Constants; +import org.apache.dolphinscheduler.common.enums.UserType; +import org.apache.dolphinscheduler.common.utils.CollectionUtils; +import org.apache.dolphinscheduler.dao.entity.ProcessInstance; +import org.apache.dolphinscheduler.dao.entity.User; +import org.apache.dolphinscheduler.dao.entity.WorkerGroup; +import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapper; +import org.apache.dolphinscheduler.dao.mapper.WorkerGroupMapper; +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 org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +@RunWith(MockitoJUnitRunner.class) +public class WorkerGroupServiceTest { + + private static final Logger logger = LoggerFactory.getLogger(WorkerGroupServiceTest.class); + + @InjectMocks + private WorkerGroupService workerGroupService; + @Mock + private WorkerGroupMapper workerGroupMapper; + @Mock + private ProcessInstanceMapper processInstanceMapper; + + + private String groupName="groupName000001"; + + + /** + * create or update a worker group + */ + @Test + public void testSaveWorkerGroup(){ + + User user = new User(); + // general user add + user.setUserType(UserType.GENERAL_USER); + Map result = workerGroupService.saveWorkerGroup(user, 0, groupName, "127.0.0.1"); + logger.info(result.toString()); + Assert.assertEquals( Status.USER_NO_OPERATION_PERM.getMsg(),(String) result.get(Constants.MSG)); + + //success + user.setUserType(UserType.ADMIN_USER); + result = workerGroupService.saveWorkerGroup(user, 0, groupName, "127.0.0.1"); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS.getMsg(),(String)result.get(Constants.MSG)); + // group name exist + Mockito.when(workerGroupMapper.selectById(2)).thenReturn(getWorkerGroup(2)); + Mockito.when(workerGroupMapper.queryWorkerGroupByName(groupName)).thenReturn(getList()); + result = workerGroupService.saveWorkerGroup(user, 2, groupName, "127.0.0.1"); + logger.info(result.toString()); + Assert.assertEquals(Status.NAME_EXIST,result.get(Constants.STATUS)); + + } + + /** + * query worker group paging + */ + @Test + public void testQueryAllGroupPaging(){ + + User user = new User(); + // general user add + user.setUserType(UserType.GENERAL_USER); + Map result = workerGroupService.queryAllGroupPaging(user, 1, 10, groupName); + logger.info(result.toString()); + Assert.assertEquals((String) result.get(Constants.MSG), Status.USER_NO_OPERATION_PERM.getMsg()); + //success + user.setUserType(UserType.ADMIN_USER); + Page page = new Page<>(1,10); + page.setRecords(getList()); + page.setSize(1L); + Mockito.when(workerGroupMapper.queryListPaging(Mockito.any(Page.class), Mockito.eq(groupName))).thenReturn(page); + result = workerGroupService.queryAllGroupPaging(user, 1, 10, groupName); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS.getMsg(),(String)result.get(Constants.MSG)); + PageInfo pageInfo = (PageInfo) result.get(Constants.DATA_LIST); + Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getLists())); + } + + /** + * delete group by id + */ + @Test + public void testDeleteWorkerGroupById(){ + + //DELETE_WORKER_GROUP_BY_ID_FAIL + Mockito.when(processInstanceMapper.queryByWorkerGroupIdAndStatus(1, Constants.NOT_TERMINATED_STATES)).thenReturn(getProcessInstanceList()); + Map result = workerGroupService.deleteWorkerGroupById(1); + logger.info(result.toString()); + Assert.assertEquals(Status.DELETE_WORKER_GROUP_BY_ID_FAIL.getCode(),((Status) result.get(Constants.STATUS)).getCode()); + + //correct + result = workerGroupService.deleteWorkerGroupById(2); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS.getMsg(),(String)result.get(Constants.MSG)); + + } + + @Test + public void testQueryAllGroup(){ + Mockito.when(workerGroupMapper.queryAllWorkerGroup()).thenReturn(getList()); + Map result = workerGroupService.queryAllGroup(); + logger.info(result.toString()); + Assert.assertEquals(Status.SUCCESS.getMsg(),(String)result.get(Constants.MSG)); + List workerGroupList = (List) result.get(Constants.DATA_LIST); + Assert.assertTrue(workerGroupList.size()>0); + } + + + /** + * get processInstances + * @return + */ + private List getProcessInstanceList(){ + + List processInstances = new ArrayList<>(); + processInstances.add(new ProcessInstance()); + return processInstances; + } + /** + * get Group + * @return + */ + private WorkerGroup getWorkerGroup(int id){ + WorkerGroup workerGroup = new WorkerGroup(); + workerGroup.setName(groupName); + workerGroup.setId(id); + return workerGroup; + } + private WorkerGroup getWorkerGroup(){ + + return getWorkerGroup(1); + } + + private List getList(){ + List list = new ArrayList<>(); + list.add(getWorkerGroup()); + return list; + } + +} \ No newline at end of file diff --git a/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/definition/pages/list/_source/start.vue b/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/definition/pages/list/_source/start.vue index dfc7f49c20..2049b6b16e 100644 --- a/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/definition/pages/list/_source/start.vue +++ b/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/definition/pages/list/_source/start.vue @@ -19,6 +19,12 @@
{{$t('Please set the parameters before starting')}}
+
+
+ {{$t('Process Name')}} +
+
{{workflowName}}
+
{{$t('Failure Strategy')}} @@ -174,6 +180,7 @@ processDefinitionId: 0, failureStrategy: 'CONTINUE', warningTypeList: warningTypeList, + workflowName: '', warningType: '', notifyGroupList: [], warningGroupId: '', @@ -276,6 +283,7 @@ this.warningGroupId = '' }) }) + this.workflowName = this.item.name }, computed: {}, components: { mEmail, mPriority, mWorkerGroups } diff --git a/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/index/_source/chartConfig.js b/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/index/_source/chartConfig.js index f693ed578e..b8601a69c9 100644 --- a/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/index/_source/chartConfig.js +++ b/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/index/_source/chartConfig.js @@ -27,7 +27,7 @@ let pie = { avoidLabelOverlap: true, // Whether to prevent the label overlap policy hoverAnimation: true, // Whether to enable hover to enlarge the animation on the sector. radius: ['30%', '60%'], - center: ['50%', '50%'], + center: ['53%', '60%'], label: { align: 'left', normal: { diff --git a/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/index/_source/processStateCount.vue b/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/index/_source/processStateCount.vue index c21579a434..d121034932 100644 --- a/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/index/_source/processStateCount.vue +++ b/dolphinscheduler-ui/src/js/conf/home/pages/projects/pages/index/_source/processStateCount.vue @@ -29,7 +29,7 @@ {{$t('Number')}} {{$t('State')}} - + {{$index+1}} {{item.value}} {{item.key}} diff --git a/pom.xml b/pom.xml index 7936bf7dc8..fafa7be6ef 100644 --- a/pom.xml +++ b/pom.xml @@ -666,6 +666,15 @@ **/api/utils/CheckUtilsTest.java **/api/utils/FileUtilsTest.java **/api/enums/*.java + **/api/service/AccessTokenServiceTest.java + **/api/service/QueueServiceTest.java + **/api/service/MonitorServiceTest.java + **/api/service/SessionServiceTest.java + **/api/service/UsersServiceTest.java + **/api/service/TenantServiceTest.java + **/api/service/WorkerGroupServiceTest.java + **/api/service/AlertGroupServiceTest.java + **/api/service/ProjectServiceTest.java **/alert/utils/ExcelUtilsTest.java **/alert/utils/FuncUtilsTest.java **/alert/utils/JSONUtilsTest.java