Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BIGTOP-4347: Add ut cases for utils classes in server module #166

Merged
merged 1 commit into from
Feb 8, 2025
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 @@ -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();
Expand Down
Original file line number Diff line number Diff line change
@@ -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));
}
}
Original file line number Diff line number Diff line change
@@ -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(), "");
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
}
Original file line number Diff line number Diff line change
@@ -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<ServletUtils> 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);
}
}
Loading
Loading