Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,15 @@
@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();
Expand All @@ -79,6 +75,8 @@ public void before(JoinPoint joinPoint) {
operationDesc = operation.description();
}

AuditLogPO auditLogPO = new AuditLogPO();
auditLogPO.setUserId(userId);
auditLogPO.setUri(uri);
auditLogPO.setTagName(apiName);
auditLogPO.setTagDesc(apiDesc);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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));
}
}
Original file line number Diff line number Diff line change
@@ -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());
}
}
Original file line number Diff line number Diff line change
@@ -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());
}
}
Loading