From: nisha.gangore Date: Wed, 9 Apr 2025 14:12:51 +0000 (+0530) Subject: [AAI] Improve test coverage for A&AI component aai-schema-service X-Git-Tag: 1.12.10~2 X-Git-Url: https://gerrit.onap.org/r/gitweb?a=commitdiff_plain;h=refs%2Fchanges%2F78%2F140678%2F4;p=aai%2Fschema-service.git [AAI] Improve test coverage for A&AI component aai-schema-service - to Improve test coverage for A&AI component aai-schema-service <=80% Issue-ID: AAI-4107 Change-Id: I766206c9aad33ee59f7a1eedab63f912dfc97e36 Signed-off-by: nisha.gangore --- diff --git a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/edges/EdgeResourceTest.java b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/edges/EdgeResourceTest.java new file mode 100644 index 0000000..475fbf1 --- /dev/null +++ b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/edges/EdgeResourceTest.java @@ -0,0 +1,157 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2025 Deutsche Telekom. All rights reserved. + * ================================================================================ + * Licensed 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 + * + * http://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. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.schemaservice.edges; + +import com.google.gson.Gson; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.schemaservice.nodeschema.SchemaVersion; +import org.onap.aai.schemaservice.nodeschema.SchemaVersions; + +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +class EdgeResourceTest { + + @InjectMocks + private EdgeResource edgeResource; + + @Mock + private EdgeService edgeService; + + @Mock + private SchemaVersions schemaVersions; + + @Mock + private HttpHeaders headers; + + @Mock + private UriInfo uriInfo; + + private static final Gson gson = new Gson(); + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + edgeResource = new EdgeResource(edgeService, schemaVersions, gson); + } + + @Test + void testRetrieveSchema_getEmptyRules() throws AAIException { + String version = "v1"; + + EdgeRule edgeRule1 = new EdgeRule(); + List edgeRuleList = Arrays.asList(edgeRule1); + EdgeRules edgeRules = new EdgeRules(edgeRuleList); + + List schemaVersionList = Arrays.asList(new SchemaVersion(version)); + when(edgeService.findRules(version)).thenReturn(Optional.of(edgeRules)); + when(schemaVersions.getVersions()).thenReturn(schemaVersionList); + + Response response = edgeResource.retrieveSchema(version, headers, uriInfo); + + String expectedRules ="{\"rules\":[{}]}"; + assertEquals(expectedRules,response.getEntity()); + } + + @Test + void testRetrieveSchema_InvalidVersion_Empty() { + String version = ""; + Response response = edgeResource.retrieveSchema(version, headers, uriInfo); + String expectedResponseEntity = "{\"requestError\":{\"serviceException\":{" + + "\"messageId\":\"SVC3000\"," + + "\"text\":\"Invalid input performing %1 on %2 (msg=%3) (ec=%4)\"," + + "\"variables\":[\"GET\",null,\"Invalid Accept header\",\"4.0.4014\"]" + + "}}}"; + + assertEquals(expectedResponseEntity,response.getEntity()); + } + + @Test + void testRetrieveSchema_VersionNotFound() throws AAIException { + String version = "v2"; + + List schemaVersionList = Arrays.asList(new SchemaVersion("v1")); + when(schemaVersions.getVersions()).thenReturn(schemaVersionList); + + Response response = edgeResource.retrieveSchema(version, headers, uriInfo); + + assertEquals(400, response.getStatus()); + String expectedResponseEntity = "{" + + "\"requestError\":{" + + "\"serviceException\":{" + + "\"messageId\":\"SVC3000\"," + + "\"text\":\"Invalid input performing %1 on %2 (msg=%3) (ec=%4)\"," + + "\"variables\":[\"GET\",null,\"Invalid Accept header\",\"4.0.4014\"]" + + "}}}"; + assertEquals(expectedResponseEntity,response.getEntity()); + } + + @Test + void testRetrieveSchema_EdgeRulesNotFound() throws AAIException { + String version = "v1"; + + when(edgeService.findRules(version)).thenReturn(Optional.empty()); + List schemaVersionList = Arrays.asList(new SchemaVersion(version)); + when(schemaVersions.getVersions()).thenReturn(schemaVersionList); + + Response response = edgeResource.retrieveSchema(version, headers, uriInfo); + + assertEquals(404, response.getStatus()); + String expectedResponseEntity = "{\"requestError\":{\"serviceException\":{" + + "\"messageId\":\"SVC3000\"," + + "\"text\":\"Invalid input performing %1 on %2 (msg=%3) (ec=%4)\"," + + "\"variables\":[\"GET\",null,\"Invalid Accept header\",\"4.0.4014\"]" + + "}}}"; + + assertEquals(expectedResponseEntity,response.getEntity()); + } + + @Test + void testRetrieveSchema_ExceptionHandling() throws AAIException { + String version = "v1"; + + when(edgeService.findRules(version)).thenThrow(new RuntimeException("Unexpected error")); + + List schemaVersionList = Arrays.asList(new SchemaVersion(version)); + when(schemaVersions.getVersions()).thenReturn(schemaVersionList); + + Response response = edgeResource.retrieveSchema(version, headers, uriInfo); + + assertEquals(500, response.getStatus()); + String expectedResponseEntity = "{\"requestError\":{\"serviceException\":{" + + "\"messageId\":\"SVC3000\"," + + "\"text\":\"Invalid input performing %1 on %2 (msg=%3) (ec=%4)\"," + + "\"variables\":[\"GET\",null,\"Invalid Accept header\",\"4.0.4014\"]" + + "}}}"; + assertEquals(expectedResponseEntity,response.getEntity()); + } +} diff --git a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/healthcheck/EchoResourceTest.java b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/healthcheck/EchoResourceTest.java new file mode 100644 index 0000000..20b6a49 --- /dev/null +++ b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/healthcheck/EchoResourceTest.java @@ -0,0 +1,90 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2025 Deutsche Telekom. All rights reserved. + * ================================================================================ + * Licensed 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 + * + * http://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. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.schemaservice.healthcheck; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.exceptions.AAIException; +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.List; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +class EchoResourceTest { + + @InjectMocks + private EchoResource echoResource; + + @Mock + private HttpHeaders headers; + + @Mock + private HttpServletRequest request; + + @Mock + private UriInfo uriInfo; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + void testEchoResult_Success() throws AAIException { + when(headers.getRequestHeader("X-FromAppId")).thenReturn(List.of("App1")); + when(headers.getRequestHeader("X-TransactionId")).thenReturn(List.of("Trans1")); + + Response response = echoResource.echoResult(headers, request, uriInfo); + + assertEquals(200, response.getStatus()); + assertTrue(response.getEntity().toString().contains("App1")); + assertTrue(response.getEntity().toString().contains("Trans1")); + } + + @Test + void testEchoResult_MissingHeaders() throws AAIException { + when(headers.getRequestHeader("X-FromAppId")).thenReturn(null); + when(headers.getRequestHeader("X-TransactionId")).thenReturn(null); + + Response response = echoResource.echoResult(headers, request, uriInfo); + + assertEquals(400, response.getStatus()); + assertTrue(response.getEntity().toString().contains("Headers missing")); + } + + @Test + void testEchoResult_ValidHeadersNoQuery() throws AAIException { + when(headers.getRequestHeader("X-FromAppId")).thenReturn(List.of("App1")); + when(headers.getRequestHeader("X-TransactionId")).thenReturn(List.of("Trans1")); + + Response response = echoResource.echoResult(headers, request, uriInfo); + + assertEquals(200, response.getStatus()); + assertTrue(response.getEntity().toString().contains("App1")); + assertTrue(response.getEntity().toString().contains("Trans1")); + } +} diff --git a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/nodeschema/NodeIngestorTest.java b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/nodeschema/NodeIngestorTest.java new file mode 100644 index 0000000..74be418 --- /dev/null +++ b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/nodeschema/NodeIngestorTest.java @@ -0,0 +1,122 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2025 Deutsche Telekom. All rights reserved. + * ================================================================================ + * Licensed 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 + * + * http://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. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.schemaservice.nodeschema; + +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +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.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.onap.aai.schemaservice.config.ConfigTranslator; +import org.w3c.dom.*; +import java.lang.reflect.Method; +import java.util.*; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class NodeIngestorTest { + + @Mock + private ConfigTranslator configTranslator; + + @Mock + private Map versionContextMap; + + @Mock + private Map> typesPerVersion; + + @InjectMocks + private NodeIngestor nodeIngestor; + + @Mock + DynamicJAXBContext context1; + + @Mock + DynamicJAXBContext context2; + + + private static final SchemaVersion version1 = new SchemaVersion("v1"); + private static final SchemaVersion version2 = new SchemaVersion("v2"); + + + @BeforeEach + public void setUp() { + when(versionContextMap.get(version1)).thenReturn(context1); + when(versionContextMap.get(version2)).thenReturn(context2); + + Set nodeTypesV1 = new HashSet<>(Arrays.asList("node-type-1", "node-type-2")); + Set nodeTypesV2 = new HashSet<>(Collections.singletonList("node-type-3")); + + when(typesPerVersion.get(version1)).thenReturn(nodeTypesV1); + when(typesPerVersion.get(version2)).thenReturn(nodeTypesV2); + + when(configTranslator.getNodeFiles()).thenReturn(mockFileMap()); + } + + @Test + public void testGetVersionFromClassNameWithVersion() { + String className = "com.example.SomeClass.v1.SomeOtherClass"; + SchemaVersion result = nodeIngestor.getVersionFromClassName(className); + assertNotNull(result, "SchemaVersion should not be null"); + assertEquals("v1", result.toString(), "The version extracted from class name should be v1"); + } + + @Test + public void testCreateNode() throws Exception { + Document mockDoc1 = mock(Document.class); + Node mockNode1 = mock(Node.class); + Node mockNode2 = mock(Node.class); + + NodeList mockNodeList = mock(NodeList.class); + when(mockNodeList.getLength()).thenReturn(2); + when(mockNodeList.item(0)).thenReturn(mockNode1); + when(mockNodeList.item(1)).thenReturn(mockNode2); + when(mockDoc1.getElementsByTagName("java-type")).thenReturn(mockNodeList); + + Node javaTypesContainer = mock(Node.class); + Document combinedDoc = mock(Document.class); + Map> mockNodeMap = new HashMap<>(); + mockNodeMap.put("node-type-1", List.of(mockNode1, mockNode2)); + + Node mockImportedNode = mock(Node.class); + when(combinedDoc.importNode(any(Node.class), eq(true))).thenReturn(mockImportedNode); + + Method createNodeMethod = NodeIngestor.class.getDeclaredMethod("createNode", Document.class, Node.class, Map.class); + createNodeMethod.setAccessible(true); + + createNodeMethod.invoke(nodeIngestor, combinedDoc, javaTypesContainer, mockNodeMap); + + verify(javaTypesContainer, times(1)).appendChild(any(Node.class)); + verify(combinedDoc, times(2)).importNode(any(Node.class), eq(true)); + } + + private Map> mockFileMap() { + return Map.of( + version1, List.of("file1.xml", "file2.xml"), + version2, List.of("file3.xml", "file4.xml") + ); + } +} diff --git a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaResourceTest.java b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaResourceTest.java new file mode 100644 index 0000000..fbce64d --- /dev/null +++ b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/nodeschema/NodeSchemaResourceTest.java @@ -0,0 +1,113 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2025 Deutsche Telekom. All rights reserved. + * ================================================================================ + * Licensed 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 + * + * http://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. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.schemaservice.nodeschema; + +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 javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class NodeSchemaResourceTest { + + @Mock + private NodeSchemaService nodeSchemaService; + + @Mock + private SchemaVersions schemaVersions; + + @Mock + private HttpHeaders headers; + + @Mock + private UriInfo uriInfo; + + @InjectMocks + private NodeSchemaResource nodeSchemaResource; + + @Test + public void testRetrieveSchema_Success() { + String version = "v1"; + String schema = "..."; + + when(schemaVersions.getVersions()).thenReturn( + List.of(new SchemaVersion("v1"), new SchemaVersion("v2"), new SchemaVersion("v3")) + ); + when(nodeSchemaService.fetch(version)).thenReturn(Optional.of(schema)); + + Response response = nodeSchemaResource.retrieveSchema(version, headers, uriInfo); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + assertEquals(schema, response.getEntity()); + } + + @Test + public void testRetrieveSchema_VersionEmpty_ThrowsAAIException() { + String version = ""; + when(nodeSchemaService.fetch(version)).thenReturn(Optional.empty()); + + Response response = nodeSchemaResource.retrieveSchema(version, headers, uriInfo); + + String expectedResponseEntity = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3000\",\"text\":\"Invalid input performing %1 on %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",null,\"Invalid Accept header\",\"4.0.4014\"]}}}"; + assertEquals(expectedResponseEntity,response.getEntity()); + } + + @Test + public void testRetrieveSchema_VersionNotFound_ThrowsAAIException() { + String version = "v2"; + String schema = "..."; + + when(nodeSchemaService.fetch(version)).thenReturn(Optional.of(schema)); + when(schemaVersions.getVersions()).thenReturn( + List.of(new SchemaVersion("v1"), new SchemaVersion("v3")) + ); + + Response response = nodeSchemaResource.retrieveSchema(version, headers, uriInfo); + + String expectedResponseEntity = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3000\",\"text\":\"Invalid input performing %1 on %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",null,\"Invalid Accept header\",\"4.0.4014\"]}}}"; + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + assertEquals(expectedResponseEntity,response.getEntity()); + } + + @Test + public void testRetrieveSchema_SchemaNotFound_ThrowsAAIException() { + String version = "v1"; + + when(schemaVersions.getVersions()).thenReturn( + List.of(new SchemaVersion("v1"), new SchemaVersion("v2"), new SchemaVersion("v3")) + ); + when(nodeSchemaService.fetch(version)).thenReturn(Optional.empty()); + + Response response = nodeSchemaResource.retrieveSchema(version, headers, uriInfo); + String expectedEntityResponse = "{\"requestError\":{\"serviceException\":{\"messageId\":\"SVC3000\",\"text\":\"Invalid input performing %1 on %2 (msg=%3) (ec=%4)\",\"variables\":[\"GET\",null,\"Invalid Accept header\",\"4.0.4014\"]}}}"; + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + assertEquals(expectedEntityResponse,response.getEntity()); + } +} diff --git a/aai-schema-service/src/test/java/org/onap/aai/schemaservice/service/AuthorizationServiceTest.java b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/service/AuthorizationServiceTest.java new file mode 100644 index 0000000..2107e40 --- /dev/null +++ b/aai-schema-service/src/test/java/org/onap/aai/schemaservice/service/AuthorizationServiceTest.java @@ -0,0 +1,160 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2025 Deutsche Telekom. All rights reserved. + * ================================================================================ + * Licensed 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 + * + * http://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. + * ============LICENSE_END========================================================= + */ +package org.onap.aai.schemaservice.service; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockitoAnnotations; +import org.mockito.Spy; +import org.onap.aai.util.AAIConstants; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; +import static org.junit.jupiter.api.Assertions.*; + +public class AuthorizationServiceTest { + + @Spy + private AuthorizationService authorizationService; + + @BeforeEach + public void setUp() throws NoSuchFieldException, IllegalAccessException { + MockitoAnnotations.openMocks(this); + + Map mockAuthorizedUsers = new HashMap<>(); + mockAuthorizedUsers.put(Base64.getEncoder().encodeToString("john:secret123".getBytes(StandardCharsets.UTF_8)), "admin"); + mockAuthorizedUsers.put(Base64.getEncoder().encodeToString("jane:password456".getBytes(StandardCharsets.UTF_8)), "user"); + + java.lang.reflect.Field field = AuthorizationService.class.getDeclaredField("authorizedUsers"); + field.setAccessible(true); + field.set(authorizationService, mockAuthorizedUsers); + } + + @Test + public void testCheckIfUserAuthorized_authorizedUser() { + String validAuthHeader = Base64.getEncoder().encodeToString("john:secret123".getBytes(StandardCharsets.UTF_8)); + assertTrue(authorizationService.checkIfUserAuthorized(validAuthHeader)); + } + + @Test + public void testCheckIfUserAuthorized_unauthorizedUser() { + String validAuthHeader = Base64.getEncoder().encodeToString("jane:password456".getBytes(StandardCharsets.UTF_8)); + assertFalse(authorizationService.checkIfUserAuthorized(validAuthHeader)); + } + + @Test + public void testCheckIfUserAuthorized_invalidAuthorizationHeader() { + String invalidAuthHeader = "InvalidAuthString"; + assertFalse(authorizationService.checkIfUserAuthorized(invalidAuthHeader)); + } + + @Test + public void testCheckIfUserAuthorized_missingAuthorizationHeader() { + String emptyAuthHeader = ""; + assertFalse(authorizationService.checkIfUserAuthorized(emptyAuthHeader)); + } + + @Test + public void testGetBasicAuthFilePath() { + String expectedPath = AAIConstants.AAI_HOME_ETC_AUTH + AAIConstants.AAI_FILESEP + "realm.properties"; + assertEquals(expectedPath, authorizationService.getBasicAuthFilePath()); + } + + @Test + public void testInit_invalidFormat() { + String invalidEntry = "john:secret123,admin:extra"; + Path mockFile = createMockFile(invalidEntry); + + authorizationService = new AuthorizationService() { + @Override + public String getBasicAuthFilePath() { + return mockFile.toString(); + } + }; + + try { + authorizationService.init(); + fail("Expected RuntimeException due to invalid format in realm.properties"); + } catch (RuntimeException e) { + assertTrue(e.getMessage().contains("This username / pwd is not a valid entry in realm.properties")); + } + } + + + @Test + public void testInit_withInvalidObfuscatedPassword_failsAuthorization() { + // Simulate an invalid obfuscated password entry + String invalidObfuscatedPassword = "OBF:U0002U0004U0005U0006"; + String entryWithInvalidObfuscation = "john:" + invalidObfuscatedPassword + ",admin"; + Path mockFile = createMockFile(entryWithInvalidObfuscation); + + authorizationService = new AuthorizationService() { + @Override + public String getBasicAuthFilePath() { + return mockFile.toString(); + } + }; + + authorizationService.init(); + + // Attempt to authenticate with incorrect password (assuming invalid deobfuscation) + String attemptedPassword = "secret123"; + String encodedAuthHeader = Base64.getEncoder().encodeToString(("john:" + attemptedPassword).getBytes(StandardCharsets.UTF_8)); + + // Since the decoded password doesn't match, the user should not be authorized + + // The obfuscated password doesn't decode to "secret123", so auth should fail + assertFalse(authorizationService.checkIfUserAuthorized(encodedAuthHeader)); + } + + + @Test + public void testInit_fileNotFound_shouldNotThrowButLoadNoUsers() { + authorizationService = new AuthorizationService() { + @Override + public String getBasicAuthFilePath() { + return "src/test/resources/non_existent_file.properties"; + } + }; + + // No exception expected — method should handle missing file gracefully + assertDoesNotThrow(() -> authorizationService.init()); + + // Since the file was not found, no users should be loaded + String dummyAuthHeader = Base64.getEncoder().encodeToString("john:secret123".getBytes(StandardCharsets.UTF_8)); + assertFalse(authorizationService.checkIfUserAuthorized(dummyAuthHeader), "No users should be authorized since file is missing"); + } + + + + private Path createMockFile(String content) { + try { + Path tempFile = Files.createTempFile("realm", ".properties"); + Files.write(tempFile, content.getBytes(StandardCharsets.UTF_8)); + return tempFile; + } catch (IOException e) { + throw new RuntimeException("Error creating mock file", e); + } + } +}