This is an automated email from the ASF dual-hosted git repository.

wuzhiguo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/bigtop-manager.git


The following commit(s) were added to refs/heads/main by this push:
     new 34694a5  BIGTOP-4177: Add ut cases for config classes in server module 
(#32)
34694a5 is described below

commit 34694a5dfb5a6d5e4934fbf96e4092dc82aaa36d
Author: Zhiguo Wu <[email protected]>
AuthorDate: Mon Aug 5 14:35:07 2024 +0800

    BIGTOP-4177: Add ut cases for config classes in server module (#32)
---
 .../bigtop/manager/server/aop/AuditAspect.java     |  12 +--
 .../config/CommandGroupSequenceProvider.java       |   4 +-
 .../bigtop/manager/server/aop/AuditAspectTest.java | 109 +++++++++++++++++++++
 .../server/config/AsyncThreadPoolConfigTest.java   | 101 +++++++++++++++++++
 .../server/config/FrontendRedirectorTest.java      |  71 ++++++++++++++
 .../manager/server/config/LocaleConfigTest.java    |  81 +++++++++++++++
 .../manager/server/config/OpenAPIConfigTest.java   |  49 +++++++++
 7 files changed, 418 insertions(+), 9 deletions(-)

diff --git 
a/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/aop/AuditAspect.java
 
b/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/aop/AuditAspect.java
index 4471f73..4599260 100644
--- 
a/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/aop/AuditAspect.java
+++ 
b/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/aop/AuditAspect.java
@@ -43,19 +43,15 @@ import jakarta.servlet.http.HttpServletRequest;
 @Configuration
 public class AuditAspect {
 
-    private static final String POINT_CUT = 
"@annotation(org.apache.bigtop.manager.server.annotations.Audit)";
-
     @Resource
     private AuditLogRepository auditLogRepository;
 
-    @Before(value = POINT_CUT)
+    @Before(value = 
"@annotation(org.apache.bigtop.manager.server.annotations.Audit)")
     public void before(JoinPoint joinPoint) {
         MethodSignature ms = (MethodSignature) joinPoint.getSignature();
-        AuditLogPO auditLogPO = new AuditLogPO();
-        auditLogPO.setUserId(SessionUserHolder.getUserId());
-
+        Long userId = SessionUserHolder.getUserId();
         ServletRequestAttributes attributes = (ServletRequestAttributes) 
RequestContextHolder.getRequestAttributes();
-        if (attributes != null) {
+        if (attributes != null && userId != null) {
             // obtain request uri
             HttpServletRequest request = attributes.getRequest();
             String uri = request.getRequestURI();
@@ -79,6 +75,8 @@ public class AuditAspect {
                 operationDesc = operation.description();
             }
 
+            AuditLogPO auditLogPO = new AuditLogPO();
+            auditLogPO.setUserId(userId);
             auditLogPO.setUri(uri);
             auditLogPO.setTagName(apiName);
             auditLogPO.setTagDesc(apiDesc);
diff --git 
a/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/config/CommandGroupSequenceProvider.java
 
b/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/config/CommandGroupSequenceProvider.java
index f7911ad..650a228 100644
--- 
a/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/config/CommandGroupSequenceProvider.java
+++ 
b/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/config/CommandGroupSequenceProvider.java
@@ -32,9 +32,9 @@ public class CommandGroupSequenceProvider implements 
DefaultGroupSequenceProvide
     @Override
     public List<Class<?>> getValidationGroups(CommandReq bean) {
         List<Class<?>> defaultGroupSequence = new ArrayList<>();
-        defaultGroupSequence.add(CommandReq.class); // 
这一步不能省,否则Default分组都不会执行了,会抛错的
+        defaultGroupSequence.add(CommandReq.class);
 
-        if (bean != null) { // 这块判空请务必要做
+        if (bean != null) {
             CommandLevel commandLevel = bean.getCommandLevel();
 
             switch (commandLevel) {
diff --git 
a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/aop/AuditAspectTest.java
 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/aop/AuditAspectTest.java
new file mode 100644
index 0000000..60ecd0f
--- /dev/null
+++ 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/aop/AuditAspectTest.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bigtop.manager.server.aop;
+
+import org.apache.bigtop.manager.dao.po.AuditLogPO;
+import org.apache.bigtop.manager.dao.repository.AuditLogRepository;
+import org.apache.bigtop.manager.server.holder.SessionUserHolder;
+
+import org.aspectj.lang.JoinPoint;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+import jakarta.servlet.http.HttpServletRequest;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class AuditAspectTest {
+
+    @Mock
+    private AuditLogRepository auditLogRepository;
+
+    @Mock
+    private JoinPoint joinPoint;
+
+    @Mock
+    private MethodSignature methodSignature;
+
+    @Mock
+    private HttpServletRequest request;
+
+    @Mock
+    private ServletRequestAttributes attributes;
+
+    @InjectMocks
+    private AuditAspect auditAspect;
+
+    @BeforeEach
+    void setUp() {
+        when(joinPoint.getSignature()).thenReturn(methodSignature);
+    }
+
+    @AfterEach
+    void tearDown() {
+        SessionUserHolder.setUserId(null);
+        RequestContextHolder.setRequestAttributes(null);
+    }
+
+    @Test
+    void before_ValidRequest_SavesAuditLog() {
+        when(request.getRequestURI()).thenReturn("/test/uri");
+        when(joinPoint.getThis()).thenReturn(this);
+        when(attributes.getRequest()).thenReturn(request);
+        when(methodSignature.getName()).thenReturn("testMethod");
+        
when(methodSignature.getMethod()).thenReturn(this.getClass().getDeclaredMethods()[0]);
+        SessionUserHolder.setUserId(1L);
+        RequestContextHolder.setRequestAttributes(attributes);
+
+        auditAspect.before(joinPoint);
+
+        verify(auditLogRepository, times(1)).save(any(AuditLogPO.class));
+    }
+
+    @Test
+    void before_NullRequestAttributes_DoesNotSaveAuditLog() {
+        SessionUserHolder.setUserId(1L);
+
+        auditAspect.before(joinPoint);
+
+        verify(auditLogRepository, never()).save(any(AuditLogPO.class));
+    }
+
+    @Test
+    void before_NullUserId_DoesNotSaveAuditLog() {
+        RequestContextHolder.setRequestAttributes(attributes);
+
+        auditAspect.before(joinPoint);
+
+        verify(auditLogRepository, never()).save(any(AuditLogPO.class));
+    }
+}
diff --git 
a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/AsyncThreadPoolConfigTest.java
 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/AsyncThreadPoolConfigTest.java
new file mode 100644
index 0000000..5ecd33b
--- /dev/null
+++ 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/AsyncThreadPoolConfigTest.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bigtop.manager.server.config;
+
+import org.apache.bigtop.manager.server.holder.SessionUserHolder;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
+import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.ThreadPoolExecutor;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+@ExtendWith(MockitoExtension.class)
+class AsyncThreadPoolConfigTest {
+
+    private AsyncThreadPoolConfig asyncThreadPoolConfig;
+
+    @BeforeEach
+    void setUp() {
+        asyncThreadPoolConfig = new AsyncThreadPoolConfig();
+    }
+
+    @AfterEach
+    void tearDown() {
+        asyncThreadPoolConfig = null;
+        SessionUserHolder.setUserId(null);
+    }
+
+    @Test
+    void getAsyncExecutor_ReturnsConfiguredExecutor() {
+        Executor executor = asyncThreadPoolConfig.getAsyncExecutor();
+
+        assertNotNull(executor);
+        assertInstanceOf(ThreadPoolTaskExecutor.class, executor);
+        ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) 
executor;
+        assertEquals(5, taskExecutor.getCorePoolSize());
+        assertEquals(10, taskExecutor.getMaxPoolSize());
+        assertEquals(300, taskExecutor.getQueueCapacity());
+        assertInstanceOf(
+                ThreadPoolExecutor.CallerRunsPolicy.class,
+                
taskExecutor.getThreadPoolExecutor().getRejectedExecutionHandler());
+    }
+
+    @Test
+    void 
getAsyncUncaughtExceptionHandler_ReturnsSimpleAsyncUncaughtExceptionHandler() {
+        assertInstanceOf(
+                SimpleAsyncUncaughtExceptionHandler.class, 
asyncThreadPoolConfig.getAsyncUncaughtExceptionHandler());
+    }
+
+    @Test
+    void 
contextCopyingDecorator_CopiesContextAndClearsAfterExecutionInSubThread() 
throws InterruptedException {
+        SessionUserHolder.setUserId(1L);
+        Runnable task = mock(Runnable.class);
+        AsyncThreadPoolConfig.ContextCopyingDecorator decorator = new 
AsyncThreadPoolConfig.ContextCopyingDecorator();
+
+        Runnable decoratedTask = decorator.decorate(() -> {
+            assertEquals(1L, SessionUserHolder.getUserId());
+            task.run();
+        });
+
+        Thread taskThread = new Thread(() -> {
+            decoratedTask.run();
+            assertNull(SessionUserHolder.getUserId());
+        });
+
+        taskThread.start();
+        taskThread.join();
+
+        verify(task, times(1)).run();
+        assertEquals(1L, SessionUserHolder.getUserId());
+    }
+}
diff --git 
a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/FrontendRedirectorTest.java
 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/FrontendRedirectorTest.java
new file mode 100644
index 0000000..4177427
--- /dev/null
+++ 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/FrontendRedirectorTest.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bigtop.manager.server.config;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.servlet.ModelAndView;
+
+import jakarta.servlet.RequestDispatcher;
+import jakarta.servlet.http.HttpServletRequest;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class FrontendRedirectorTest {
+
+    @Test
+    void handleError_ReturnsForwardToIndexHtmlForNotFound() {
+        HttpServletRequest request = mock(HttpServletRequest.class);
+        
when(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).thenReturn(HttpStatus.NOT_FOUND.value());
+
+        ModelAndView modelAndView = new 
FrontendRedirector().handleError(request);
+
+        assertEquals(HttpStatus.OK, modelAndView.getStatus());
+        assertEquals("forward:/ui/index.html", modelAndView.getViewName());
+    }
+
+    @Test
+    void handleError_ReturnsModelAndViewWithStatusCode() {
+        HttpServletRequest request = mock(HttpServletRequest.class);
+        when(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE))
+                .thenReturn(HttpStatus.INTERNAL_SERVER_ERROR.value());
+
+        ModelAndView modelAndView = new 
FrontendRedirector().handleError(request);
+
+        assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, 
modelAndView.getStatus());
+        assertNull(modelAndView.getViewName());
+    }
+
+    @Test
+    void handleError_ReturnsModelAndViewWithNullStatus() {
+        HttpServletRequest request = mock(HttpServletRequest.class);
+        
when(request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE)).thenReturn(null);
+
+        ModelAndView modelAndView = new 
FrontendRedirector().handleError(request);
+
+        assertNull(modelAndView.getStatus());
+        assertNull(modelAndView.getViewName());
+    }
+}
diff --git 
a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/LocaleConfigTest.java
 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/LocaleConfigTest.java
new file mode 100644
index 0000000..a12c947
--- /dev/null
+++ 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/LocaleConfigTest.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bigtop.manager.server.config;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+import 
org.springframework.context.annotation.AnnotationConfigApplicationContext;
+import org.springframework.web.servlet.LocaleResolver;
+import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
+
+import jakarta.servlet.http.HttpServletRequest;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+class LocaleConfigTest {
+
+    private final AnnotationConfigApplicationContext context =
+            new AnnotationConfigApplicationContext(LocaleConfig.class);
+
+    @Test
+    void localeResolver_ReturnsAcceptHeaderLocaleResolver() {
+        LocaleConfig localeConfig = context.getBean(LocaleConfig.class);
+        LocaleResolver localeResolver = localeConfig.localeResolver();
+        assertInstanceOf(AcceptHeaderLocaleResolver.class, localeResolver);
+    }
+
+    @Test
+    void resolveLocale_ValidLocaleHeader() {
+        LocaleConfig localeConfig = context.getBean(LocaleConfig.class);
+        AcceptHeaderLocaleResolver localeResolver = 
(AcceptHeaderLocaleResolver) localeConfig.localeResolver();
+        localeResolver.setSupportedLocales(List.of(Locale.CHINESE, 
Locale.ENGLISH));
+
+        HttpServletRequest request = mock(HttpServletRequest.class);
+        
when(request.getLocales()).thenReturn(Collections.enumeration(List.of(Locale.CHINESE,
 Locale.ENGLISH)));
+        Locale resolvedLocale;
+
+        when(request.getHeader("Accept-Language")).thenReturn("zh");
+        resolvedLocale = localeResolver.resolveLocale(request);
+        assertEquals(Locale.CHINESE, resolvedLocale);
+
+        when(request.getHeader("Accept-Language")).thenReturn("en");
+        resolvedLocale = localeResolver.resolveLocale(request);
+        assertEquals(Locale.ENGLISH, resolvedLocale);
+    }
+
+    @Test
+    void resolveLocale_NoLocaleHeader() {
+        LocaleConfig localeConfig = context.getBean(LocaleConfig.class);
+        AcceptHeaderLocaleResolver localeResolver = 
(AcceptHeaderLocaleResolver) localeConfig.localeResolver();
+
+        HttpServletRequest request = mock(HttpServletRequest.class);
+        when(request.getHeader("Accept-Language")).thenReturn(null);
+
+        Locale resolvedLocale = localeResolver.resolveLocale(request);
+        assertEquals(Locale.US, resolvedLocale); // Assuming default is US
+    }
+}
diff --git 
a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/OpenAPIConfigTest.java
 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/OpenAPIConfigTest.java
new file mode 100644
index 0000000..838d54e
--- /dev/null
+++ 
b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/config/OpenAPIConfigTest.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *    https://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.bigtop.manager.server.config;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+import 
org.springframework.context.annotation.AnnotationConfigApplicationContext;
+
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.info.Info;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+
+@ExtendWith(MockitoExtension.class)
+class OpenAPIConfigTest {
+
+    private final AnnotationConfigApplicationContext context =
+            new AnnotationConfigApplicationContext(OpenAPIConfig.class);
+
+    @Test
+    void apiV1Info1_ReturnsOpenAPIWithCorrectInfo() {
+        OpenAPI openAPI = context.getBean(OpenAPI.class);
+
+        assertNotNull(openAPI);
+        Info info = openAPI.getInfo();
+        assertNotNull(info);
+        assertEquals("Bigtop Manager Api Docs", info.getTitle());
+        assertEquals("Bigtop Manager Api Docs", info.getDescription());
+        assertEquals("V1", info.getVersion());
+    }
+}

Reply via email to