From 57fafe42567b434d5a8ef4673ca5d9796cc4dd05 Mon Sep 17 00:00:00 2001 From: rickchengx <38122586+rickchengx@users.noreply.github.com> Date: Thu, 29 Sep 2022 12:00:41 +0800 Subject: [PATCH] [Improvement-12144] Remove powermock in dolphinschduler-api (#12169) --- dolphinscheduler-api/pom.xml | 9 + .../DataAnalysisControllerTest.java | 21 +- .../ProcessInstanceControllerTest.java | 37 +- .../ProcessTaskRelationControllerTest.java | 18 +- .../controller/ResourcesControllerTest.java | 54 +- .../controller/WorkerGroupControllerTest.java | 23 +- .../interceptor/RateLimitInterceptorTest.java | 9 +- .../api/service/BaseServiceTest.java | 24 +- .../api/service/DataAnalysisServiceTest.java | 42 +- .../api/service/DataSourceServiceTest.java | 202 ++++---- .../api/service/LoggerServiceTest.java | 2 - .../api/service/ResourcesServiceTest.java | 490 +++++++++--------- .../api/service/SchedulerServiceTest.java | 15 +- .../api/service/TenantServiceTest.java | 77 +-- .../api/service/UdfFuncServiceTest.java | 202 +++++--- 15 files changed, 621 insertions(+), 604 deletions(-) diff --git a/dolphinscheduler-api/pom.xml b/dolphinscheduler-api/pom.xml index fee8b25056..66df53785b 100644 --- a/dolphinscheduler-api/pom.xml +++ b/dolphinscheduler-api/pom.xml @@ -200,6 +200,15 @@ h2 test + + + org.mockito + mockito-inline + 3.12.4 + + test + + diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java index 636a1ec0a4..66e9b9ce0b 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/DataAnalysisControllerTest.java @@ -28,9 +28,9 @@ import org.apache.dolphinscheduler.common.utils.JSONUtils; import org.apache.dolphinscheduler.dao.entity.Project; import org.apache.dolphinscheduler.dao.mapper.ProjectMapper; +import java.util.Date; + import org.junit.Test; -import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -39,12 +39,11 @@ import org.springframework.test.web.servlet.MvcResult; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import java.util.Date; - /** * data analysis controller test */ public class DataAnalysisControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(DataAnalysisControllerTest.class); @Autowired @@ -65,9 +64,9 @@ public class DataAnalysisControllerTest extends AbstractControllerTest { int projectId = createProject(); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("startDate","2019-12-01 00:00:00"); - paramsMap.add("endDate","2019-12-28 00:00:00"); - paramsMap.add("projectCode","16"); + paramsMap.add("startDate", "2019-12-01 00:00:00"); + paramsMap.add("endDate", "2019-12-28 00:00:00"); + paramsMap.add("projectCode", "16"); MvcResult mvcResult = mockMvc.perform(get("/projects/analysis/task-state-count") .header("sessionId", sessionId) .params(paramsMap)) @@ -86,9 +85,9 @@ public class DataAnalysisControllerTest extends AbstractControllerTest { int projectId = createProject(); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("startDate","2019-12-01 00:00:00"); - paramsMap.add("endDate","2019-12-28 00:00:00"); - paramsMap.add("projectCode","16"); + paramsMap.add("startDate", "2019-12-01 00:00:00"); + paramsMap.add("endDate", "2019-12-28 00:00:00"); + paramsMap.add("projectCode", "16"); MvcResult mvcResult = mockMvc.perform(get("/projects/analysis/process-state-count") .header("sessionId", sessionId) @@ -107,7 +106,7 @@ public class DataAnalysisControllerTest extends AbstractControllerTest { public void testCountDefinitionByUser() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("projectId","16"); + paramsMap.add("projectId", "16"); MvcResult mvcResult = mockMvc.perform(get("/projects/analysis/define-user-count") .header("sessionId", sessionId) diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java index 8f4fd9902d..56cbee73dc 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessInstanceControllerTest.java @@ -17,8 +17,12 @@ package org.apache.dolphinscheduler.api.controller; -import java.util.HashMap; -import java.util.Map; +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.service.ProcessInstanceService; @@ -26,21 +30,18 @@ import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.enums.WorkflowExecutionStatus; 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.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; 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.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; /** * process instance controller test @@ -54,7 +55,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { public void testQueryProcessInstanceList() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.SUCCESS.getCode()); - PowerMockito.when(processInstanceService + Mockito.when(processInstanceService .queryProcessInstanceList(Mockito.any(), Mockito.anyLong(), Mockito.anyLong(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) @@ -85,7 +86,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { public void testQueryTaskListByProcessId() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.PROJECT_NOT_FOUND); - PowerMockito + Mockito .when(processInstanceService.queryTaskListByProcessId(Mockito.any(), Mockito.anyLong(), Mockito.any())) .thenReturn(mockResult); @@ -104,7 +105,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { public void testUpdateProcessInstance() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when(processInstanceService + Mockito.when(processInstanceService .updateProcessInstance(Mockito.any(), Mockito.anyLong(), Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())) @@ -141,7 +142,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { public void testQueryProcessInstanceById() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when( + Mockito.when( processInstanceService.queryProcessInstanceById(Mockito.any(), Mockito.anyLong(), Mockito.anyInt())) .thenReturn(mockResult); MvcResult mvcResult = mockMvc.perform(get("/projects/{projectCode}/process-instances/{id}", "1113", "123") @@ -159,7 +160,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { public void testQuerySubProcessInstanceByTaskId() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.TASK_INSTANCE_NOT_EXISTS); - PowerMockito.when(processInstanceService.querySubProcessInstanceByTaskId(Mockito.any(), Mockito.anyLong(), + Mockito.when(processInstanceService.querySubProcessInstanceByTaskId(Mockito.any(), Mockito.anyLong(), Mockito.anyInt())).thenReturn(mockResult); MvcResult mvcResult = mockMvc @@ -179,7 +180,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { public void testQueryParentInstanceBySubId() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.PROCESS_INSTANCE_NOT_SUB_PROCESS_INSTANCE); - PowerMockito.when( + Mockito.when( processInstanceService.queryParentInstanceBySubId(Mockito.any(), Mockito.anyLong(), Mockito.anyInt())) .thenReturn(mockResult); @@ -200,7 +201,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { public void testViewVariables() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when(processInstanceService.viewVariables(1113L, 123)).thenReturn(mockResult); + Mockito.when(processInstanceService.viewVariables(1113L, 123)).thenReturn(mockResult); MvcResult mvcResult = mockMvc .perform(get("/projects/{projectCode}/process-instances/{id}/view-variables", "1113", "123") .header(SESSION_ID, sessionId)) @@ -216,7 +217,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { public void testDeleteProcessInstanceById() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when( + Mockito.when( processInstanceService.deleteProcessInstanceById(Mockito.any(), Mockito.anyLong(), Mockito.anyInt())) .thenReturn(mockResult); @@ -236,7 +237,7 @@ public class ProcessInstanceControllerTest extends AbstractControllerTest { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.PROCESS_INSTANCE_NOT_EXIST); - PowerMockito.when( + Mockito.when( processInstanceService.deleteProcessInstanceById(Mockito.any(), Mockito.anyLong(), Mockito.anyInt())) .thenReturn(mockResult); MvcResult mvcResult = mockMvc.perform(post("/projects/{projectCode}/process-instances/batch-delete", "1113") diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java index 8649d32cbd..ca675812e0 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ProcessTaskRelationControllerTest.java @@ -33,7 +33,6 @@ import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; @@ -42,6 +41,7 @@ import org.springframework.test.web.servlet.MvcResult; * process task relation controller test */ public class ProcessTaskRelationControllerTest extends AbstractControllerTest { + @MockBean(name = "processTaskRelationServiceImpl") private ProcessTaskRelationService processTaskRelationService; @@ -49,11 +49,13 @@ public class ProcessTaskRelationControllerTest extends AbstractControllerTest { public void testQueryDownstreamRelation() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when(processTaskRelationService.queryDownstreamRelation(Mockito.any(), Mockito.anyLong(), Mockito.anyLong())) + Mockito.when( + processTaskRelationService.queryDownstreamRelation(Mockito.any(), Mockito.anyLong(), Mockito.anyLong())) .thenReturn(mockResult); - MvcResult mvcResult = mockMvc.perform(get("/projects/{projectCode}/process-task-relation/{taskCode}/downstream", "1113", "123") - .header(SESSION_ID, sessionId)) + MvcResult mvcResult = mockMvc + .perform(get("/projects/{projectCode}/process-task-relation/{taskCode}/downstream", "1113", "123") + .header(SESSION_ID, sessionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); @@ -67,11 +69,13 @@ public class ProcessTaskRelationControllerTest extends AbstractControllerTest { public void testQueryUpstreamRelation() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when(processTaskRelationService.queryUpstreamRelation(Mockito.any(), Mockito.anyLong(), Mockito.anyLong())) + Mockito.when( + processTaskRelationService.queryUpstreamRelation(Mockito.any(), Mockito.anyLong(), Mockito.anyLong())) .thenReturn(mockResult); - MvcResult mvcResult = mockMvc.perform(get("/projects/{projectCode}/process-task-relation/{taskCode}/upstream", "1113", "123") - .header(SESSION_ID, sessionId)) + MvcResult mvcResult = mockMvc + .perform(get("/projects/{projectCode}/process-task-relation/{taskCode}/upstream", "1113", "123") + .header(SESSION_ID, sessionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java index 3be552f878..d499a35125 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/ResourcesControllerTest.java @@ -39,7 +39,6 @@ import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.mock.mockito.MockBean; @@ -53,6 +52,7 @@ import org.springframework.util.MultiValueMap; * resources controller test */ public class ResourcesControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(ResourcesControllerTest.class); @MockBean(name = "resourcesServiceImpl") @@ -65,7 +65,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testQuerytResourceList() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when(resourcesService.queryResourceList(Mockito.any(), Mockito.any())).thenReturn(mockResult); + Mockito.when(resourcesService.queryResourceList(Mockito.any(), Mockito.any())).thenReturn(mockResult); MvcResult mvcResult = mockMvc.perform(get("/resources/list") .header(SESSION_ID, sessionId) @@ -84,8 +84,9 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testQueryResourceListPaging() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.SUCCESS.getCode()); - PowerMockito.when(resourcesService.queryResourceListPaging( - Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt())) + Mockito.when(resourcesService.queryResourceListPaging( + Mockito.any(), Mockito.anyInt(), Mockito.any(), Mockito.anyString(), Mockito.anyInt(), + Mockito.anyInt())) .thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); @@ -112,7 +113,8 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testVerifyResourceName() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.TENANT_NOT_EXIST.getCode()); - PowerMockito.when(resourcesService.verifyResourceName(Mockito.anyString(), Mockito.any(), Mockito.any())).thenReturn(mockResult); + Mockito.when(resourcesService.verifyResourceName(Mockito.anyString(), Mockito.any(), Mockito.any())) + .thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("fullName", "list_resources_1.sh"); @@ -135,7 +137,8 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testViewResource() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.HDFS_NOT_STARTUP.getCode()); - PowerMockito.when(resourcesService.readResource(Mockito.any(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(mockResult); + Mockito.when(resourcesService.readResource(Mockito.any(), Mockito.anyInt(), Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("skipLineNum", "2"); @@ -158,8 +161,9 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testOnlineCreateResource() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.TENANT_NOT_EXIST.getCode()); - PowerMockito.when(resourcesService - .onlineCreateResource(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())) + Mockito.when(resourcesService + .onlineCreateResource(Mockito.any(), Mockito.any(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyString())) .thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); @@ -188,7 +192,8 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testUpdateResourceContent() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.TENANT_NOT_EXIST.getCode()); - PowerMockito.when(resourcesService.updateResourceContent(Mockito.any(), Mockito.anyInt(), Mockito.anyString())).thenReturn(mockResult); + Mockito.when(resourcesService.updateResourceContent(Mockito.any(), Mockito.anyInt(), Mockito.anyString())) + .thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("id", "1"); @@ -210,7 +215,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { @Test public void testDownloadResource() throws Exception { - PowerMockito.when(resourcesService.downloadResource(Mockito.any(), Mockito.anyInt())).thenReturn(null); + Mockito.when(resourcesService.downloadResource(Mockito.any(), Mockito.anyInt())).thenReturn(null); MvcResult mvcResult = mockMvc.perform(get("/resources/{id}/download", 5) .header(SESSION_ID, sessionId)) @@ -224,8 +229,9 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testCreateUdfFunc() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.TENANT_NOT_EXIST.getCode()); - PowerMockito.when(udfFuncService - .createUdfFunction(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyInt())) + Mockito.when(udfFuncService + .createUdfFunction(Mockito.any(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyInt())) .thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); @@ -254,7 +260,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testViewUIUdfFunction() throws Exception { Result mockResult = new Result<>(); putMsg(mockResult, Status.TENANT_NOT_EXIST); - PowerMockito.when(udfFuncService + Mockito.when(udfFuncService .queryUdfFuncDetail(Mockito.any(), Mockito.anyInt())) .thenReturn(mockResult); @@ -274,8 +280,9 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testUpdateUdfFunc() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.TENANT_NOT_EXIST.getCode()); - PowerMockito.when(udfFuncService - .updateUdfFunc(Mockito.any(), Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyInt())) + Mockito.when(udfFuncService + .updateUdfFunc(Mockito.any(), Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), + Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyInt())) .thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); @@ -305,7 +312,8 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testQueryUdfFuncList() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.SUCCESS.getCode()); - PowerMockito.when(udfFuncService.queryUdfFuncListPaging(Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt())).thenReturn(mockResult); + Mockito.when(udfFuncService.queryUdfFuncListPaging(Mockito.any(), Mockito.anyString(), Mockito.anyInt(), + Mockito.anyInt())).thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("pageNo", "1"); @@ -329,7 +337,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testQueryResourceList() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.SUCCESS.getCode()); - PowerMockito.when(udfFuncService.queryUdfFuncList(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); + Mockito.when(udfFuncService.queryUdfFuncList(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("type", String.valueOf(UdfType.HIVE)); @@ -351,7 +359,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testVerifyUdfFuncName() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.SUCCESS.getCode()); - PowerMockito.when(udfFuncService.verifyUdfFuncByName(Mockito.any(), Mockito.anyString())).thenReturn(mockResult); + Mockito.when(udfFuncService.verifyUdfFuncByName(Mockito.any(), Mockito.anyString())).thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("name", "test"); @@ -373,7 +381,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testAuthorizedFile() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when(resourcesService.authorizedFile(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); + Mockito.when(resourcesService.authorizedFile(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("userId", "2"); @@ -395,7 +403,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testAuthorizedUDFFunction() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when(resourcesService.authorizedUDFFunction(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); + Mockito.when(resourcesService.authorizedUDFFunction(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("userId", "2"); @@ -417,7 +425,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testUnauthUDFFunc() throws Exception { Map mockResult = new HashMap<>(); mockResult.put(Constants.STATUS, Status.SUCCESS); - PowerMockito.when(resourcesService.unauthorizedUDFFunction(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); + Mockito.when(resourcesService.unauthorizedUDFFunction(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); paramsMap.add("userId", "2"); @@ -439,7 +447,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testDeleteUdfFunc() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.SUCCESS.getCode()); - PowerMockito.when(udfFuncService.delete(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); + Mockito.when(udfFuncService.delete(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); MvcResult mvcResult = mockMvc.perform(delete("/resources/udf-func/{id}", "123") .header(SESSION_ID, sessionId)) @@ -457,7 +465,7 @@ public class ResourcesControllerTest extends AbstractControllerTest { public void testDeleteResource() throws Exception { Result mockResult = new Result<>(); mockResult.setCode(Status.SUCCESS.getCode()); - PowerMockito.when(resourcesService.delete(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); + Mockito.when(resourcesService.delete(Mockito.any(), Mockito.anyInt())).thenReturn(mockResult); MvcResult mvcResult = mockMvc.perform(delete("/resources/{id}", "123") .header(SESSION_ID, sessionId)) diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java index 72bad1e686..118a82eb6d 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/controller/WorkerGroupControllerTest.java @@ -38,7 +38,6 @@ import java.util.Map; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.test.mock.mockito.MockBean; @@ -51,6 +50,7 @@ import org.springframework.util.MultiValueMap; * worker group controller test */ public class WorkerGroupControllerTest extends AbstractControllerTest { + private static final Logger logger = LoggerFactory.getLogger(WorkerGroupControllerTest.class); @MockBean(name = "workerGroupMapper") @@ -67,13 +67,13 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { Map serverMaps = new HashMap<>(); serverMaps.put("192.168.0.1", "192.168.0.1"); serverMaps.put("192.168.0.2", "192.168.0.2"); - PowerMockito.when(registryClient.getServerMaps(NodeType.WORKER, true)).thenReturn(serverMaps); + Mockito.when(registryClient.getServerMaps(NodeType.WORKER, true)).thenReturn(serverMaps); MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("name","cxc_work_group"); - paramsMap.add("addrList","192.168.0.1,192.168.0.2"); - paramsMap.add("description",""); - paramsMap.add("otherParamsJson",""); + paramsMap.add("name", "cxc_work_group"); + paramsMap.add("addrList", "192.168.0.1,192.168.0.2"); + paramsMap.add("description", ""); + paramsMap.add("otherParamsJson", ""); MvcResult mvcResult = mockMvc.perform(post("/worker-groups") .header("sessionId", sessionId) .params(paramsMap)) @@ -88,9 +88,9 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { @Test public void testQueryAllWorkerGroupsPaging() throws Exception { MultiValueMap paramsMap = new LinkedMultiValueMap<>(); - paramsMap.add("pageNo","2"); - paramsMap.add("searchVal","cxc"); - paramsMap.add("pageSize","2"); + paramsMap.add("pageNo", "2"); + paramsMap.add("searchVal", "cxc"); + paramsMap.add("pageSize", "2"); MvcResult mvcResult = mockMvc.perform(get("/worker-groups") .header("sessionId", sessionId) .params(paramsMap)) @@ -119,7 +119,7 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { @Test public void queryWorkerAddressList() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/worker-groups/worker-address-list") - .header("sessionId", sessionId)) + .header("sessionId", sessionId)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andReturn(); @@ -134,7 +134,8 @@ public class WorkerGroupControllerTest extends AbstractControllerTest { workerGroup.setId(12); workerGroup.setName("测试"); Mockito.when(workerGroupMapper.selectById(12)).thenReturn(workerGroup); - Mockito.when(processInstanceMapper.queryByWorkerGroupNameAndStatus("测试", Constants.NOT_TERMINATED_STATES)).thenReturn(null); + Mockito.when(processInstanceMapper.queryByWorkerGroupNameAndStatus("测试", Constants.NOT_TERMINATED_STATES)) + .thenReturn(null); Mockito.when(workerGroupMapper.deleteById(12)).thenReturn(1); Mockito.when(processInstanceMapper.updateProcessInstanceByWorkerGroupName("测试", "")).thenReturn(1); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java index c903df5009..e1eef9e41d 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/interceptor/RateLimitInterceptorTest.java @@ -30,10 +30,9 @@ import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.junit.MockitoJUnitRunner; -@RunWith(PowerMockRunner.class) +@RunWith(MockitoJUnitRunner.class) public class RateLimitInterceptorTest { @Test @@ -58,8 +57,8 @@ public class RateLimitInterceptorTest { HttpServletRequest tenant1Request = Mockito.mock(HttpServletRequest.class); HttpServletRequest tenant2Request = Mockito.mock(HttpServletRequest.class); - PowerMockito.when(tenant1Request.getHeader(Mockito.any())).thenReturn("tenant1"); - PowerMockito.when(tenant2Request.getHeader(Mockito.any())).thenReturn("tenant2"); + Mockito.when(tenant1Request.getHeader(Mockito.any())).thenReturn("tenant1"); + Mockito.when(tenant2Request.getHeader(Mockito.any())).thenReturn("tenant2"); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); for (int i = 0; i < 2; i++) { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java index 49b3c1c299..eefc6ce254 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/BaseServiceTest.java @@ -33,18 +33,14 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * base service test */ -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({"sun.security.*", "javax.net.*"}) -@PrepareForTest({HadoopUtils.class}) +@RunWith(MockitoJUnitRunner.class) public class BaseServiceTest { private static final Logger logger = LoggerFactory.getLogger(BaseServiceTest.class); @@ -93,22 +89,6 @@ public class BaseServiceTest { baseService.putMsg(result, Status.PROJECT_NOT_FOUND, "test"); } - // @Test - // public void testCreateTenantDirIfNotExists() { - // - // PowerMockito.mockStatic(HadoopUtils.class); - // PowerMockito.when(HadoopUtils.getInstance()).thenReturn(hadoopUtils); - // - // try { - // baseService.createTenantDirIfNotExists("test"); - // } catch (Exception e) { - // Assert.fail(); - // logger.error("CreateTenantDirIfNotExists error ",e); - // e.printStackTrace(); - // } - // - // } - @Test public void testHasPerm() { diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java index 1ae0455f61..d732be6f03 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataAnalysisServiceTest.java @@ -17,8 +17,6 @@ package org.apache.dolphinscheduler.api.service; -import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.PROJECT_OVERVIEW; - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; @@ -32,9 +30,7 @@ import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.enums.AuthorizationType; import org.apache.dolphinscheduler.common.enums.CommandType; import org.apache.dolphinscheduler.common.enums.UserType; -import org.apache.dolphinscheduler.common.utils.DateUtils; import org.apache.dolphinscheduler.dao.entity.CommandCount; -import org.apache.dolphinscheduler.dao.entity.DefinitionGroupByUser; import org.apache.dolphinscheduler.dao.entity.ExecuteStatusCount; import org.apache.dolphinscheduler.dao.entity.Project; import org.apache.dolphinscheduler.dao.entity.User; @@ -44,6 +40,7 @@ import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper; import org.apache.dolphinscheduler.dao.mapper.ProcessInstanceMapper; import org.apache.dolphinscheduler.dao.mapper.ProjectMapper; import org.apache.dolphinscheduler.dao.mapper.TaskInstanceMapper; +import org.apache.dolphinscheduler.plugin.task.api.enums.TaskExecutionStatus; import java.text.MessageFormat; import java.util.ArrayList; @@ -54,7 +51,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.dolphinscheduler.plugin.task.api.enums.TaskExecutionStatus; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -63,15 +59,14 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * data analysis service test */ -@RunWith(PowerMockRunner.class) +@RunWith(MockitoJUnitRunner.class) public class DataAnalysisServiceTest { private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); @@ -118,8 +113,6 @@ public class DataAnalysisServiceTest { project.setId(1); project.setName("test"); resultMap = new HashMap<>(); - Mockito.when(projectMapper.selectById(1)).thenReturn(project); - Mockito.when(projectService.hasProjectAndPerm(user, project, resultMap, PROJECT_OVERVIEW)).thenReturn(true); Mockito.when(projectMapper.queryByCode(1L)).thenReturn(project); } @@ -142,15 +135,6 @@ public class DataAnalysisServiceTest { Mockito.when(projectMapper.queryByCode(1L)).thenReturn(getProject("test")); // SUCCESS - Mockito.when(taskInstanceMapper.countTaskInstanceStateByProjectCodes(DateUtils.stringToDate(startDate), - DateUtils.stringToDate(endDate), - new Long[]{1L})).thenReturn(getTaskInstanceStateCounts()); - Mockito.when(projectMapper.selectById(Mockito.any())).thenReturn(getProject("test")); - Mockito.when(projectService.hasProjectAndPerm(Mockito.any(), - Mockito.any(), - (Map) Mockito.any(), - Mockito.any())).thenReturn(true); - result = dataAnalysisServiceImpl.countTaskStateByProject(user, 1, startDate, endDate); Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @@ -227,7 +211,7 @@ public class DataAnalysisServiceTest { // when instanceStateCounter return null, then return nothing user.setUserType(UserType.GENERAL_USER); - PowerMockito.when(taskInstanceMapper.countTaskInstanceStateByProjectCodes(any(), any(), any())) + Mockito.when(taskInstanceMapper.countTaskInstanceStateByProjectCodes(any(), any(), any())) .thenReturn(null); result = dataAnalysisServiceImpl.countTaskStateByProject(user, 1, null, null); Assert.assertNull(result.get(Constants.DATA_LIST)); @@ -252,28 +236,16 @@ public class DataAnalysisServiceTest { Mockito.when(projectService.checkProjectAndAuth(any(), any(), anyLong(), any())).thenReturn(result); // SUCCESS - Mockito.when(processInstanceMapper.countInstanceStateByProjectCodes(DateUtils.stringToDate(startDate), - DateUtils.stringToDate(endDate), - new Long[]{1L})).thenReturn(getTaskInstanceStateCounts()); - Mockito.when(projectService.hasProjectAndPerm(Mockito.any(), - Mockito.any(), - (Map) Mockito.any(), - Mockito.any())).thenReturn(true); - result = dataAnalysisServiceImpl.countProcessInstanceStateByProject(user, 1, startDate, endDate); Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); } @Test public void testCountDefinitionByUser() { - Mockito.when(projectMapper.queryByCode(1L)).thenReturn(getProject("test")); Map result = new HashMap<>(); putMsg(result, Status.SUCCESS, null); - Mockito.when(projectService.checkProjectAndAuth(any(), any(), anyLong(), any())).thenReturn(result); - Mockito.when(processDefinitionMapper.countDefinitionByProjectCodes( - Mockito.any(Long[].class))).thenReturn(new ArrayList()); Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.PROJECTS, 1, serviceLogger)).thenReturn(projectIds()); result = dataAnalysisServiceImpl.countDefinitionByUser(user, 0); @@ -290,12 +262,6 @@ public class DataAnalysisServiceTest { User user = new User(); user.setUserType(UserType.ADMIN_USER); user.setId(1); - List commandCounts = new ArrayList<>(1); - CommandCount commandCount = new CommandCount(); - commandCount.setCommandType(CommandType.START_PROCESS); - commandCounts.add(commandCount); - Mockito.when(commandMapper.countCommandState(null, null, new Long[]{1L})).thenReturn(commandCounts); - Mockito.when(errorCommandMapper.countCommandState(null, null, new Long[]{1L})).thenReturn(commandCounts); Map result = dataAnalysisServiceImpl.countCommandState(user); Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java index d5e6ac554e..cf13f7f20a 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/DataSourceServiceTest.java @@ -18,9 +18,9 @@ package org.apache.dolphinscheduler.api.service; import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.DATASOURCE_DELETE; -import static org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant.DATASOURCE_LIST; 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.DataSourceServiceImpl; import org.apache.dolphinscheduler.api.utils.Result; @@ -35,12 +35,10 @@ import org.apache.dolphinscheduler.dao.mapper.DataSourceUserMapper; import org.apache.dolphinscheduler.plugin.datasource.api.plugin.DataSourceClientProvider; import org.apache.dolphinscheduler.plugin.datasource.api.utils.CommonUtils; import org.apache.dolphinscheduler.plugin.datasource.api.utils.DataSourceUtils; -import org.apache.dolphinscheduler.plugin.datasource.api.utils.PasswordUtils; import org.apache.dolphinscheduler.plugin.datasource.hive.param.HiveDataSourceParamDTO; import org.apache.dolphinscheduler.plugin.datasource.mysql.param.MySQLDataSourceParamDTO; import org.apache.dolphinscheduler.plugin.datasource.oracle.param.OracleDataSourceParamDTO; import org.apache.dolphinscheduler.plugin.datasource.postgresql.param.PostgreSQLDataSourceParamDTO; -import org.apache.dolphinscheduler.api.permission.ResourcePermissionCheckService; import org.apache.dolphinscheduler.spi.datasource.ConnectionParam; import org.apache.dolphinscheduler.spi.enums.DbConnectType; import org.apache.dolphinscheduler.spi.enums.DbType; @@ -50,7 +48,6 @@ import org.apache.commons.collections.CollectionUtils; import java.sql.Connection; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -63,21 +60,18 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * data source service test */ -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({"sun.security.*", "javax.net.*"}) -@PrepareForTest({DataSourceUtils.class, CommonUtils.class, DataSourceClientProvider.class, PasswordUtils.class}) +@RunWith(MockitoJUnitRunner.class) public class DataSourceServiceTest { + private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); private static final Logger logger = LoggerFactory.getLogger(DataSourceServiceTest.class); private static final Logger dataSourceServiceLogger = LoggerFactory.getLogger(DataSourceServiceImpl.class); @@ -113,30 +107,31 @@ public class DataSourceServiceTest { DataSource dataSource = new DataSource(); dataSource.setName(dataSourceName); dataSourceList.add(dataSource); - PowerMockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(dataSourceList); + Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(dataSourceList); Result dataSourceExitsResult = dataSourceService.createDataSource(loginUser, postgreSqlDatasourceParam); Assert.assertEquals(Status.DATASOURCE_EXIST.getCode(), dataSourceExitsResult.getCode().intValue()); ConnectionParam connectionParam = DataSourceUtils.buildConnectionParams(postgreSqlDatasourceParam); DbType dataSourceType = postgreSqlDatasourceParam.getType(); // data source exits - PowerMockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(null); - Result connectionResult = new Result(Status.DATASOURCE_CONNECT_FAILED.getCode(), Status.DATASOURCE_CONNECT_FAILED.getMsg()); - //PowerMockito.when(dataSourceService.checkConnection(dataSourceType, parameter)).thenReturn(connectionResult); - PowerMockito.doReturn(connectionResult).when(dataSourceService).checkConnection(dataSourceType, connectionParam); + Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(null); + Result connectionResult = + new Result(Status.DATASOURCE_CONNECT_FAILED.getCode(), Status.DATASOURCE_CONNECT_FAILED.getMsg()); + + Mockito.doReturn(connectionResult).when(dataSourceService).checkConnection(dataSourceType, connectionParam); Result connectFailedResult = dataSourceService.createDataSource(loginUser, postgreSqlDatasourceParam); Assert.assertEquals(Status.DATASOURCE_CONNECT_FAILED.getCode(), connectFailedResult.getCode().intValue()); // data source exits - PowerMockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(null); + Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(null); connectionResult = new Result(Status.SUCCESS.getCode(), Status.SUCCESS.getMsg()); - PowerMockito.when(dataSourceService.checkConnection(dataSourceType, connectionParam)).thenReturn(connectionResult); + 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()); // success - PowerMockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName.trim())).thenReturn(null); - PowerMockito.when(dataSourceService.checkConnection(dataSourceType, connectionParam)).thenReturn(connectionResult); + 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()); } @@ -158,40 +153,44 @@ public class DataSourceServiceTest { postgreSqlDatasourceParam.setPassword(""); // data source not exits - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); - Result resourceNotExits = dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); + Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); + Result resourceNotExits = + dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getCode(), resourceNotExits.getCode().intValue()); // user no operation perm DataSource dataSource = new DataSource(); dataSource.setUserId(0); - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); - Result userNoOperationPerm = dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); + 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()); // data source name exits dataSource.setUserId(-1); List dataSourceList = new ArrayList<>(); dataSourceList.add(dataSource); - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); - PowerMockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(dataSourceList); - Result dataSourceNameExist = dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); + Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); + Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(dataSourceList); + Result dataSourceNameExist = + dataSourceService.updateDataSource(dataSourceId, loginUser, postgreSqlDatasourceParam); Assert.assertEquals(Status.DATASOURCE_EXIST.getCode(), dataSourceNameExist.getCode().intValue()); // data source connect failed DbType dataSourceType = postgreSqlDatasourceParam.getType(); ConnectionParam connectionParam = DataSourceUtils.buildConnectionParams(postgreSqlDatasourceParam); - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); - PowerMockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(null); + Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); + Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(null); Result connectionResult = new Result(Status.SUCCESS.getCode(), Status.SUCCESS.getMsg()); - PowerMockito.when(dataSourceService.checkConnection(dataSourceType, connectionParam)).thenReturn(connectionResult); + 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()); - //success - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); - PowerMockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(null); - connectionResult = new Result(Status.DATASOURCE_CONNECT_FAILED.getCode(), Status.DATASOURCE_CONNECT_FAILED.getMsg()); - PowerMockito.when(dataSourceService.checkConnection(dataSourceType, connectionParam)).thenReturn(connectionResult); + // success + Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); + Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(null); + connectionResult = + 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()); @@ -199,25 +198,19 @@ public class DataSourceServiceTest { @Test public void queryDataSourceListPagingTest() { - Set ids = new HashSet<>(); - ids.add(1); - User loginUser = getAdminUser(); String searchVal = ""; int pageNo = 1; int pageSize = 10; - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATASOURCE, null, loginUser.getId(), DATASOURCE_LIST, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATASOURCE, null, loginUser.getId(), baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.DATASOURCE, loginUser.getId(), baseServiceLogger)).thenReturn(ids); Result result = dataSourceService.queryDataSourceListPaging(loginUser, searchVal, pageNo, pageSize); - Assert.assertEquals(Status.SUCCESS.getCode(),(int)result.getCode()); + Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); } @Test public void connectionTest() { int dataSourceId = -1; - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); + Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); Result result = dataSourceService.connectionTest(dataSourceId); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getCode(), result.getCode().intValue()); } @@ -227,18 +220,16 @@ public class DataSourceServiceTest { User loginUser = getAdminUser(); int dataSourceId = 1; Result result = new Result(); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATASOURCE, null, loginUser.getId(), null, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATASOURCE, new Object[]{dataSourceId}, -1, baseServiceLogger)).thenReturn(true); - //resource not exist + // resource not exist dataSourceService.putMsg(result, Status.RESOURCE_NOT_EXIST); - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); + Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(null); Assert.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); - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); + Mockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); Assert.assertEquals(result.getCode(), dataSourceService.delete(loginUser, dataSourceId).getCode()); // success @@ -247,9 +238,11 @@ public class DataSourceServiceTest { loginUser.setUserType(UserType.ADMIN_USER); loginUser.setId(1); dataSource.setId(22); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATASOURCE, null, loginUser.getId(), DATASOURCE_DELETE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATASOURCE,new Object[]{dataSource.getId()} , 0, baseServiceLogger)).thenReturn(true); - PowerMockito.when(dataSourceMapper.selectById(dataSourceId)).thenReturn(dataSource); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATASOURCE, null, + loginUser.getId(), DATASOURCE_DELETE, baseServiceLogger)).thenReturn(true); + 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()); } @@ -260,8 +253,10 @@ public class DataSourceServiceTest { loginUser.setId(1); loginUser.setUserType(UserType.ADMIN_USER); int userId = 3; - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATASOURCE, null, loginUser.getId(), null, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATASOURCE, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATASOURCE, null, + loginUser.getId(), null, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATASOURCE, null, 0, + baseServiceLogger)).thenReturn(true); // test admin user Mockito.when(dataSourceMapper.queryAuthedDatasource(userId)).thenReturn(getSingleDataSourceList()); Mockito.when(dataSourceMapper.queryDatasourceExceptUserId(userId)).thenReturn(getDataSourceList()); @@ -273,7 +268,8 @@ public class DataSourceServiceTest { // test non-admin user loginUser.setId(2); loginUser.setUserType(UserType.GENERAL_USER); - Mockito.when(dataSourceMapper.selectByMap(Collections.singletonMap("user_id", loginUser.getId()))).thenReturn(getDataSourceList()); + Mockito.when(dataSourceMapper.selectByMap(Collections.singletonMap("user_id", loginUser.getId()))) + .thenReturn(getDataSourceList()); result = dataSourceService.unauthDatasource(loginUser, userId); logger.info(result.toString()); dataSources = (List) result.get(Constants.DATA_LIST); @@ -308,14 +304,14 @@ public class DataSourceServiceTest { loginUser.setUserType(UserType.GENERAL_USER); Set dataSourceIds = new HashSet<>(); dataSourceIds.add(1); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.DATASOURCE, null, loginUser.getId(), null, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.DATASOURCE, null, 0, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.DATASOURCE, loginUser.getId(), dataSourceServiceLogger)).thenReturn(dataSourceIds); + Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.DATASOURCE, + loginUser.getId(), dataSourceServiceLogger)).thenReturn(dataSourceIds); DataSource dataSource = new DataSource(); dataSource.setType(DbType.MYSQL); Mockito.when(dataSourceMapper.selectBatchIds(dataSourceIds)).thenReturn(Collections.singletonList(dataSource)); - Map map = dataSourceService.queryDataSourceList(loginUser, DbType.MYSQL.ordinal(),Constants.TEST_FLAG_NO); + Map map = + dataSourceService.queryDataSourceList(loginUser, DbType.MYSQL.ordinal(), Constants.TEST_FLAG_NO); Assert.assertEquals(Status.SUCCESS, map.get(Constants.STATUS)); } @@ -324,18 +320,18 @@ public class DataSourceServiceTest { User loginUser = new User(); loginUser.setUserType(UserType.GENERAL_USER); String dataSourceName = "dataSource1"; - PowerMockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(getDataSourceList()); + Mockito.when(dataSourceMapper.queryDataSourceByName(dataSourceName)).thenReturn(getDataSourceList()); Result result = dataSourceService.verifyDataSourceName(dataSourceName); Assert.assertEquals(Status.DATASOURCE_EXIST.getMsg(), result.getMsg()); } @Test public void queryDataSourceTest() { - PowerMockito.when(dataSourceMapper.selectById(Mockito.anyInt())).thenReturn(null); + Mockito.when(dataSourceMapper.selectById(Mockito.anyInt())).thenReturn(null); Map result = dataSourceService.queryDataSource(Mockito.anyInt()); Assert.assertEquals(((Status) result.get(Constants.STATUS)).getCode(), Status.RESOURCE_NOT_EXIST.getCode()); - PowerMockito.when(dataSourceMapper.selectById(Mockito.anyInt())).thenReturn(getOracleDataSource()); + Mockito.when(dataSourceMapper.selectById(Mockito.anyInt())).thenReturn(getOracleDataSource()); result = dataSourceService.queryDataSource(Mockito.anyInt()); Assert.assertEquals(((Status) result.get(Constants.STATUS)).getCode(), Status.SUCCESS.getCode()); } @@ -358,8 +354,9 @@ public class DataSourceServiceTest { dataSource.setName("test"); dataSource.setNote("Note"); dataSource.setType(DbType.ORACLE); - dataSource.setConnectionParams("{\"connectType\":\"ORACLE_SID\",\"address\":\"jdbc:oracle:thin:@192.168.xx.xx:49161\",\"database\":\"XE\"," - + "\"jdbcUrl\":\"jdbc:oracle:thin:@192.168.xx.xx:49161/XE\",\"user\":\"system\",\"password\":\"oracle\"}"); + dataSource.setConnectionParams( + "{\"connectType\":\"ORACLE_SID\",\"address\":\"jdbc:oracle:thin:@192.168.xx.xx:49161\",\"database\":\"XE\"," + + "\"jdbcUrl\":\"jdbc:oracle:thin:@192.168.xx.xx:49161/XE\",\"user\":\"system\",\"password\":\"oracle\"}"); return dataSource; } @@ -370,8 +367,9 @@ public class DataSourceServiceTest { dataSource.setName("test"); dataSource.setNote("Note"); dataSource.setType(DbType.ORACLE); - dataSource.setConnectionParams("{\"connectType\":\"ORACLE_SID\",\"address\":\"jdbc:oracle:thin:@192.168.xx.xx:49161\",\"database\":\"XE\"," - + "\"jdbcUrl\":\"jdbc:oracle:thin:@192.168.xx.xx:49161/XE\",\"user\":\"system\",\"password\":\"oracle\"}"); + dataSource.setConnectionParams( + "{\"connectType\":\"ORACLE_SID\",\"address\":\"jdbc:oracle:thin:@192.168.xx.xx:49161\",\"database\":\"XE\"," + + "\"jdbcUrl\":\"jdbc:oracle:thin:@192.168.xx.xx:49161/XE\",\"user\":\"system\",\"password\":\"oracle\"}"); return dataSource; } @@ -387,14 +385,13 @@ public class DataSourceServiceTest { oracleDatasourceParamDTO.setConnectType(DbConnectType.ORACLE_SERVICE_NAME); ConnectionParam connectionParam = DataSourceUtils.buildConnectionParams(oracleDatasourceParamDTO); - 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\"}"; + 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)); - PowerMockito.mockStatic(CommonUtils.class); - PowerMockito.mockStatic(PasswordUtils.class); - PowerMockito.when(CommonUtils.getKerberosStartupState()).thenReturn(true); - PowerMockito.when(PasswordUtils.encodePassword(Mockito.anyString())).thenReturn("test"); + Mockito.mockStatic(CommonUtils.class); + Mockito.when(CommonUtils.getKerberosStartupState()).thenReturn(true); HiveDataSourceParamDTO hiveDataSourceParamDTO = new HiveDataSourceParamDTO(); hiveDataSourceParamDTO.setHost("192.168.9.1"); hiveDataSourceParamDTO.setPort(10000); @@ -407,42 +404,48 @@ public class DataSourceServiceTest { hiveDataSourceParamDTO.setLoginUserKeytabUsername("test2/hdfs-mycluster@ESZ.COM"); connectionParam = DataSourceUtils.buildConnectionParams(hiveDataSourceParamDTO); - expected = "{\"user\":\"test\",\"password\":\"test\",\"address\":\"jdbc:hive2://192.168.9.1:10000\",\"database\":\"im\"," - + "\"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\"}"; + expected = + "{\"user\":\"test\",\"password\":\"test\",\"address\":\"jdbc:hive2://192.168.9.1:10000\",\"database\":\"im\"," + + "\"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)); } @Test public void buildParameterWithDecodePassword() { - PropertyUtils.setValue(Constants.DATASOURCE_ENCRYPTION_ENABLE, "true"); - Map other = new HashMap<>(); - other.put("autoDeserialize", "yes"); - other.put("allowUrlInLocalInfile", "true"); + try (MockedStatic mockedStaticPropertyUtils = Mockito.mockStatic(PropertyUtils.class)) { + mockedStaticPropertyUtils + .when(() -> PropertyUtils.getBoolean(Constants.DATASOURCE_ENCRYPTION_ENABLE, false)) + .thenReturn(true); + Map other = new HashMap<>(); + other.put("autoDeserialize", "yes"); + other.put("allowUrlInLocalInfile", "true"); + MySQLDataSourceParamDTO mysqlDatasourceParamDTO = new MySQLDataSourceParamDTO(); + mysqlDatasourceParamDTO.setHost("192.168.9.1"); + mysqlDatasourceParamDTO.setPort(1521); + mysqlDatasourceParamDTO.setDatabase("im"); + mysqlDatasourceParamDTO.setUserName("test"); + mysqlDatasourceParamDTO.setPassword("123456"); + mysqlDatasourceParamDTO.setOther(other); + ConnectionParam connectionParam = DataSourceUtils.buildConnectionParams(mysqlDatasourceParamDTO); + 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)); + } + MySQLDataSourceParamDTO mysqlDatasourceParamDTO = new MySQLDataSourceParamDTO(); mysqlDatasourceParamDTO.setHost("192.168.9.1"); mysqlDatasourceParamDTO.setPort(1521); mysqlDatasourceParamDTO.setDatabase("im"); mysqlDatasourceParamDTO.setUserName("test"); mysqlDatasourceParamDTO.setPassword("123456"); - mysqlDatasourceParamDTO.setOther(other); ConnectionParam connectionParam = DataSourceUtils.buildConnectionParams(mysqlDatasourceParamDTO); - String expected = "{\"user\":\"test\",\"password\":\"IUAjJCVeJipNVEl6TkRVMg==\",\"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)); - - PropertyUtils.setValue(Constants.DATASOURCE_ENCRYPTION_ENABLE, "false"); - mysqlDatasourceParamDTO = new MySQLDataSourceParamDTO(); - mysqlDatasourceParamDTO.setHost("192.168.9.1"); - mysqlDatasourceParamDTO.setPort(1521); - mysqlDatasourceParamDTO.setDatabase("im"); - mysqlDatasourceParamDTO.setUserName("test"); - mysqlDatasourceParamDTO.setPassword("123456"); - connectionParam = DataSourceUtils.buildConnectionParams(mysqlDatasourceParamDTO); - 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\"}"; + 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)); } @@ -478,16 +481,15 @@ public class DataSourceServiceTest { postgreSqlDatasourceParam.setPassword(""); ConnectionParam connectionParam = DataSourceUtils.buildConnectionParams(postgreSqlDatasourceParam); - PowerMockito.mockStatic(DataSourceUtils.class); - PowerMockito.mockStatic(DataSourceClientProvider.class); - DataSourceClientProvider clientProvider = PowerMockito.mock(DataSourceClientProvider.class); - PowerMockito.when(DataSourceClientProvider.getInstance()).thenReturn(clientProvider); + Mockito.mockStatic(DataSourceClientProvider.class); + DataSourceClientProvider clientProvider = Mockito.mock(DataSourceClientProvider.class); + Mockito.when(DataSourceClientProvider.getInstance()).thenReturn(clientProvider); Result result = dataSourceService.checkConnection(dataSourceType, connectionParam); Assert.assertEquals(Status.CONNECTION_TEST_FAILURE.getCode(), result.getCode().intValue()); - Connection connection = PowerMockito.mock(Connection.class); - PowerMockito.when(clientProvider.getConnection(Mockito.any(), Mockito.any())).thenReturn(connection); + 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()); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java index 1391ee0857..6fc0dd5ebb 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/LoggerServiceTest.java @@ -45,7 +45,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,7 +52,6 @@ import org.slf4j.LoggerFactory; * logger service test */ @RunWith(MockitoJUnitRunner.class) -@PrepareForTest({LoggerServiceImpl.class}) public class LoggerServiceTest { private static final Logger logger = LoggerFactory.getLogger(LoggerServiceTest.class); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java index fd394a2c0f..e170256002 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/ResourcesServiceTest.java @@ -17,10 +17,7 @@ package org.apache.dolphinscheduler.api.service; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; import org.apache.dolphinscheduler.api.constants.ApiFuncIdentificationConstant; import org.apache.dolphinscheduler.api.enums.Status; @@ -30,11 +27,15 @@ import org.apache.dolphinscheduler.api.service.impl.ResourcesServiceImpl; 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.*; +import org.apache.dolphinscheduler.common.enums.AuthorizationType; +import org.apache.dolphinscheduler.common.enums.UserType; import org.apache.dolphinscheduler.common.storage.StorageOperate; import org.apache.dolphinscheduler.common.utils.FileUtils; import org.apache.dolphinscheduler.common.utils.PropertyUtils; -import org.apache.dolphinscheduler.dao.entity.*; +import org.apache.dolphinscheduler.dao.entity.Resource; +import org.apache.dolphinscheduler.dao.entity.Tenant; +import org.apache.dolphinscheduler.dao.entity.UdfFunc; +import org.apache.dolphinscheduler.dao.entity.User; import org.apache.dolphinscheduler.dao.mapper.ProcessDefinitionMapper; import org.apache.dolphinscheduler.dao.mapper.ResourceMapper; import org.apache.dolphinscheduler.dao.mapper.ResourceUserMapper; @@ -56,17 +57,16 @@ import java.util.Map; import java.util.Random; import java.util.Set; +import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.MockedStatic; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.mock.web.MockMultipartFile; @@ -78,11 +78,7 @@ import com.google.common.io.Files; /** * resources service test */ -@RunWith(PowerMockRunner.class) -@PowerMockIgnore({"sun.security.*", "javax.net.*"}) -@PrepareForTest({PropertyUtils.class, - FileUtils.class, org.apache.dolphinscheduler.api.utils.FileUtils.class, - Files.class}) +@RunWith(MockitoJUnitRunner.class) public class ResourcesServiceTest { private static final Logger logger = LoggerFactory.getLogger(ResourcesServiceTest.class); @@ -118,142 +114,153 @@ public class ResourcesServiceTest { private static final Logger resourceLogger = LoggerFactory.getLogger(ResourcesServiceImpl.class); + private MockedStatic mockedStaticFileUtils; + + private MockedStatic mockedStaticFiles; + + private MockedStatic mockedStaticDolphinschedulerFileUtils; + + private MockedStatic mockedStaticPropertyUtils; + @Before public void setUp() { -// PowerMockito.mockStatic(HadoopUtils.class); - PowerMockito.mockStatic(FileUtils.class); - PowerMockito.mockStatic(Files.class); - PowerMockito.mockStatic(org.apache.dolphinscheduler.api.utils.FileUtils.class); - try { - // new HadoopUtils - // PowerMockito.whenNew(HadoopUtils.class).withNoArguments().thenReturn(hadoopUtils); - } catch (Exception e) { - e.printStackTrace(); - } - // PowerMockito.when(HadoopUtils.getInstance()).thenReturn(hadoopUtils); - PowerMockito.mockStatic(PropertyUtils.class); + mockedStaticFileUtils = Mockito.mockStatic(FileUtils.class); + mockedStaticFiles = Mockito.mockStatic(Files.class); + mockedStaticDolphinschedulerFileUtils = + Mockito.mockStatic(org.apache.dolphinscheduler.api.utils.FileUtils.class); + + mockedStaticPropertyUtils = Mockito.mockStatic(PropertyUtils.class); + } + + @After + public void after() { + mockedStaticFileUtils.close(); + mockedStaticFiles.close(); + mockedStaticDolphinschedulerFileUtils.close(); + mockedStaticPropertyUtils.close(); } @Test public void testCreateResource() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_UPLOAD, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); User user = new User(); user.setId(1); user.setUserType(UserType.GENERAL_USER); - //CURRENT_LOGIN_USER_TENANT_NOT_EXIST + // CURRENT_LOGIN_USER_TENANT_NOT_EXIST MockMultipartFile mockMultipartFile = new MockMultipartFile("test.pdf", "test.pdf", "pdf", "test".getBytes()); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); Mockito.when(tenantMapper.queryById(1)).thenReturn(null); Result result = resourcesService.createResource(user, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, mockMultipartFile, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); - //set tenant for user + // set tenant for user user.setTenantId(1); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - //HDFS_NOT_STARTUP - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + // HDFS_NOT_STARTUP + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); result = resourcesService.createResource(user, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, null, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); - //RESOURCE_FILE_IS_EMPTY + // RESOURCE_FILE_IS_EMPTY mockMultipartFile = new MockMultipartFile("test.pdf", "".getBytes()); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); result = resourcesService.createResource(user, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, mockMultipartFile, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_FILE_IS_EMPTY.getMsg(), result.getMsg()); - //RESOURCE_SUFFIX_FORBID_CHANGE + // RESOURCE_SUFFIX_FORBID_CHANGE mockMultipartFile = new MockMultipartFile("test.pdf", "test.pdf", "pdf", "test".getBytes()); - PowerMockito.when(Files.getFileExtension("test.pdf")).thenReturn("pdf"); - PowerMockito.when(Files.getFileExtension("ResourcesServiceTest.jar")).thenReturn("jar"); + Mockito.when(Files.getFileExtension("test.pdf")).thenReturn("pdf"); + Mockito.when(Files.getFileExtension("ResourcesServiceTest.jar")).thenReturn("jar"); result = resourcesService.createResource(user, "ResourcesServiceTest.jar", "ResourcesServiceTest", ResourceType.FILE, mockMultipartFile, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_SUFFIX_FORBID_CHANGE.getMsg(), result.getMsg()); - //UDF_RESOURCE_SUFFIX_NOT_JAR - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + // UDF_RESOURCE_SUFFIX_NOT_JAR + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.UDF_UPLOAD, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); mockMultipartFile = new MockMultipartFile("ResourcesServiceTest.pdf", "ResourcesServiceTest.pdf", "pdf", "test".getBytes()); - PowerMockito.when(Files.getFileExtension("ResourcesServiceTest.pdf")).thenReturn("pdf"); + Mockito.when(Files.getFileExtension("ResourcesServiceTest.pdf")).thenReturn("pdf"); result = resourcesService.createResource(user, "ResourcesServiceTest.pdf", "ResourcesServiceTest", ResourceType.UDF, mockMultipartFile, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.UDF_RESOURCE_SUFFIX_NOT_JAR.getMsg(), result.getMsg()); - //FULL_FILE_NAME_TOO_LONG - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + // FULL_FILE_NAME_TOO_LONG + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_UPLOAD, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); String tooLongFileName = getRandomStringWithLength(Constants.RESOURCE_FULL_NAME_MAX_LENGTH) + ".pdf"; mockMultipartFile = new MockMultipartFile(tooLongFileName, tooLongFileName, "pdf", "test".getBytes()); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); - PowerMockito.when(Files.getFileExtension(tooLongFileName)).thenReturn("pdf"); - result = resourcesService.createResource(user, tooLongFileName, tooLongFileName, ResourceType.FILE, mockMultipartFile, -1, "/"); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(Files.getFileExtension(tooLongFileName)).thenReturn("pdf"); + result = resourcesService.createResource(user, tooLongFileName, tooLongFileName, ResourceType.FILE, + mockMultipartFile, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_FULL_NAME_TOO_LONG_ERROR.getMsg(), result.getMsg()); } @Test public void testCreateDirecotry() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FOLDER_ONLINE_CREATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); User user = new User(); user.setId(1); user.setUserType(UserType.GENERAL_USER); - //HDFS_NOT_STARTUP + // HDFS_NOT_STARTUP Result result = resourcesService.createDirectory(user, "directoryTest", "directory test", ResourceType.FILE, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); - //PARENT_RESOURCE_NOT_EXIST + // PARENT_RESOURCE_NOT_EXIST user.setId(1); user.setTenantId(1); - Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); Mockito.when(resourcesMapper.selectById(Mockito.anyInt())).thenReturn(null); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FOLDER_ONLINE_CREATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_RENAME, serviceLogger)).thenReturn(true); result = resourcesService.createDirectory(user, "directoryTest", "directory test", ResourceType.FILE, 1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.PARENT_RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); - //RESOURCE_EXIST - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + // RESOURCE_EXIST + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); Mockito.when(resourcesMapper.existResource("/directoryTest", 0)).thenReturn(true); result = resourcesService.createDirectory(user, "directoryTest", "directory test", ResourceType.FILE, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); - //Description_Lingth_ERROR - result = resourcesService.createDirectory(user, "directoryTest", "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", + // Description_Lingth_ERROR + result = resourcesService.createDirectory(user, "directoryTest", + "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111", ResourceType.FILE, -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.DESCRIPTION_TOO_LONG_ERROR.getMsg(), result.getMsg()); @@ -262,52 +269,54 @@ public class ResourcesServiceTest { @Test public void testUpdateResource() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); User user = new User(); user.setId(1); user.setUserType(UserType.GENERAL_USER); - //HDFS_NOT_STARTUP - Result result = resourcesService.updateResource(user, 1, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, null); + // HDFS_NOT_STARTUP + Result result = resourcesService.updateResource(user, 1, "ResourcesServiceTest", "ResourcesServiceTest", + ResourceType.FILE, null); logger.info(result.toString()); Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); - //RESOURCE_NOT_EXIST - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + // RESOURCE_NOT_EXIST + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{0}, 1, serviceLogger)).thenReturn(true); Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); - result = resourcesService.updateResource(user, 0, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, null); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + result = resourcesService.updateResource(user, 0, "ResourcesServiceTest", "ResourcesServiceTest", + ResourceType.FILE, null); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); - //USER_NO_OPERATION_PERM + // USER_NO_OPERATION_PERM user.setId(2); user.setUserType(UserType.GENERAL_USER); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 2, ApiFuncIdentificationConstant.FILE_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, 2, serviceLogger)).thenReturn(false); result = resourcesService.updateResource(user, 1, "ResourcesServiceTest", "ResourcesServiceTest", ResourceType.FILE, null); logger.info(result.toString()); Assert.assertEquals(Status.NO_CURRENT_OPERATING_PERMISSION.getMsg(), result.getMsg()); - //RESOURCE_NOT_EXIST + // RESOURCE_NOT_EXIST user.setId(1); Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - PowerMockito.when(storageOperate.getFileName(Mockito.any(), Mockito.any(), Mockito.anyString())).thenReturn("test1"); + Mockito.when(storageOperate.getFileName(Mockito.any(), Mockito.any(), Mockito.anyString())).thenReturn("test1"); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF_FILE, null, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF_FILE, null, 1, ApiFuncIdentificationConstant.UDF_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF_FILE, new Object[]{1}, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF_FILE, new Object[]{1}, 1, serviceLogger)).thenReturn(true); try { Mockito.when(storageOperate.exists(Mockito.any(), Mockito.any())).thenReturn(false); @@ -318,9 +327,8 @@ public class ResourcesServiceTest { ResourceType.UDF, null); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); - //SUCCESS + // SUCCESS user.setId(1); - Mockito.when(userMapper.queryDetailsById(1)).thenReturn(getUser()); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); try { Mockito.when(storageOperate.exists(Mockito.any(), Mockito.any())).thenReturn(true); @@ -328,47 +336,43 @@ public class ResourcesServiceTest { logger.error(e.getMessage(), e); } - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + new Object[]{1}, 1, serviceLogger)).thenReturn(true); result = resourcesService.updateResource(user, 1, "ResourcesServiceTest.jar", "ResourcesServiceTest", ResourceType.FILE, null); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); - //RESOURCE_EXIST + // RESOURCE_EXIST Mockito.when(resourcesMapper.existResource("/ResourcesServiceTest1.jar", 0)).thenReturn(true); - result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", ResourceType.FILE, null); + result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", + ResourceType.FILE, null); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); - //USER_NOT_EXIST - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, - 1, ApiFuncIdentificationConstant.UDF_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, - 1, serviceLogger)).thenReturn(true); + // USER_NOT_EXIST + Mockito.when(userMapper.selectById(Mockito.anyInt())).thenReturn(null); - result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", ResourceType.UDF, null); + result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", + ResourceType.UDF, null); logger.info(result.toString()); Assert.assertTrue(Status.USER_NOT_EXIST.getCode() == result.getCode()); - //TENANT_NOT_EXIST + // TENANT_NOT_EXIST Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); Mockito.when(tenantMapper.queryById(Mockito.anyInt())).thenReturn(null); - result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", ResourceType.UDF, null); + result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest", + ResourceType.UDF, null); logger.info(result.toString()); Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); - //SUCCESS + // SUCCESS Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - PowerMockito.when(storageOperate.getResourceFileName(Mockito.any(), Mockito.any())).thenReturn("test"); - try { - // PowerMockito.when(HadoopUtils.getInstance().copy(Mockito.anyString(), Mockito.anyString(), true, true)).thenReturn(true); - } catch (Exception e) { - logger.error(e.getMessage(), e); - } - result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest1.jar", ResourceType.UDF, null); + result = resourcesService.updateResource(user, 1, "ResourcesServiceTest1.jar", "ResourcesServiceTest1.jar", + ResourceType.UDF, null); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); @@ -383,14 +387,12 @@ public class ResourcesServiceTest { resourcePage.setTotal(1); resourcePage.setRecords(getResourceList()); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, - 1, ApiFuncIdentificationConstant.FILE_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, - 0, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.RESOURCE_FILE_ID, + Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.RESOURCE_FILE_ID, 1, resourceLogger)).thenReturn(getSetIds()); - Mockito.when(resourcesMapper.queryResourcePaging(Mockito.any(Page.class), eq(-1), eq(0), eq("test"), Mockito.any())).thenReturn(resourcePage); + Mockito.when( + resourcesMapper.queryResourcePaging(Mockito.any(Page.class), eq(-1), eq(0), eq("test"), Mockito.any())) + .thenReturn(resourcePage); Result result = resourcesService.queryResourceListPaging(loginUser, -1, ResourceType.FILE, "test", 1, 10); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS.getCode(), (int) result.getCode()); @@ -405,7 +407,8 @@ public class ResourcesServiceTest { loginUser.setId(0); loginUser.setUserType(UserType.ADMIN_USER); - PowerMockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.RESOURCE_FILE_ID, 0, resourceLogger)).thenReturn(getSetIds()); + Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.RESOURCE_FILE_ID, + 0, resourceLogger)).thenReturn(getSetIds()); Mockito.when(resourcesMapper.selectBatchIds(Mockito.anySet())).thenReturn(getResourceList()); Map result = resourcesService.queryResourceList(loginUser, ResourceType.FILE); @@ -415,9 +418,12 @@ public class ResourcesServiceTest { Assert.assertTrue(CollectionUtils.isNotEmpty(resourceList)); // test udf - PowerMockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.UDF_FILE, 0, resourceLogger)).thenReturn(getSetIds()); - Mockito.when(resourcesMapper.selectBatchIds(Mockito.anySet())).thenReturn(Arrays.asList(getResource(11, ResourceType.UDF), - getResource(10, ResourceType.UDF), getResource(9, ResourceType.UDF), getResource(8, ResourceType.UDF))); + Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.UDF_FILE, 0, + resourceLogger)).thenReturn(getSetIds()); + Mockito.when(resourcesMapper.selectBatchIds(Mockito.anySet())) + .thenReturn(Arrays.asList(getResource(11, ResourceType.UDF), + getResource(10, ResourceType.UDF), getResource(9, ResourceType.UDF), + getResource(8, ResourceType.UDF))); loginUser.setUserType(UserType.GENERAL_USER); result = resourcesService.queryResourceList(loginUser, ResourceType.UDF); @@ -433,13 +439,14 @@ public class ResourcesServiceTest { User loginUser = new User(); loginUser.setId(0); loginUser.setUserType(UserType.GENERAL_USER); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 0, ApiFuncIdentificationConstant.FILE_DELETE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + new Object[]{1}, 0, serviceLogger)).thenReturn(true); try { // HDFS_NOT_STARTUP @@ -447,14 +454,15 @@ public class ResourcesServiceTest { logger.info(result.toString()); Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); - //RESOURCE_NOT_EXIST - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + // RESOURCE_NOT_EXIST + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, - 0, ApiFuncIdentificationConstant.FILE_DELETE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{2}, - 0, serviceLogger)).thenReturn(true); + Mockito.when( + resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + 0, ApiFuncIdentificationConstant.FILE_DELETE, serviceLogger)) + .thenReturn(true); + result = resourcesService.delete(loginUser, 2); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); @@ -464,21 +472,23 @@ public class ResourcesServiceTest { logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); - //TENANT_NOT_EXIST + // TENANT_NOT_EXIST loginUser.setUserType(UserType.ADMIN_USER); loginUser.setTenantId(2); Mockito.when(userMapper.selectById(Mockito.anyInt())).thenReturn(loginUser); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, - 0, ApiFuncIdentificationConstant.FILE_DELETE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, + Mockito.when( + resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + 0, ApiFuncIdentificationConstant.FILE_DELETE, serviceLogger)) + .thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + new Object[]{1}, 0, serviceLogger)).thenReturn(true); result = resourcesService.delete(loginUser, 1); logger.info(result.toString()); Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); - //SUCCESS + // SUCCESS loginUser.setTenantId(1); - Mockito.when(storageOperate.delete(Mockito.any(), Mockito.anyString(), Mockito.anyBoolean())).thenReturn(true); Mockito.when(processDefinitionMapper.listResources()).thenReturn(getResources()); Mockito.when(resourcesMapper.deleteIds(Mockito.any())).thenReturn(1); Mockito.when(resourceUserMapper.deleteResourceUserArray(Mockito.anyInt(), Mockito.any())).thenReturn(1); @@ -495,9 +505,9 @@ public class ResourcesServiceTest { @Test public void testVerifyResourceName() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_RENAME, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); User user = new User(); user.setId(1); @@ -507,31 +517,22 @@ public class ResourcesServiceTest { logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_EXIST.getMsg(), result.getMsg()); - //TENANT_NOT_EXIST + // TENANT_NOT_EXIST Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); String unExistFullName = "/test.jar"; - try { - Mockito.when(storageOperate.exists(Mockito.anyString(), eq(unExistFullName))).thenReturn(false); - } catch (IOException e) { - logger.error("hadoop error", e); - } + result = resourcesService.verifyResourceName("/test.jar", ResourceType.FILE, user); logger.info(result.toString()); Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); - //RESOURCE_FILE_EXIST + // RESOURCE_FILE_EXIST user.setTenantId(1); - try { - Mockito.when(storageOperate.exists(Mockito.any(), eq("test"))).thenReturn(true); - } catch (IOException e) { - logger.error("hadoop error", e); - } - PowerMockito.when(storageOperate.getResourceFileName("123", "test1")).thenReturn("test"); + result = resourcesService.verifyResourceName("/ResourcesServiceTest.jar", ResourceType.FILE, user); logger.info(result.toString()); Assert.assertTrue(Status.RESOURCE_EXIST.getCode() == result.getCode()); - //SUCCESS + // SUCCESS result = resourcesService.verifyResourceName("test2", ResourceType.FILE, user); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); @@ -541,65 +542,61 @@ public class ResourcesServiceTest { @Test public void testReadResource() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + new Object[]{1}, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); - //HDFS_NOT_STARTUP + // HDFS_NOT_STARTUP Result result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); - //RESOURCE_NOT_EXIST + // RESOURCE_NOT_EXIST Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{2}, - 1, serviceLogger)).thenReturn(true); + result = resourcesService.readResource(getUser(), 2, 1, 10); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); - //RESOURCE_SUFFIX_NOT_SUPPORT_VIEW - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + // RESOURCE_SUFFIX_NOT_SUPPORT_VIEW + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + new Object[]{1}, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("class"); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("class"); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); - //USER_NOT_EXIST - PowerMockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("jar"); - PowerMockito.when(Files.getFileExtension("ResourcesServiceTest.jar")).thenReturn("jar"); + // USER_NOT_EXIST + Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("jar"); + Mockito.when(Files.getFileExtension("ResourcesServiceTest.jar")).thenReturn("jar"); result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); Assert.assertEquals(Status.USER_NOT_EXIST.getCode(), (int) result.getCode()); - //TENANT_NOT_EXIST + // TENANT_NOT_EXIST Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); Assert.assertEquals(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getMsg(), result.getMsg()); - //RESOURCE_FILE_NOT_EXIST + // RESOURCE_FILE_NOT_EXIST Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - try { - Mockito.when(storageOperate.exists(Mockito.any(), Mockito.anyString())).thenReturn(false); - } catch (IOException e) { - logger.error("hadoop error", e); - } + result = resourcesService.readResource(getUser(), 1, 1, 10); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_FILE_NOT_EXIST.getCode(), (int) result.getCode()); - - //SUCCESS + // SUCCESS try { Mockito.when(storageOperate.exists(Mockito.any(), Mockito.any())).thenReturn(true); Mockito.when(storageOperate.vimFile(Mockito.any(), Mockito.any(), eq(1), eq(10))).thenReturn(getContent()); @@ -615,47 +612,49 @@ public class ResourcesServiceTest { @Test public void testOnlineCreateResource() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_ONLINE_CREATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); - PowerMockito.when(storageOperate.getResourceFileName(Mockito.anyString(), eq("hdfsdDir"))).thenReturn("hdfsDir"); - PowerMockito.when(storageOperate.getUdfDir("udfDir")).thenReturn("udfDir"); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); User user = getUser(); user.setId(1); - //HDFS_NOT_STARTUP - Result result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, "/"); + // HDFS_NOT_STARTUP + Result result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", + -1, "/"); logger.info(result.toString()); Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); - //RESOURCE_SUFFIX_NOT_SUPPORT_VIEW - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); - PowerMockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("class"); - result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, "/"); + // RESOURCE_SUFFIX_NOT_SUPPORT_VIEW + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("class"); + result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, + "/"); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); - //RuntimeException + // RuntimeException try { - PowerMockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("jar"); + Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("jar"); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, "/"); + result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", + -1, "/"); } catch (RuntimeException ex) { logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), ex.getMessage()); } - //SUCCESS - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + // SUCCESS + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_RENAME, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); Mockito.when(FileUtils.getUploadFilename(Mockito.anyString(), Mockito.anyString())).thenReturn("test"); - PowerMockito.when(FileUtils.writeContent2File(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, "/"); + Mockito.when(FileUtils.writeContent2File(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + result = resourcesService.onlineCreateResource(user, ResourceType.FILE, "test", "jar", "desc", "content", -1, + "/"); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); @@ -682,38 +681,36 @@ public class ResourcesServiceTest { Resource dir2 = new Resource(); dir2.setFullName(resourceDir); dir2.setUserId(user.getId()); - Mockito.when(resourcesMapper.queryResource(dir1.getFullName(), ResourceType.FILE.ordinal())).thenReturn(Collections.singletonList(dir1)); + Mockito.when(resourcesMapper.queryResource(dir1.getFullName(), ResourceType.FILE.ordinal())) + .thenReturn(Collections.singletonList(dir1)); Mockito.when(resourcesMapper.queryResource(resourceDir, ResourceType.FILE.ordinal())).thenReturn(null); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck( - AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck( - AuthorizationType.RESOURCE_FILE_ID, new Object[]{dir1.getId()}, 1, serviceLogger)).thenReturn(true); Tenant tenant = getTenant(); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck( - AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FOLDER_ONLINE_CREATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck( + Mockito.when(resourcePermissionCheckService.operationPermissionCheck( + AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FOLDER_ONLINE_CREATE, + serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck( AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); try { - PowerMockito.when(storageOperate.mkdir(tenant.getTenantCode(), null)).thenReturn(true); + Mockito.when(storageOperate.mkdir(tenant.getTenantCode(), null)).thenReturn(true); } catch (IOException e) { logger.error("storage error", e); } - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck( - AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_ONLINE_CREATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck( + Mockito.when(resourcePermissionCheckService.operationPermissionCheck( + AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_ONLINE_CREATE, + serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck( AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck( - AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_RENAME, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck( + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck( + AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_RENAME, serviceLogger)) + .thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck( AuthorizationType.RESOURCE_FILE_ID, null, 1, serviceLogger)).thenReturn(true); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - Mockito.when(resourcesMapper.selectById(dir1.getId())).thenReturn(dir1); - Mockito.when(resourcesMapper.selectById(dir2.getId())).thenReturn(dir2); Mockito.when(FileUtils.getUploadFilename(Mockito.anyString(), Mockito.anyString())).thenReturn("test"); - PowerMockito.when(FileUtils.writeContent2File(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + Mockito.when(FileUtils.writeContent2File(Mockito.anyString(), Mockito.anyString())).thenReturn(true); Result result = resourcesService.onlineCreateOrUpdateResourceWithDir(user, fullName, desc, content); Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); @@ -729,67 +726,69 @@ public class ResourcesServiceTest { file.setId(1); Mockito.when(resourcesMapper.queryResource(file.getFullName(), ResourceType.FILE.ordinal())) .thenReturn(Collections.singletonList(file)); - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck( - AuthorizationType.RESOURCE_FILE_ID, null, user.getId(), ApiFuncIdentificationConstant.FILE_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck( - AuthorizationType.RESOURCE_FILE_ID, new Object[]{file.getId()}, user.getId(), serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck( + AuthorizationType.RESOURCE_FILE_ID, null, user.getId(), ApiFuncIdentificationConstant.FILE_VIEW, + serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck( + AuthorizationType.RESOURCE_FILE_ID, new Object[]{file.getId()}, user.getId(), serviceLogger)) + .thenReturn(true); Resource result = resourcesService.queryResourcesFileInfo(userName, file.getFullName()); Assert.assertEquals(file.getFullName(), result.getFullName()); } @Test public void testUpdateResourceContent() { - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); // HDFS_NOT_STARTUP - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + new Object[]{1}, 1, serviceLogger)).thenReturn(true); Result result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); Assert.assertEquals(Status.STORAGE_NOT_STARTUP.getMsg(), result.getMsg()); - //RESOURCE_NOT_EXIST - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + // RESOURCE_NOT_EXIST + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{2}, - 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); result = resourcesService.updateResourceContent(getUser(), 2, "content"); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); - //RESOURCE_SUFFIX_NOT_SUPPORT_VIEW - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + // RESOURCE_SUFFIX_NOT_SUPPORT_VIEW + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + new Object[]{1}, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); - PowerMockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("class"); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("class"); result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); Assert.assertEquals(Status.RESOURCE_SUFFIX_NOT_SUPPORT_VIEW.getMsg(), result.getMsg()); - //USER_NOT_EXIST - PowerMockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("jar"); - PowerMockito.when(Files.getFileExtension("ResourcesServiceTest.jar")).thenReturn("jar"); + // USER_NOT_EXIST + Mockito.when(FileUtils.getResourceViewSuffixes()).thenReturn("jar"); + Mockito.when(Files.getFileExtension("ResourcesServiceTest.jar")).thenReturn("jar"); result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); Assert.assertTrue(Status.USER_NOT_EXIST.getCode() == result.getCode()); - //TENANT_NOT_EXIST + // TENANT_NOT_EXIST Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); Assert.assertTrue(Status.CURRENT_LOGIN_USER_TENANT_NOT_EXIST.getCode() == result.getCode()); - //SUCCESS + // SUCCESS Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); Mockito.when(FileUtils.getUploadFilename(Mockito.anyString(), Mockito.anyString())).thenReturn("test"); - PowerMockito.when(FileUtils.writeContent2File(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + Mockito.when(FileUtils.writeContent2File(Mockito.anyString(), Mockito.anyString())).thenReturn(true); result = resourcesService.updateResourceContent(getUser(), 1, "content"); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); @@ -798,22 +797,24 @@ public class ResourcesServiceTest { @Test public void testDownloadResource() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.RESOURCE_FILE_ID, null, 1, ApiFuncIdentificationConstant.FILE_DOWNLOAD, serviceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, new Object[]{1}, + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.RESOURCE_FILE_ID, + new Object[]{1}, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); Mockito.when(userMapper.selectById(1)).thenReturn(getUser()); org.springframework.core.io.Resource resourceMock = Mockito.mock(org.springframework.core.io.Resource.class); try { - //resource null + // resource null org.springframework.core.io.Resource resource = resourcesService.downloadResource(getUser(), 1); Assert.assertNull(resource); Mockito.when(resourcesMapper.selectById(1)).thenReturn(getResource()); - PowerMockito.when(org.apache.dolphinscheduler.api.utils.FileUtils.file2Resource(Mockito.any())).thenReturn(resourceMock); + Mockito.when(org.apache.dolphinscheduler.api.utils.FileUtils.file2Resource(Mockito.any())) + .thenReturn(resourceMock); resource = resourcesService.downloadResource(getUser(), 1); Assert.assertNotNull(resource); } catch (Exception e) { @@ -862,9 +863,9 @@ public class ResourcesServiceTest { // test admin user List resIds = new ArrayList<>(); resIds.add(1); - Mockito.when(resourcePermissionCheckService.functionDisabled()).thenReturn(true); Mockito.when(resourcesMapper.queryResourceExceptUserId(userId)).thenReturn(getResourceList()); - Mockito.when(resourceUserMapper.queryResourcesIdListByUserIdAndPerm(Mockito.anyInt(), Mockito.anyInt())).thenReturn(resIds); + Mockito.when(resourceUserMapper.queryResourcesIdListByUserIdAndPerm(Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(resIds); Mockito.when(resourcesMapper.queryResourceListById(Mockito.any())).thenReturn(getSingleResourceList()); Map result = resourcesService.unauthorizedFile(user, userId); logger.info(result.toString()); @@ -902,7 +903,8 @@ public class ResourcesServiceTest { // test non-admin user user.setId(2); user.setUserType(UserType.GENERAL_USER); - Mockito.when(udfFunctionMapper.selectByMap(Collections.singletonMap("user_id", user.getId()))).thenReturn(getUdfFuncList()); + Mockito.when(udfFunctionMapper.selectByMap(Collections.singletonMap("user_id", user.getId()))) + .thenReturn(getUdfFuncList()); result = resourcesService.unauthorizedUDFFunction(user, userId); logger.info(result.toString()); Assert.assertEquals(Status.SUCCESS, result.get(Constants.STATUS)); @@ -948,7 +950,8 @@ public class ResourcesServiceTest { List resIds = new ArrayList<>(); resIds.add(1); Mockito.when(resourcePermissionCheckService.functionDisabled()).thenReturn(true); - Mockito.when(resourceUserMapper.queryResourcesIdListByUserIdAndPerm(Mockito.anyInt(), Mockito.anyInt())).thenReturn(resIds); + Mockito.when(resourceUserMapper.queryResourcesIdListByUserIdAndPerm(Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(resIds); Mockito.when(resourcesMapper.queryResourceListById(Mockito.any())).thenReturn(getResourceList()); Map result = resourcesService.authorizedFile(user, userId); logger.info(result.toString()); @@ -959,7 +962,8 @@ public class ResourcesServiceTest { // test non-admin user user.setId(2); user.setUserType(UserType.GENERAL_USER); - Mockito.when(resourceUserMapper.queryResourcesIdListByUserIdAndPerm(Mockito.anyInt(), Mockito.anyInt())).thenReturn(resIds); + Mockito.when(resourceUserMapper.queryResourcesIdListByUserIdAndPerm(Mockito.anyInt(), Mockito.anyInt())) + .thenReturn(resIds); Mockito.when(resourcesMapper.queryResourceListById(Mockito.any())).thenReturn(getResourceList()); result = resourcesService.authorizedFile(user, userId); logger.info(result.toString()); @@ -971,12 +975,10 @@ public class ResourcesServiceTest { @Test public void testCatFile() { - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); - //SUCCESS + // SUCCESS try { - Mockito.when(storageOperate.exists(Mockito.anyString(), Mockito.anyString())).thenReturn(true); - Mockito.when(storageOperate.vimFile(Mockito.anyString(), Mockito.anyString(), eq(1), eq(10))).thenReturn(getContent()); List list = storageOperate.vimFile(Mockito.any(), Mockito.anyString(), eq(1), eq(10)); Assert.assertNotNull(list); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SchedulerServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SchedulerServiceTest.java index 1e8b1a698c..5d65d96ea3 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SchedulerServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/SchedulerServiceTest.java @@ -28,7 +28,6 @@ import org.apache.dolphinscheduler.api.exceptions.ServiceException; import org.apache.dolphinscheduler.api.service.impl.SchedulerServiceImpl; import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.enums.ReleaseState; -import org.apache.dolphinscheduler.common.model.Server; import org.apache.dolphinscheduler.dao.entity.Environment; import org.apache.dolphinscheduler.dao.entity.ProcessDefinition; import org.apache.dolphinscheduler.dao.entity.Project; @@ -42,8 +41,6 @@ import org.apache.dolphinscheduler.dao.mapper.ScheduleMapper; import org.apache.dolphinscheduler.scheduler.api.SchedulerApi; import org.apache.dolphinscheduler.service.process.ProcessService; -import java.util.ArrayList; -import java.util.List; import java.util.Map; import org.junit.Assert; @@ -54,12 +51,12 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.junit.MockitoJUnitRunner; /** * scheduler service test */ -@RunWith(PowerMockRunner.class) +@RunWith(MockitoJUnitRunner.class) public class SchedulerServiceTest extends BaseServiceTestTool { @InjectMocks @@ -130,13 +127,9 @@ public class SchedulerServiceTest extends BaseServiceTestTool { schedule.setProcessDefinitionCode(1); schedule.setReleaseState(ReleaseState.OFFLINE); - List masterServers = new ArrayList<>(); - masterServers.add(new Server()); - Mockito.when(scheduleMapper.selectById(1)).thenReturn(schedule); Mockito.when(projectMapper.queryByCode(projectCode)).thenReturn(project); - Mockito.when(projectMapper.queryByName(projectName)).thenReturn(project); Mockito.when(processDefinitionMapper.queryByCode(1)).thenReturn(processDefinition); @@ -162,14 +155,10 @@ public class SchedulerServiceTest extends BaseServiceTestTool { Assert.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); processDefinition.setReleaseState(ReleaseState.ONLINE); - Mockito.when(processService.findProcessDefineById(1)).thenReturn(processDefinition); result = schedulerService.setScheduleState(user, project.getCode(), 1, ReleaseState.ONLINE); Assert.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); - // set master - Mockito.when(monitorService.getServerListFromRegistry(true)).thenReturn(masterServers); - // SUCCESS result = schedulerService.setScheduleState(user, project.getCode(), 1, ReleaseState.ONLINE); Assert.assertEquals(Status.PROCESS_DAG_IS_EMPTY, result.get(Constants.STATUS)); 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 0ff9d4c5de..2c0419474b 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 @@ -31,7 +31,6 @@ import org.apache.dolphinscheduler.api.utils.Result; import org.apache.dolphinscheduler.common.Constants; import org.apache.dolphinscheduler.common.enums.AuthorizationType; import org.apache.dolphinscheduler.common.enums.UserType; -import org.apache.dolphinscheduler.common.utils.PropertyUtils; import org.apache.dolphinscheduler.dao.entity.ProcessDefinition; import org.apache.dolphinscheduler.dao.entity.ProcessInstance; import org.apache.dolphinscheduler.dao.entity.Queue; @@ -59,7 +58,6 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -70,8 +68,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; * tenant service test */ @RunWith(MockitoJUnitRunner.class) -@PrepareForTest({PropertyUtils.class}) public class TenantServiceTest { + private static final Logger baseServiceLogger = LoggerFactory.getLogger(BaseServiceImpl.class); private static final Logger tenantServiceImplLogger = LoggerFactory.getLogger(TenantServiceImpl.class); @@ -106,27 +104,34 @@ public class TenantServiceTest { User loginUser = getLoginUser(); Mockito.when(tenantMapper.existTenant(tenantCode)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TENANT, null, loginUser.getId(), TENANT_CREATE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.TENANT, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TENANT, null, + loginUser.getId(), TENANT_CREATE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.TENANT, null, 0, + baseServiceLogger)).thenReturn(true); Map result; - //check exist + // check exist String emptyTenantCode = ""; - Throwable exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.createTenant(loginUser, emptyTenantCode, 1, tenantDesc)); + Throwable exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.createTenant(loginUser, emptyTenantCode, 1, tenantDesc)); String formatter = MessageFormat.format(Status.REQUEST_PARAMS_NOT_VALID_ERROR.getMsg(), emptyTenantCode); Assertions.assertEquals(formatter, exception.getMessage()); - //check tenant code too long - String longStr = "this_is_a_very_long_string_this_is_a_very_long_string_this_is_a_very_long_string_this_is_a_very_long_string"; - exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.createTenant(loginUser, longStr, 1, tenantDesc)); + // check tenant code too long + String longStr = + "this_is_a_very_long_string_this_is_a_very_long_string_this_is_a_very_long_string_this_is_a_very_long_string"; + exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.createTenant(loginUser, longStr, 1, tenantDesc)); Assert.assertEquals(Status.TENANT_FULL_NAME_TOO_LONG_ERROR.getMsg(), exception.getMessage()); - //check tenant code invalid - exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.createTenant(getLoginUser(), "%!1111", 1, tenantDesc)); + // check tenant code invalid + exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.createTenant(getLoginUser(), "%!1111", 1, tenantDesc)); Assert.assertEquals(Status.CHECK_OS_TENANT_CODE_ERROR.getMsg(), exception.getMessage()); - //check exist - exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.createTenant(loginUser, tenantCode, 1, tenantDesc)); + // check exist + exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.createTenant(loginUser, tenantCode, 1, tenantDesc)); formatter = MessageFormat.format(Status.OS_TENANT_CODE_EXIST.getMsg(), tenantCode); Assert.assertEquals(formatter, exception.getMessage()); @@ -140,7 +145,8 @@ public class TenantServiceTest { Mockito.when(tenantMapper.existTenant(tenantCode)).thenReturn(true); // tenantCode exist - Throwable exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.verifyTenantCode(getTenant().getTenantCode())); + Throwable exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.verifyTenantCode(getTenant().getTenantCode())); String expect = MessageFormat.format(Status.OS_TENANT_CODE_EXIST.getMsg(), getTenant().getTenantCode()); Assertions.assertEquals(expect, exception.getMessage()); @@ -157,7 +163,8 @@ public class TenantServiceTest { page.setTotal(1L); Set ids = new HashSet<>(); ids.add(1); - Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.TENANT, getLoginUser().getId(), tenantServiceImplLogger)).thenReturn(ids); + Mockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.TENANT, + getLoginUser().getId(), tenantServiceImplLogger)).thenReturn(ids); Mockito.when(tenantMapper.queryTenantPaging(Mockito.any(Page.class), Mockito.anyList(), Mockito.eq(tenantDesc))) .thenReturn(page); Result result = tenantService.queryTenantList(getLoginUser(), tenantDesc, 1, 10); @@ -169,12 +176,15 @@ public class TenantServiceTest { @Test public void testUpdateTenant() throws Exception { Mockito.when(tenantMapper.queryById(1)).thenReturn(getTenant()); - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TENANT, null, getLoginUser().getId(), TENANT_UPDATE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.TENANT, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TENANT, null, + getLoginUser().getId(), TENANT_UPDATE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.TENANT, null, 0, + baseServiceLogger)).thenReturn(true); Mockito.when(tenantMapper.updateById(getTenant())).thenReturn(1); // update not exists tenant - Throwable exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.updateTenant(getLoginUser(), 912222, tenantCode, 1, tenantDesc)); + Throwable exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.updateTenant(getLoginUser(), 912222, tenantCode, 1, tenantDesc)); Assertions.assertEquals(Status.TENANT_NOT_EXIST.getMsg(), exception.getMessage()); // success @@ -188,32 +198,38 @@ public class TenantServiceTest { @Test public void testDeleteTenantById() throws Exception { - Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TENANT, null, getLoginUser().getId(), TENANT_DELETE, baseServiceLogger)).thenReturn(true); - Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.TENANT, null, 0, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.TENANT, null, + getLoginUser().getId(), TENANT_DELETE, baseServiceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.TENANT, null, 0, + baseServiceLogger)).thenReturn(true); 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()); - //TENANT_NOT_EXIST - Throwable exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.deleteTenantById(getLoginUser(), 12)); + // TENANT_NOT_EXIST + Throwable exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.deleteTenantById(getLoginUser(), 12)); Assertions.assertEquals(Status.TENANT_NOT_EXIST.getMsg(), exception.getMessage()); - //DELETE_TENANT_BY_ID_FAIL - exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.deleteTenantById(getLoginUser(), 1)); + // DELETE_TENANT_BY_ID_FAIL + exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.deleteTenantById(getLoginUser(), 1)); String prefix = Status.DELETE_TENANT_BY_ID_FAIL.getMsg().substring(1, 5); Assertions.assertTrue(exception.getMessage().contains(prefix)); - //DELETE_TENANT_BY_ID_FAIL_DEFINES + // DELETE_TENANT_BY_ID_FAIL_DEFINES Mockito.when(tenantMapper.queryById(2)).thenReturn(getTenant(2)); - exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.deleteTenantById(getLoginUser(), 2)); + exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.deleteTenantById(getLoginUser(), 2)); prefix = Status.DELETE_TENANT_BY_ID_FAIL_DEFINES.getMsg().substring(1, 5); Assertions.assertTrue(exception.getMessage().contains(prefix)); - //DELETE_TENANT_BY_ID_FAIL_USERS + // DELETE_TENANT_BY_ID_FAIL_USERS Mockito.when(tenantMapper.queryById(3)).thenReturn(getTenant(3)); - exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.deleteTenantById(getLoginUser(), 3)); + exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.deleteTenantById(getLoginUser(), 3)); prefix = Status.DELETE_TENANT_BY_ID_FAIL_USERS.getMsg().substring(1, 5); Assertions.assertTrue(exception.getMessage().contains(prefix)); @@ -228,7 +244,8 @@ public class TenantServiceTest { public void testVerifyTenantCode() { Mockito.when(tenantMapper.existTenant(tenantCode)).thenReturn(true); // tenantCode exist - Throwable exception = Assertions.assertThrows(ServiceException.class, () -> tenantService.verifyTenantCode(getTenant().getTenantCode())); + Throwable exception = Assertions.assertThrows(ServiceException.class, + () -> tenantService.verifyTenantCode(getTenant().getTenantCode())); String expect = MessageFormat.format(Status.OS_TENANT_CODE_EXIST.getMsg(), getTenant().getTenantCode()); Assertions.assertEquals(expect, exception.getMessage()); diff --git a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UdfFuncServiceTest.java b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UdfFuncServiceTest.java index b96ab81abd..31145857d0 100644 --- a/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UdfFuncServiceTest.java +++ b/dolphinscheduler-api/src/test/java/org/apache/dolphinscheduler/api/service/UdfFuncServiceTest.java @@ -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.UdfFuncServiceImpl; import org.apache.dolphinscheduler.api.utils.PageInfo; @@ -43,17 +44,16 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import org.apache.dolphinscheduler.api.permission.ResourcePermissionCheckService; +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.MockedStatic; import org.mockito.Mockito; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -63,12 +63,13 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * udf func service test */ -@RunWith(PowerMockRunner.class) -@PrepareForTest(PropertyUtils.class) +@RunWith(MockitoJUnitRunner.class) public class UdfFuncServiceTest { private static final Logger logger = LoggerFactory.getLogger(UdfFuncServiceTest.class); + private MockedStatic mockedStaticPropertyUtils; + @InjectMocks private UdfFuncServiceImpl udfFuncService; @@ -83,7 +84,7 @@ public class UdfFuncServiceTest { @Before public void setUp() { - PowerMockito.mockStatic(PropertyUtils.class); + mockedStaticPropertyUtils = Mockito.mockStatic(PropertyUtils.class); } @Mock @@ -93,84 +94,103 @@ public class UdfFuncServiceTest { private static final Logger udfLogger = LoggerFactory.getLogger(UdfFuncServiceImpl.class); @Test - public void testCreateUdfFunction() { - - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_CREATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, null, 0, serviceLogger)).thenReturn(true); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); - //hdfs not start - Result result = udfFuncService.createUdfFunction(getLoginUser(), "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", + public void testCreateUdfFunction() { + + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_CREATE, serviceLogger)).thenReturn(true); + Mockito.when( + resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, null, 0, serviceLogger)) + .thenReturn(true); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + // hdfs not start + Result result = udfFuncService.createUdfFunction(getLoginUser(), "UdfFuncServiceTest", + "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, Integer.MAX_VALUE); logger.info(result.toString()); - Assert.assertEquals(Status.HDFS_NOT_STARTUP.getMsg(),result.getMsg()); - //resource not exist - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); - result = udfFuncService.createUdfFunction(getLoginUser(), "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", + Assert.assertEquals(Status.HDFS_NOT_STARTUP.getMsg(), result.getMsg()); + // resource not exist + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + result = udfFuncService.createUdfFunction(getLoginUser(), "UdfFuncServiceTest", + "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, Integer.MAX_VALUE); logger.info(result.toString()); - Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(),result.getMsg()); + Assert.assertEquals(Status.RESOURCE_NOT_EXIST.getMsg(), result.getMsg()); // success - PowerMockito.when(resourceMapper.selectById(1)).thenReturn(getResource()); - result = udfFuncService.createUdfFunction(getLoginUser(), "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", + Mockito.when(resourceMapper.selectById(1)).thenReturn(getResource()); + result = udfFuncService.createUdfFunction(getLoginUser(), "UdfFuncServiceTest", + "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 1); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(),result.getMsg()); + Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @Test - public void testQueryUdfFuncDetail() { - - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{2}, 0, serviceLogger)).thenReturn(true); - PowerMockito.when(udfFuncMapper.selectById(1)).thenReturn(getUdfFunc()); - //resource not exist + public void testQueryUdfFuncDetail() { + + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{2}, 0, + serviceLogger)).thenReturn(true); + Mockito.when(udfFuncMapper.selectById(1)).thenReturn(getUdfFunc()); + // resource not exist Result result = udfFuncService.queryUdfFuncDetail(getLoginUser(), 2); logger.info(result.toString()); Assert.assertTrue(Status.RESOURCE_NOT_EXIST.getCode() == result.getCode()); // success - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{1}, 0, serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{1}, 0, + serviceLogger)).thenReturn(true); result = udfFuncService.queryUdfFuncDetail(getLoginUser(), 1); logger.info(result.toString()); Assert.assertTrue(Status.SUCCESS.getCode() == result.getCode()); } @Test - public void testUpdateUdfFunc() { - - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); - PowerMockito.when(udfFuncMapper.selectUdfById(1)).thenReturn(getUdfFunc()); - PowerMockito.when(resourceMapper.selectById(1)).thenReturn(getResource()); - - //UDF_FUNCTION_NOT_EXIST - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{12}, 0, serviceLogger)).thenReturn(true); - Result result = udfFuncService.updateUdfFunc(getLoginUser(), 12, "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", + public void testUpdateUdfFunc() { + + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(false); + Mockito.when(udfFuncMapper.selectUdfById(1)).thenReturn(getUdfFunc()); + Mockito.when(resourceMapper.selectById(1)).thenReturn(getResource()); + + // UDF_FUNCTION_NOT_EXIST + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_UPDATE, serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{12}, 0, + serviceLogger)).thenReturn(true); + Result result = udfFuncService.updateUdfFunc(getLoginUser(), 12, "UdfFuncServiceTest", + "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 1); logger.info(result.toString()); Assert.assertTrue(Status.UDF_FUNCTION_NOT_EXIST.getCode() == result.getCode()); - //HDFS_NOT_STARTUP - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{1}, 0, serviceLogger)).thenReturn(true); - result = udfFuncService.updateUdfFunc(getLoginUser(), 1, "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", + // HDFS_NOT_STARTUP + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{1}, 0, + serviceLogger)).thenReturn(true); + result = udfFuncService.updateUdfFunc(getLoginUser(), 1, "UdfFuncServiceTest", + "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 1); logger.info(result.toString()); Assert.assertTrue(Status.HDFS_NOT_STARTUP.getCode() == result.getCode()); - //RESOURCE_NOT_EXIST - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{11}, 0, serviceLogger)).thenReturn(true); - PowerMockito.when(udfFuncMapper.selectUdfById(11)).thenReturn(getUdfFunc()); - PowerMockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); - result = udfFuncService.updateUdfFunc(getLoginUser(), 11, "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", + // RESOURCE_NOT_EXIST + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_UPDATE, serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{11}, 0, + serviceLogger)).thenReturn(true); + Mockito.when(udfFuncMapper.selectUdfById(11)).thenReturn(getUdfFunc()); + Mockito.when(PropertyUtils.getResUploadStartupState()).thenReturn(true); + result = udfFuncService.updateUdfFunc(getLoginUser(), 11, "UdfFuncServiceTest", + "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 12); logger.info(result.toString()); Assert.assertTrue(Status.RESOURCE_NOT_EXIST.getCode() == result.getCode()); - //success - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_UPDATE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{1}, 0, serviceLogger)).thenReturn(true); - result = udfFuncService.updateUdfFunc(getLoginUser(), 11, "UdfFuncServiceTest", "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", + // success + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_UPDATE, serviceLogger)).thenReturn(true); + result = udfFuncService.updateUdfFunc(getLoginUser(), 11, "UdfFuncServiceTest", + "org.apache.dolphinscheduler.api.service.UdfFuncServiceTest", "String", "UdfFuncServiceTest", "UdfFuncServiceTest", UdfType.HIVE, 1); logger.info(result.toString()); Assert.assertTrue(Status.SUCCESS.getCode() == result.getCode()); @@ -178,32 +198,44 @@ public class UdfFuncServiceTest { } @Test - public void testQueryUdfFuncListPaging() { - - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, null, 0, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.UDF, 1, udfLogger)).thenReturn(getSetIds()); - IPage page = new Page<>(1,10); + public void testQueryUdfFuncListPaging() { + + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); + Mockito.when( + resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, null, 0, serviceLogger)) + .thenReturn(true); + Mockito.when( + resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.UDF, 1, udfLogger)) + .thenReturn(getSetIds()); + IPage page = new Page<>(1, 10); page.setTotal(1L); page.setRecords(getList()); - Mockito.when(udfFuncMapper.queryUdfFuncPaging(Mockito.any(Page.class), Mockito.anyList(),Mockito.eq("test"))).thenReturn(page); - Result result = udfFuncService.queryUdfFuncListPaging(getLoginUser(),"test",1,10); + Mockito.when(udfFuncMapper.queryUdfFuncPaging(Mockito.any(Page.class), Mockito.anyList(), Mockito.eq("test"))) + .thenReturn(page); + Result result = udfFuncService.queryUdfFuncListPaging(getLoginUser(), "test", 1, 10); logger.info(result.toString()); PageInfo pageInfo = (PageInfo) result.getData(); Assert.assertTrue(CollectionUtils.isNotEmpty(pageInfo.getTotalList())); } @Test - public void testQueryUdfFuncList() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, null, 1, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.UDF, 1, udfLogger)).thenReturn(getSetIds()); + public void testQueryUdfFuncList() { + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); + Mockito.when( + resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, null, 1, serviceLogger)) + .thenReturn(true); + Mockito.when( + resourcePermissionCheckService.userOwnedResourceIdsAcquisition(AuthorizationType.UDF, 1, udfLogger)) + .thenReturn(getSetIds()); User user = getLoginUser(); user.setUserType(UserType.GENERAL_USER); user.setId(1); - Mockito.when(udfFuncMapper.getUdfFuncByType(Collections.singletonList(1), UdfType.HIVE.ordinal())).thenReturn(getList()); - Result result = udfFuncService.queryUdfFuncList(user,UdfType.HIVE.ordinal()); + Mockito.when(udfFuncMapper.getUdfFuncByType(Collections.singletonList(1), UdfType.HIVE.ordinal())) + .thenReturn(getList()); + Result result = udfFuncService.queryUdfFuncList(user, UdfType.HIVE.ordinal()); logger.info(result.toString()); Assert.assertTrue(Status.SUCCESS.getCode() == result.getCode()); List udfFuncList = (List) result.getData(); @@ -211,34 +243,39 @@ public class UdfFuncServiceTest { } @Test - public void testDelete() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_DELETE, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{122}, 0, serviceLogger)).thenReturn(true); + public void testDelete() { + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_DELETE, serviceLogger)).thenReturn(true); + Mockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, new Object[]{122}, 0, + serviceLogger)).thenReturn(true); Mockito.when(udfFuncMapper.deleteById(Mockito.anyInt())).thenReturn(1); Mockito.when(udfUserMapper.deleteByUdfFuncId(Mockito.anyInt())).thenReturn(1); Result result = udfFuncService.delete(getLoginUser(), 122); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(),result.getMsg()); + Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); } @Test - public void testVerifyUdfFuncByName() { + public void testVerifyUdfFuncByName() { - PowerMockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); - PowerMockito.when(resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, null, 0, serviceLogger)).thenReturn(true); - //success + Mockito.when(resourcePermissionCheckService.operationPermissionCheck(AuthorizationType.UDF, null, 1, + ApiFuncIdentificationConstant.UDF_FUNCTION_VIEW, serviceLogger)).thenReturn(true); + Mockito.when( + resourcePermissionCheckService.resourcePermissionCheck(AuthorizationType.UDF, null, 0, serviceLogger)) + .thenReturn(true); + // success Mockito.when(udfFuncMapper.queryUdfByIdStr(null, "UdfFuncServiceTest")).thenReturn(getList()); Result result = udfFuncService.verifyUdfFuncByName(getLoginUser(), "test"); logger.info(result.toString()); - Assert.assertEquals(Status.SUCCESS.getMsg(),result.getMsg()); - //exist + Assert.assertEquals(Status.SUCCESS.getMsg(), result.getMsg()); + // exist result = udfFuncService.verifyUdfFuncByName(getLoginUser(), "UdfFuncServiceTest"); logger.info(result.toString()); - Assert.assertEquals(Status.UDF_FUNCTION_EXISTS.getMsg(),result.getMsg()); + Assert.assertEquals(Status.UDF_FUNCTION_EXISTS.getMsg(), result.getMsg()); } - private Set getSetIds(){ + private Set getSetIds() { Set set = new HashSet(); set.add(1); return set; @@ -270,7 +307,7 @@ public class UdfFuncServiceTest { private List getList() { List udfFuncList = new ArrayList<>(); udfFuncList.add(getUdfFunc()); - return udfFuncList; + return udfFuncList; } /** @@ -288,4 +325,9 @@ public class UdfFuncServiceTest { udfFunc.setType(UdfType.HIVE); return udfFunc; } + + @After + public void after() { + mockedStaticPropertyUtils.close(); + } }