diff --git a/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/utils/JWTUtils.java b/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/utils/JWTUtils.java index 3bd7bb04..02ca8c63 100644 --- a/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/utils/JWTUtils.java +++ b/bigtop-manager-server/src/main/java/org/apache/bigtop/manager/server/utils/JWTUtils.java @@ -31,7 +31,7 @@ public class JWTUtils { public static final String CLAIM_USERNAME = "username"; - private static final String SIGN = "r0PGVyvjKOxUBwGt"; + protected static final String SIGN = "r0PGVyvjKOxUBwGt"; public static String generateToken(Long id, String username) { Calendar calendar = Calendar.getInstance(); diff --git a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ClusterUtilsTest.java b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ClusterUtilsTest.java new file mode 100644 index 00000000..d0b2fe1a --- /dev/null +++ b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ClusterUtilsTest.java @@ -0,0 +1,57 @@ +/* + * 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.utils; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class ClusterUtilsTest { + + @Test + public void testIsNoneClusterClusterIdIsNull() { + assertTrue(ClusterUtils.isNoneCluster(null)); + } + + @Test + public void testIsNoneClusterClusterIdIsZero() { + assertTrue(ClusterUtils.isNoneCluster(0L)); + } + + @Test + public void testIsNoneClusterClusterIdIsPositive() { + assertFalse(ClusterUtils.isNoneCluster(1L)); + } + + @Test + public void testIsNoneClusterClusterIdIsNegative() { + assertFalse(ClusterUtils.isNoneCluster(-1L)); + } + + @Test + public void testIsNoneClusterClusterIdIsMaxValue() { + assertFalse(ClusterUtils.isNoneCluster(Long.MAX_VALUE)); + } + + @Test + public void testIsNoneClusterClusterIdIsMinValue() { + assertFalse(ClusterUtils.isNoneCluster(Long.MIN_VALUE)); + } +} diff --git a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/JWTUtilsTest.java b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/JWTUtilsTest.java new file mode 100644 index 00000000..53152e57 --- /dev/null +++ b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/JWTUtilsTest.java @@ -0,0 +1,88 @@ +/* + * 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.utils; + +import org.junit.jupiter.api.Test; + +import com.auth0.jwt.JWT; +import com.auth0.jwt.algorithms.Algorithm; +import com.auth0.jwt.exceptions.JWTDecodeException; +import com.auth0.jwt.exceptions.JWTVerificationException; +import com.auth0.jwt.interfaces.DecodedJWT; + +import java.util.Calendar; +import java.util.Date; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class JWTUtilsTest { + + @Test + public void testGenerateTokenNormal() { + Long id = 1L; + String username = "testUser"; + String token = JWTUtils.generateToken(id, username); + assertNotNull(token); + + DecodedJWT decodedJWT = JWTUtils.resolveToken(token); + assertEquals(decodedJWT.getClaim(JWTUtils.CLAIM_ID).asLong(), id); + assertEquals(decodedJWT.getClaim(JWTUtils.CLAIM_USERNAME).asString(), username); + } + + @Test + public void testResolveTokenExpired() { + Long id = 2L; + String username = "expiredUser"; + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.HOUR_OF_DAY, -1); + Date date = calendar.getTime(); + + String token = JWT.create() + .withClaim(JWTUtils.CLAIM_ID, id) + .withClaim(JWTUtils.CLAIM_USERNAME, username) + .withExpiresAt(date) + .sign(Algorithm.HMAC256(JWTUtils.SIGN)); + + assertThrows(JWTVerificationException.class, () -> JWTUtils.resolveToken(token)); + } + + @Test + public void testResolveTokenIllegal() { + String illegalToken = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; + assertThrows(JWTVerificationException.class, () -> JWTUtils.resolveToken(illegalToken)); + } + + @Test + public void testResolveTokenWrongFormat() { + String wrongFormatToken = "wrong_format_token"; + assertThrows(JWTDecodeException.class, () -> JWTUtils.resolveToken(wrongFormatToken)); + } + + @Test + public void testGenerateTokenUsernameEmpty() { + String token = JWTUtils.generateToken(1L, ""); + assertNotNull(token); + + DecodedJWT decodedJWT = JWTUtils.resolveToken(token); + assertEquals(decodedJWT.getClaim(JWTUtils.CLAIM_USERNAME).asString(), ""); + } +} diff --git a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/MessageSourceUtilsTest.java b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/MessageSourceUtilsTest.java new file mode 100644 index 00000000..df4617c1 --- /dev/null +++ b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/MessageSourceUtilsTest.java @@ -0,0 +1,67 @@ +/* + * 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.utils; + +import org.apache.bigtop.manager.server.enums.LocaleKeys; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; + +import java.util.Locale; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.AdditionalMatchers.aryEq; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class MessageSourceUtilsTest { + + private MessageSource messageSourceMock; + + @BeforeEach + void setUp() { + messageSourceMock = mock(MessageSource.class); + MessageSourceUtils utils = new MessageSourceUtils(); + utils.setMessageSource(messageSourceMock); + + LocaleContextHolder.setLocale(Locale.US); + } + + @AfterEach + void tearDown() { + LocaleContextHolder.resetLocaleContext(); + } + + @Test + void testGetMessageWithArguments() { + LocaleKeys testKey = LocaleKeys.REQUEST_SUCCESS; + Object[] args = {"operation"}; + String expectedMessage = "Operation succeeded"; + + when(messageSourceMock.getMessage(eq(testKey.getKey()), aryEq(args), eq(Locale.US))) + .thenReturn(expectedMessage); + + String actualMessage = MessageSourceUtils.getMessage(testKey, "operation"); + assertEquals(expectedMessage, actualMessage); + } +} diff --git a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/PageUtilsTest.java b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/PageUtilsTest.java new file mode 100644 index 00000000..7b24fb6b --- /dev/null +++ b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/PageUtilsTest.java @@ -0,0 +1,147 @@ +/* + * 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.utils; + +import org.apache.bigtop.manager.server.model.query.PageQuery; + +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.MockedStatic; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mockStatic; + +@ExtendWith(MockitoExtension.class) +class PageUtilsTest { + + private MockedStatic servletUtilsMock; + + @BeforeEach + void setUp() { + servletUtilsMock = mockStatic(ServletUtils.class); + } + + @AfterEach + void tearDown() { + servletUtilsMock.close(); + } + + @Test + void testDefaultValues() { + // Simulate all parameters not existing + setupMockParameters(null, null, null, null); + + PageQuery result = PageUtils.getPageQuery(); + + assertAll( + "Default values check", + () -> assertEquals(1, result.getPageNum()), + () -> assertEquals(10, result.getPageSize()), + () -> assertEquals("id ASC ", result.getOrderBy())); + } + + @Test + void testValidParameters() { + // Simulate valid parameters + setupMockParameters("3", "25", "createTime", "desc"); + + PageQuery result = PageUtils.getPageQuery(); + + assertAll( + "Valid parameters check", + () -> assertEquals(3, result.getPageNum()), + () -> assertEquals(25, result.getPageSize()), + () -> assertEquals("createTime DESC ", result.getOrderBy())); + } + + @Test + void testInvalidNumberParameters() { + // Simulate invalid number parameters + setupMockParameters("abc", "xyz", "name", "asc"); + + PageQuery result = PageUtils.getPageQuery(); + + assertAll( + "Invalid number parameters check", + () -> assertEquals(1, result.getPageNum()), + () -> assertEquals(10, result.getPageSize()), + () -> assertEquals("name ASC ", result.getOrderBy())); + } + + @Test + void testEmptyStringParameters() { + // Simulate empty string parameters + setupMockParameters("", "", "", ""); + + PageQuery result = PageUtils.getPageQuery(); + + assertAll( + "Empty string parameters check", + () -> assertEquals(1, result.getPageNum()), + () -> assertEquals(10, result.getPageSize()), + () -> assertEquals("id ASC ", result.getOrderBy())); + } + + @Test + void testEdgeCaseNumbers() { + // Test edge case numbers + setupMockParameters("0", "0", "updateTime", "invalid"); + + PageQuery result = PageUtils.getPageQuery(); + + assertAll( + "Edge case numbers check", + () -> assertEquals(0, result.getPageNum()), + () -> assertEquals(0, result.getPageSize()), + () -> assertEquals("updateTime ASC ", result.getOrderBy())); + } + + @Test + void testSpecialCharactersInOrderBy() { + // Test special characters handling + setupMockParameters("2", "15", "user_name", "desc"); + + PageQuery result = PageUtils.getPageQuery(); + + assertAll("Special characters check", () -> assertEquals("user_name DESC ", result.getOrderBy())); + } + + @Test + void testMixedCaseSortParameter() { + // Test mixed case sort parameter + setupMockParameters("1", "10", "email", "desc"); + + PageQuery result = PageUtils.getPageQuery(); + + assertEquals("email DESC ", result.getOrderBy()); + } + + private void setupMockParameters(String pageNum, String pageSize, String orderBy, String sort) { + // Parameter mock configuration method + servletUtilsMock.when(() -> ServletUtils.getParameter(eq("pageNum"))).thenReturn(pageNum); + servletUtilsMock.when(() -> ServletUtils.getParameter(eq("pageSize"))).thenReturn(pageSize); + servletUtilsMock.when(() -> ServletUtils.getParameter(eq("orderBy"))).thenReturn(orderBy); + servletUtilsMock.when(() -> ServletUtils.getParameter(eq("sort"))).thenReturn(sort); + } +} diff --git a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ProxyUtilsTest.java b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ProxyUtilsTest.java new file mode 100644 index 00000000..aa39edd3 --- /dev/null +++ b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ProxyUtilsTest.java @@ -0,0 +1,217 @@ +/* + * 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.utils; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class ProxyUtilsTest { + + @Test + // Test getDoubleSafely with normal case + public void testGetDoubleSafelyHappyPath() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + String jsonString = "{\"values\":[1.1, 2.2, 3.3]}"; + JsonNode parentNode = mapper.readTree(jsonString); + assertEquals(2.2, ProxyUtils.getDoubleSafely(parentNode, "values", 1)); + } + + @Test + // Test getDoubleSafely with null node case + public void testGetDoubleSafelyNullNode() { + ObjectMapper mapper = new ObjectMapper(); + JsonNode parentNode = mapper.createObjectNode(); + assertEquals(0.0, ProxyUtils.getDoubleSafely(parentNode, "values", 1)); + } + + @Test + // Test getDoubleSafely with non-array node case + public void testGetDoubleSafelyNotArrayNode() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + String jsonString = "{\"values\":1.1}"; + JsonNode parentNode = mapper.readTree(jsonString); + assertEquals(0.0, ProxyUtils.getDoubleSafely(parentNode, "values", 1)); + } + + @Test + // Test getDoubleSafely with index out of bounds case + public void testGetDoubleSafelyIndexOutOfBound() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + String jsonString = "{\"values\":[1.1, 2.2, 3.3]}"; + JsonNode parentNode = mapper.readTree(jsonString); + assertEquals(0.0, ProxyUtils.getDoubleSafely(parentNode, "values", 5)); + } + + @Test + // Test getLongSafely with normal case + public void testGetLongSafelyHappyPath() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + String jsonString = "{\"values\":[1, 2, 3]}"; + JsonNode parentNode = mapper.readTree(jsonString); + assertEquals(2L, ProxyUtils.getLongSafely(parentNode, "values", 1)); + } + + @Test + // Test getLongSafely with null node case + public void testGetLongSafelyNullNode() { + ObjectMapper mapper = new ObjectMapper(); + JsonNode parentNode = mapper.createObjectNode(); + assertEquals(0L, ProxyUtils.getLongSafely(parentNode, "values", 1)); + } + + @Test + // Test getLongSafely with non-array node case + public void testGetLongSafelyNotArrayNode() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + String jsonString = "{\"values\":1}"; + JsonNode parentNode = mapper.readTree(jsonString); + assertEquals(0L, ProxyUtils.getLongSafely(parentNode, "values", 1)); + } + + @Test + // Test getLongSafely with index out of bounds case + public void testGetLongSafelyIndexOutOfBound() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + String jsonString = "{\"values\":[1, 2, 3]}"; + JsonNode parentNode = mapper.readTree(jsonString); + assertEquals(0L, ProxyUtils.getLongSafely(parentNode, "values", 5)); + } + + @Test + // Test array2node(double[] array) with normal case + public void testArray2NodeDoubleArrayHappyPath() { + double[] array = {1.123456789, 2.23456789, 3.3456789, 4.456789, 5.56789, 6.6789}; + JsonNode node = ProxyUtils.array2node(array); + assertEquals("1.123457", node.get(0).asText()); + assertEquals("2.234568", node.get(1).asText()); + assertEquals("3.345679", node.get(2).asText()); + assertEquals("4.456789", node.get(3).asText()); + assertEquals("5.567890", node.get(4).asText()); + assertEquals("6.678900", node.get(5).asText()); + } + + @Test + // Test array2node(long[] array) with normal case + public void testArray2NodeLongArrayHappyPath() { + long[] array = {1, 2, 3, 4, 5, 6}; + JsonNode node = ProxyUtils.array2node(array); + assertEquals(1L, node.get(0).asLong()); + assertEquals(2L, node.get(1).asLong()); + assertEquals(3L, node.get(2).asLong()); + assertEquals(4L, node.get(3).asLong()); + assertEquals(5L, node.get(4).asLong()); + assertEquals(6L, node.get(5).asLong()); + } + + @Test + // Test array2node(long[] array1, long[] array2) with normal case + public void testArray2NodeTwoLongArraysHappyPath() { + long[] array1 = {1, 2, 3, 4, 5, 6}; + long[] array2 = {2, 4, 6, 8, 10, 12}; + JsonNode node = ProxyUtils.array2node(array1, array2); + assertEquals("0.500000", node.get(0).asText()); + assertEquals("0.500000", node.get(1).asText()); + assertEquals("0.500000", node.get(2).asText()); + assertEquals("0.500000", node.get(3).asText()); + assertEquals("0.500000", node.get(4).asText()); + assertEquals("0.500000", node.get(5).asText()); + } + + @Test + // Test array2node(long[] array1, long[] array2) with array2 containing zero case + public void testArray2NodeTwoLongArraysWithZero() { + long[] array1 = {1, 2, 3, 4, 5, 6}; + long[] array2 = {0, 4, 0, 8, 10, 0}; + JsonNode node = ProxyUtils.array2node(array1, array2); + assertEquals("0.000000", node.get(0).asText()); + assertEquals("0.500000", node.get(1).asText()); + assertEquals("0.000000", node.get(2).asText()); + assertEquals("0.500000", node.get(3).asText()); + assertEquals("0.500000", node.get(4).asText()); + assertEquals("0.000000", node.get(5).asText()); + } + + @Test + // Test array2node(long[][] array1, long[][] array2, int num) with normal case + public void testArray2NodeTwoLong2DArraysHappyPath() { + long[][] array1 = {{1, 2, 3, 4, 5, 6}, {2, 3, 4, 5, 6, 7}}; + long[][] array2 = {{2, 4, 6, 8, 10, 12}, {3, 5, 6, 8, 10, 12}}; + JsonNode node = ProxyUtils.array2node(array1, array2, 2); + assertEquals("0.400000", node.get(0).asText()); + assertEquals("0.444444", node.get(1).asText()); + assertEquals("0.416667", node.get(2).asText()); + assertEquals("0.437500", node.get(3).asText()); + assertEquals("0.450000", node.get(4).asText()); + assertEquals("0.458333", node.get(5).asText()); + } + + @Test + // Test array2node(long[][] array1, long[][] array2, int num) with array2 containing zero case + public void testArray2NodeTwoLong2DArraysWithZero() { + long[][] array1 = {{1, 2, 3, 4, 5, 6}, {2, 3, 4, 5, 6, 7}}; + long[][] array2 = {{2, 4, 0, 8, 10, 0}, {3, 5, 0, 8, 10, 0}}; + JsonNode node = ProxyUtils.array2node(array1, array2, 2); + assertEquals("0.400000", node.get(0).asText()); + assertEquals("0.444444", node.get(1).asText()); + assertEquals("0.000000", node.get(2).asText()); + assertEquals("0.437500", node.get(3).asText()); + assertEquals("0.450000", node.get(4).asText()); + assertEquals("0.000000", node.get(5).asText()); + } + + @Test + // Test getTimeStampsList with normal case + public void testGetTimeStampsListHappyPath() { + ArrayList timestamps = ProxyUtils.getTimeStampsList(10); + assertEquals(7, timestamps.size()); + // Here we cannot precisely assert the value of each timestamp as they depend on the current time, but we can + // assert the number of timestamps + } + + @Test + // Test Number2Param with normal case + public void testNumber2ParamHappyPath() { + assertEquals("10m", ProxyUtils.Number2Param(10)); + } + + @Test + // Test processInternal with normal case + public void testProcessInternalHappyPath() { + assertEquals(600, ProxyUtils.processInternal("10m")); + assertEquals(3600, ProxyUtils.processInternal("1h")); + assertEquals(120, ProxyUtils.processInternal("2m")); + } + + @Test + // Test processInternal with illegal input case + public void testProcessInternalIllegalInput() { + Exception exception = assertThrows(NumberFormatException.class, () -> { + ProxyUtils.processInternal("abc"); + }); + assertNotNull(exception); + } +} diff --git a/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ServletUtilsTest.java b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ServletUtilsTest.java new file mode 100644 index 00000000..1f0d1cf9 --- /dev/null +++ b/bigtop-manager-server/src/test/java/org/apache/bigtop/manager/server/utils/ServletUtilsTest.java @@ -0,0 +1,121 @@ +/* + * 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.utils; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import jakarta.servlet.http.HttpServletRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ServletUtilsTest { + + // Use mockito to mock HttpServletRequest object + private HttpServletRequest mockRequest; + + @BeforeEach + public void setUp() { + ServletRequestAttributes mockAttributes = mock(ServletRequestAttributes.class); + mockRequest = mock(HttpServletRequest.class); + when(mockAttributes.getRequest()).thenReturn(mockRequest); + RequestContextHolder.setRequestAttributes(mockAttributes); + } + + @Test + public void testGetParameterNormalPath() { + // Test case: normal path, get existing parameter + when(mockRequest.getParameter("testParam")).thenReturn("testValue"); + assertEquals("testValue", ServletUtils.getParameter("testParam")); + } + + @Test + public void testGetParameterParameterDoesNotExist() { + // Test case: parameter does not exist, expect to return null + when(mockRequest.getParameter("nonexistentParam")).thenReturn(null); + assertNull(ServletUtils.getParameter("nonexistentParam")); + } + + @Test + public void testGetParameterEmptyStringParameterName() { + // Test case: parameter name is an empty string, expect to return null + when(mockRequest.getParameter("")).thenReturn(null); + assertNull(ServletUtils.getParameter("")); + } + + @Test + public void testGetParameterSpaceParameterName() { + // Test case: parameter name is a space, expect to return null + when(mockRequest.getParameter(" ")).thenReturn(null); + assertNull(ServletUtils.getParameter(" ")); + } + + @Test + public void testGetParameterSpecialCharacterParameterName() { + // Test case: parameter name contains special characters, expect to return null or correct value (adjust based + // on actual situation) + when(mockRequest.getParameter("!@#$%^&*()")).thenReturn(null); + assertNull(ServletUtils.getParameter("!@#$%^&*()")); + } + + @Test + public void testGetRequestCorrectRequest() { + // Test case: correct request, expect to return the mock HttpServletRequest object + assertEquals(mockRequest, ServletUtils.getRequest()); + } + + @Test + public void testGetRequestAttributesCorrectAttributes() { + // Test case: correct attributes, expect to return the mock ServletRequestAttributes object + ServletRequestAttributes attributes = ServletUtils.getRequestAttributes(); + assertNotNull(attributes); + assertEquals(mockRequest, attributes.getRequest()); + } + + @Test + public void testGetRequestAttributesAttributesNotSet() { + // Test case: attributes not set, expect to return null + RequestContextHolder.setRequestAttributes(null); + assertNull(ServletUtils.getRequestAttributes()); + } + + @Test + public void testGetParameterAttributesNotSet() { + // Test case: attributes not set, expect to throw an exception or return null + RequestContextHolder.setRequestAttributes(null); + assertThrows(NullPointerException.class, () -> ServletUtils.getParameter("testParam")); + } + + @Test + public void testGetParameterRequestNotSet() { + // Test case: request not set, expect to throw an exception or return null + when(mockRequest.getParameter("testParam")).thenReturn(null); + ServletRequestAttributes mockAttributes = mock(ServletRequestAttributes.class); + when(mockAttributes.getRequest()).thenReturn(null); + RequestContextHolder.setRequestAttributes(mockAttributes); + assertThrows(NullPointerException.class, () -> ServletUtils.getParameter("testParam")); + } +}