From 290584fe21212aa3768652f8faa9fca50b8851fd Mon Sep 17 00:00:00 2001 From: Neha Naithani Date: Fri, 26 Jan 2024 15:26:17 +1300 Subject: [PATCH] Updated APiHandlerTests --- .../strace/StraceDiagnosticManagerTest.java | 679 ++++++++--------- .../iofog/field_agent/VersionHandlerTest.java | 709 +++++++++--------- .../local_api/ApiHandlerHelpersTest.java | 668 +++++++++-------- 3 files changed, 1027 insertions(+), 1029 deletions(-) diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/strace/StraceDiagnosticManagerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/strace/StraceDiagnosticManagerTest.java index f5c7ff87..f8b0aace 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/strace/StraceDiagnosticManagerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/strace/StraceDiagnosticManagerTest.java @@ -1,353 +1,340 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.diagnostics.strace; -// -//import org.eclipse.iofog.command_line.util.CommandShellExecutor; -//import org.eclipse.iofog.command_line.util.CommandShellResultSet; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.jupiter.api.*; -//import org.junit.jupiter.api.extension.ExtendWith; -//import org.mockito.MockedStatic; -//import org.mockito.Mockito; -//import org.mockito.junit.jupiter.MockitoExtension; -//import org.mockito.junit.jupiter.MockitoSettings; -//import org.mockito.quality.Strictness; -// -//import javax.json.JsonArray; -//import javax.json.JsonObject; -//import javax.json.JsonValue; -//import java.util.ArrayList; -//import java.util.Iterator; -//import java.util.List; -// -//import static org.junit.jupiter.api.Assertions.assertEquals; -//import static org.mockito.ArgumentMatchers.any; -//import static org.mockito.Mockito.*; -// -// -///** -// * Agent Exception -// * -// * @author nehanaithani -// */ -//@ExtendWith(MockitoExtension.class) -//@MockitoSettings(strictness = Strictness.LENIENT) -//@TestInstance(TestInstance.Lifecycle.PER_METHOD) -//public class StraceDiagnosticManagerTest { -// private static StraceDiagnosticManager straceDiagnosticManager; -// private static JsonObject jsonObject; -// private static JsonArray jsonArray; -// private JsonValue jsonValue; -// private static Iterator iterator; -// private static JsonObject microserviceObject; -// private static CommandShellResultSet, List> resultSetWithPath; -// private static List error; -// private static List value; -// private static String microserviceUuid; -// private static MicroserviceStraceData microserviceStraceData; -// private static String MODULE_NAME; -// -// private static MockedStatic commandShellExecutor; -// private static MockedStatic loggingService; -// -// @BeforeEach -// public void setUp() throws Exception { -// microserviceUuid = "microserviceUuid"; -// commandShellExecutor = Mockito.mockStatic(CommandShellExecutor.class); -// loggingService = Mockito.mockStatic(LoggingService.class); -// jsonObject = mock(JsonObject.class); -// jsonArray = mock(JsonArray.class); -// iterator = mock(Iterator.class); -// microserviceObject = mock(JsonObject.class); -// when(jsonArray.iterator()).thenReturn(iterator); -// when(iterator.hasNext()) -// .thenReturn(true, false) -// .thenReturn(false, false); -// when(iterator.next()).thenReturn(microserviceObject); -// when(microserviceObject.containsKey("microserviceUuid")).thenReturn(true); -// when(microserviceObject.getString("microserviceUuid")).thenReturn("microserviceUuid"); -// when(microserviceObject.getBoolean("straceRun")).thenReturn(true); -// -// when(jsonObject.containsKey("straceValues")).thenReturn(true); -// when(jsonObject.getJsonArray("straceValues")).thenReturn(jsonArray); -// error = new ArrayList<>(); -// value = new ArrayList<>(); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// straceDiagnosticManager = spy(StraceDiagnosticManager.getInstance()); -// MODULE_NAME = "STrace Diagnostic Manager"; -// removeDummyMonitoringServices(); -// } -// -// @AfterEach -// public void tearDown() throws Exception { -// commandShellExecutor.close(); -//// reset(CommandShellExecutor.class); -// loggingService.close(); -// reset(iterator); -// microserviceUuid = null; -// jsonObject = null; -// straceDiagnosticManager = null; -// iterator = null; -// reset(microserviceObject); -// microserviceObject.clear(); -// value = null; -// error = null; -// resultSetWithPath = null; -// microserviceStraceData = null; -// MODULE_NAME = null; -// } -// -// /** -// * when updateMonitoringMicroservices is called with valid diagnosticData and StraceRun as true -// */ -// @Test -// public void doesUpdateMonitoringMicroservicesWhenValidMicroserviceUuidAndEnableStraceRun() { -// error = new ArrayList<>(); -// value = new ArrayList<>(); -// value.add("pid 1234"); -// value.add("pid 2345"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); -// verify(jsonObject, times(1)).getJsonArray("straceValues"); -// verify(iterator, atLeastOnce()).hasNext(); +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.diagnostics.strace; + +import org.eclipse.iofog.command_line.util.CommandShellExecutor; +import org.eclipse.iofog.command_line.util.CommandShellResultSet; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import javax.json.JsonArray; +import javax.json.JsonObject; +import javax.json.JsonValue; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + + +/** + * Agent Exception + * + * @author nehanaithani + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@TestInstance(TestInstance.Lifecycle.PER_METHOD) +public class StraceDiagnosticManagerTest { + private static StraceDiagnosticManager straceDiagnosticManager; + private static JsonObject jsonObject; + private static JsonArray jsonArray; + private static Iterator iterator; + private static JsonObject microserviceObject; + private static CommandShellResultSet, List> resultSetWithPath; + private static List error; + private static List value; + private static String microserviceUuid; + private static MicroserviceStraceData microserviceStraceData; + private static String MODULE_NAME; + private static MockedStatic commandShellExecutor; + private static MockedStatic loggingService; + + @BeforeEach + public void setUp() throws Exception { + microserviceUuid = "microserviceUuid"; + commandShellExecutor = Mockito.mockStatic(CommandShellExecutor.class); + loggingService = Mockito.mockStatic(LoggingService.class); + jsonObject = mock(JsonObject.class); + jsonArray = mock(JsonArray.class); + iterator = mock(Iterator.class); + microserviceObject = mock(JsonObject.class); + when(jsonArray.iterator()).thenReturn(iterator); + when(iterator.hasNext()) + .thenReturn(true, false) + .thenReturn(false, false); + when(iterator.next()).thenReturn(microserviceObject); + when(microserviceObject.containsKey("microserviceUuid")).thenReturn(true); + when(microserviceObject.getString("microserviceUuid")).thenReturn("microserviceUuid"); + when(microserviceObject.getBoolean("straceRun")).thenReturn(true); + + when(jsonObject.containsKey("straceValues")).thenReturn(true); + when(jsonObject.getJsonArray("straceValues")).thenReturn(jsonArray); + error = new ArrayList<>(); + value = new ArrayList<>(); + resultSetWithPath = new CommandShellResultSet<>(value, error); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + straceDiagnosticManager = spy(StraceDiagnosticManager.getInstance()); + MODULE_NAME = "STrace Diagnostic Manager"; + removeDummyMonitoringServices(); + } + + @AfterEach + public void tearDown() throws Exception { + commandShellExecutor.close(); +// reset(CommandShellExecutor.class); + loggingService.close(); + reset(iterator); + microserviceUuid = null; + jsonObject = null; + straceDiagnosticManager = null; + iterator = null; + reset(microserviceObject); + microserviceObject.clear(); + value = null; + error = null; + resultSetWithPath = null; + microserviceStraceData = null; + MODULE_NAME = null; + } + + /** + * when updateMonitoringMicroservices is called with valid diagnosticData and StraceRun as true + */ + @Test + public void doesUpdateMonitoringMicroservicesWhenValidMicroserviceUuidAndEnableStraceRun() { + error = new ArrayList<>(); + value = new ArrayList<>(); + value.add("pid 1234"); + value.add("pid 2345"); + resultSetWithPath = new CommandShellResultSet<>(value, error); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); + verify(jsonObject, times(1)).getJsonArray("straceValues"); + verify(iterator, atLeastOnce()).hasNext(); + CommandShellExecutor.executeCommand(any()); + } + + /** + * when updateMonitoringMicroservices is called with valid diagnosticData and StraceRun as false + */ + @Test + public void doesUpdateMonitoringMicroservicesWhenValidMicroserviceUuidAndDisabledStraceRun() { + error = new ArrayList<>(); + value = new ArrayList<>(); + value.add("pid 1234"); + value.add("pid 2345"); + resultSetWithPath = new CommandShellResultSet<>(value, error); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + when(microserviceObject.getBoolean("straceRun")).thenReturn(false); + straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); + verify(jsonObject, times(1)).getJsonArray("straceValues"); + verify(iterator, atLeastOnce()).hasNext(); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Trying to update strace monitoring microservices"); + } + + /** + * when updateMonitoringMicroservices is called with valid diagnosticData and StraceRun as true + * But getPid returns IllegalArgumentException + */ + @Test + public void throwsIllegalExceptionWhenPidByContainerNameIsNotFound() { + straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); + verify(jsonObject, times(1)).getJsonArray("straceValues"); + verify(iterator, atLeastOnce()).hasNext(); +// verify(microserviceObject, atLeastOnce()).getString("microserviceUuid"); +// verify(microserviceObject, atLeastOnce()).getBoolean("straceRun"); // CommandShellExecutor.executeCommand(any()); -// } -// -// /** -// * when updateMonitoringMicroservices is called with valid diagnosticData and StraceRun as false -// */ -// @Test -// public void doesUpdateMonitoringMicroservicesWhenValidMicroserviceUuidAndDisabledStraceRun() { -// error = new ArrayList<>(); -// value = new ArrayList<>(); -// value.add("pid 1234"); -// value.add("pid 2345"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// when(microserviceObject.getBoolean("straceRun")).thenReturn(false); -// straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); -// verify(jsonObject, times(1)).getJsonArray("straceValues"); -// verify(iterator, atLeastOnce()).hasNext(); -// verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Trying to update strace monitoring microservices"); -// } -// -// /** -// * when updateMonitoringMicroservices is called with valid diagnosticData and StraceRun as true -// * But getPid returns IllegalArgumentException -// */ -// @Test -// public void throwsIllegalExceptionWhenPidByContainerNameIsNotFound() { -// straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); -// verify(jsonObject, times(1)).getJsonArray("straceValues"); -// verify(iterator, atLeastOnce()).hasNext(); -//// verify(microserviceObject, atLeastOnce()).getString("microserviceUuid"); -//// verify(microserviceObject, atLeastOnce()).getBoolean("straceRun"); -//// CommandShellExecutor.executeCommand(any()); -//// verify(CommandShellExecutor.class, times(1)); -// verify(LoggingService.class, times(1)); -// LoggingService.logError(any(), any(), any()); -// } -// -// /** -// * when updateMonitoringMicroservices is called with invalid diagnosticData -// * Doesn't contain straceValues -// */ -// @Test -// public void doesNotUpdateMonitoringMicroservicesWhenDiagnosticDataIsInvalid() { -// when(jsonObject.containsKey("straceValues")).thenReturn(false); -// straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); -// Mockito.verify(jsonObject, Mockito.never()).getJsonArray("straceValues"); -// -// } -// -// /** -// * when updateMonitoringMicroservices is called with invalid diagnosticData -// * straceValues is empty -// */ -// @Test -// public void doesNotUpdateMonitoringMicroservicesWhenStraceValuesIsInvalid() { -// straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); -// Mockito.verify(jsonObject, Mockito.atLeastOnce()).getJsonArray("straceValues"); -// Mockito.verify(iterator, atLeastOnce()).hasNext(); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, -// "Finished update strace monitoring microservices"); -// -// } -// -// /** -// * when updateMonitoringMicroservices is called with invalid diagnosticData -// * straceValues doesn't contain microserviceUuid -// */ -// @Test -// public void doesNotUpdateMonitoringMicroservicesWhenStraceValuesHaveNoMicroserviceUuid() { -// when(microserviceObject.containsKey("microserviceUuid")).thenReturn(false); -// straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); -// Mockito.verify(jsonObject, Mockito.atLeastOnce()).getJsonArray("straceValues"); -// Mockito.verify(microserviceObject, Mockito.atLeastOnce()).containsKey("microserviceUuid"); -// Mockito.verify(iterator, Mockito.times(2)).hasNext(); -// Mockito.verify(LoggingService.class, Mockito.times(1)); -// LoggingService.logDebug(MODULE_NAME, -// "Finished update strace monitoring microservices"); -// } -// -// /** -// * when updateMonitoringMicroservices is called with diagnosticData as null -// */ +// verify(CommandShellExecutor.class, times(1)); + verify(LoggingService.class, times(1)); + LoggingService.logError(any(), any(), any()); + } + + /** + * when updateMonitoringMicroservices is called with invalid diagnosticData + * Doesn't contain straceValues + */ + @Test + public void doesNotUpdateMonitoringMicroservicesWhenDiagnosticDataIsInvalid() { + when(jsonObject.containsKey("straceValues")).thenReturn(false); + straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); + Mockito.verify(jsonObject, Mockito.never()).getJsonArray("straceValues"); + + } + + /** + * when updateMonitoringMicroservices is called with invalid diagnosticData + * straceValues is empty + */ + @Test + public void doesNotUpdateMonitoringMicroservicesWhenStraceValuesIsInvalid() { + straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); + Mockito.verify(jsonObject, Mockito.atLeastOnce()).getJsonArray("straceValues"); + Mockito.verify(iterator, atLeastOnce()).hasNext(); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, + "Finished update strace monitoring microservices"); + + } + + /** + * when updateMonitoringMicroservices is called with invalid diagnosticData + * straceValues doesn't contain microserviceUuid + */ + @Test + public void doesNotUpdateMonitoringMicroservicesWhenStraceValuesHaveNoMicroserviceUuid() { + when(microserviceObject.containsKey("microserviceUuid")).thenReturn(false); + straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); + Mockito.verify(jsonObject, Mockito.atLeastOnce()).getJsonArray("straceValues"); + Mockito.verify(microserviceObject, Mockito.atLeastOnce()).containsKey("microserviceUuid"); + Mockito.verify(iterator, Mockito.times(2)).hasNext(); + Mockito.verify(LoggingService.class, Mockito.times(1)); + LoggingService.logDebug(MODULE_NAME, + "Finished update strace monitoring microservices"); + } + + /** + * when updateMonitoringMicroservices is called with diagnosticData as null + */ + @Test + public void doesNotUpdateMonitoringMicroservicesWhenDiagnosticDataIsNull() { + straceDiagnosticManager.updateMonitoringMicroservices(null); + Mockito.verify(jsonObject, Mockito.never()).getJsonArray("straceValues"); + Mockito.verify(LoggingService.class, Mockito.times(1)); + LoggingService.logDebug(MODULE_NAME, + "Finished update strace monitoring microservices"); + } + + /** + * when updateMonitoringMicroservices is called with diagnosticData + * microservice is null + */ + @Test + public void doesNotUpdateMonitoringMicroservicesWhenStraceMicroserviceChangesIsNull() { + when(jsonObject.getJsonArray("straceValues")).thenReturn(null); + straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); + Mockito.verify(jsonObject, Mockito.times(1)).getJsonArray("straceValues"); + Mockito.verify(iterator, Mockito.never()).hasNext(); + Mockito.verify(LoggingService.class, Mockito.times(1)); + LoggingService.logDebug(MODULE_NAME, + "Finished update strace monitoring microservices"); + + } + + /** + * Asserts straceDiagnosticManager.getMonitoringMicroservices() + */ + @Test + public void testGetMonitoringMicroservices() { + assertEquals(0, straceDiagnosticManager.getMonitoringMicroservices().size()); + microserviceStraceData = new MicroserviceStraceData(microserviceUuid, 5, true); + straceDiagnosticManager.getMonitoringMicroservices().add(microserviceStraceData); + assertEquals(1, straceDiagnosticManager.getMonitoringMicroservices().size()); + + } + + /** + * Test enableMicroserviceStraceDiagnostics with valid microserviceUuid + */ + @Test + public void testEnableMicroserviceStraceDiagnosticsWithValidMicroserviceUuid() { + error = new ArrayList<>(); + value = new ArrayList<>(); + value.add("pid 1234"); + value.add("pid 2345"); + resultSetWithPath = new CommandShellResultSet<>(value, error); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + straceDiagnosticManager.enableMicroserviceStraceDiagnostics(microserviceUuid); + Mockito.verify(LoggingService.class, Mockito.times(1)); + LoggingService.logInfo(MODULE_NAME, + "Start enable microservice for strace diagnostics : microserviceUuid"); + LoggingService.logInfo(MODULE_NAME, + "Start getting pid of microservice by container name : microserviceUuid"); + LoggingService.logInfo(MODULE_NAME, + "Finished enable microservice for strace diagnostics : microserviceUuid"); + } + + /** + * Test enableMicroserviceStraceDiagnostics with invalid microserviceUuid + */ + @Test + public void testEnableMicroserviceStraceDiagnosticsWithInvalidMicroserviceUuid() { + error = new ArrayList<>(); + value = new ArrayList<>(); + error.add("error"); + resultSetWithPath = new CommandShellResultSet<>(value, error); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + straceDiagnosticManager.enableMicroserviceStraceDiagnostics(null); + Mockito.verify(LoggingService.class, Mockito.times(1)); + LoggingService.logInfo(MODULE_NAME, + "Start enable microservice for strace diagnostics : null"); + LoggingService.logInfo(MODULE_NAME, + "Start getting pid of microservice by container name : null"); + LoggingService.logInfo(MODULE_NAME, + "Finished enable microservice for strace diagnostics : null"); + LoggingService.logError(any(), any(), any()); + } + + /** + * Test disableMicroserviceStraceDiagnostics with valid microserviceUuid + */ + @Test + public void testDisableMicroserviceStraceDiagnosticsWhenMicroserviceUuidIsPresent() { + microserviceStraceData = new MicroserviceStraceData(microserviceUuid, 5, true); + straceDiagnosticManager.getMonitoringMicroservices().add(microserviceStraceData); + straceDiagnosticManager.disableMicroserviceStraceDiagnostics(microserviceUuid); + assertEquals(0, straceDiagnosticManager.getMonitoringMicroservices().size()); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, + "Disabling microservice strace diagnostics for miroservice : microserviceUuid"); + microserviceStraceData = new MicroserviceStraceData("newMicroserviceUuid", 1234, true); + straceDiagnosticManager.getMonitoringMicroservices().add(microserviceStraceData); + straceDiagnosticManager.disableMicroserviceStraceDiagnostics("Uuid"); + assertEquals(1, straceDiagnosticManager.getMonitoringMicroservices().size()); + } + + /** + * Test disableMicroserviceStraceDiagnostics with microserviceUuid which is not present + */ // @Test -// public void doesNotUpdateMonitoringMicroservicesWhenDiagnosticDataIsNull() { -// straceDiagnosticManager.updateMonitoringMicroservices(null); -// Mockito.verify(jsonObject, Mockito.never()).getJsonArray("straceValues"); -// Mockito.verify(LoggingService.class, Mockito.times(1)); -// LoggingService.logDebug(MODULE_NAME, -// "Finished update strace monitoring microservices"); -// } -// -// /** -// * when updateMonitoringMicroservices is called with diagnosticData -// * microservice is null -// */ -// @Test -// public void doesNotUpdateMonitoringMicroservicesWhenStraceMicroserviceChangesIsNull() { -// when(jsonObject.getJsonArray("straceValues")).thenReturn(null); -// straceDiagnosticManager.updateMonitoringMicroservices(jsonObject); -// Mockito.verify(jsonObject, Mockito.times(1)).getJsonArray("straceValues"); -// Mockito.verify(iterator, Mockito.never()).hasNext(); -// Mockito.verify(LoggingService.class, Mockito.times(1)); -// LoggingService.logDebug(MODULE_NAME, -// "Finished update strace monitoring microservices"); -// -// } -// -// /** -// * Asserts mock is same as the StraceDiagnosticManager.getInstance() -// */ -// @Test -// public void testGetInstanceIsSameAsMock() { -// straceDiagnosticManager = mock(StraceDiagnosticManager.class); -// Mockito.mockStatic(StraceDiagnosticManager.class); -// when(StraceDiagnosticManager.getInstance()).thenReturn(straceDiagnosticManager); -// assertEquals(straceDiagnosticManager, StraceDiagnosticManager.getInstance()); -// } -// -// /** -// * Asserts straceDiagnosticManager.getMonitoringMicroservices() -// */ -// @Test -// public void testGetMonitoringMicroservices() { -// assertEquals(0, straceDiagnosticManager.getMonitoringMicroservices().size()); -// microserviceStraceData = new MicroserviceStraceData(microserviceUuid, 5, true); -// straceDiagnosticManager.getMonitoringMicroservices().add(microserviceStraceData); -// assertEquals(1, straceDiagnosticManager.getMonitoringMicroservices().size()); -// -// } -// -// /** -// * Test enableMicroserviceStraceDiagnostics with valid microserviceUuid -// */ -// @Test -// public void testEnableMicroserviceStraceDiagnosticsWithValidMicroserviceUuid() { -// error = new ArrayList<>(); -// value = new ArrayList<>(); -// value.add("pid 1234"); -// value.add("pid 2345"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// straceDiagnosticManager.enableMicroserviceStraceDiagnostics(microserviceUuid); -// Mockito.verify(LoggingService.class, Mockito.times(1)); -// LoggingService.logInfo(MODULE_NAME, -// "Start enable microservice for strace diagnostics : microserviceUuid"); -// LoggingService.logInfo(MODULE_NAME, -// "Start getting pid of microservice by container name : microserviceUuid"); -// LoggingService.logInfo(MODULE_NAME, -// "Finished enable microservice for strace diagnostics : microserviceUuid"); -// } -// -// /** -// * Test enableMicroserviceStraceDiagnostics with invalid microserviceUuid -// */ -// @Test -// public void testEnableMicroserviceStraceDiagnosticsWithInvalidMicroserviceUuid() { -// error = new ArrayList<>(); -// value = new ArrayList<>(); -// error.add("error"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// straceDiagnosticManager.enableMicroserviceStraceDiagnostics(null); -// Mockito.verify(LoggingService.class, Mockito.times(1)); -// LoggingService.logInfo(MODULE_NAME, -// "Start enable microservice for strace diagnostics : null"); -// LoggingService.logInfo(MODULE_NAME, -// "Start getting pid of microservice by container name : null"); -// LoggingService.logInfo(MODULE_NAME, -// "Finished enable microservice for strace diagnostics : null"); -// LoggingService.logError(any(), any(), any()); -// } -// -// /** -// * Test disableMicroserviceStraceDiagnostics with valid microserviceUuid -// */ -// @Test -// public void testDisableMicroserviceStraceDiagnosticsWhenMicroserviceUuidIsPresent() { -// microserviceStraceData = new MicroserviceStraceData(microserviceUuid, 5, true); -// straceDiagnosticManager.getMonitoringMicroservices().add(microserviceStraceData); -// straceDiagnosticManager.disableMicroserviceStraceDiagnostics(microserviceUuid); -// assertEquals(0, straceDiagnosticManager.getMonitoringMicroservices().size()); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, -// "Disabling microservice strace diagnostics for miroservice : microserviceUuid"); +// public void testDisableMicroserviceStraceDiagnosticsWhenMicroserviceUuidIsNotPresent() { // microserviceStraceData = new MicroserviceStraceData("newMicroserviceUuid", 1234, true); // straceDiagnosticManager.getMonitoringMicroservices().add(microserviceStraceData); // straceDiagnosticManager.disableMicroserviceStraceDiagnostics("Uuid"); -// assertEquals(1, straceDiagnosticManager.getMonitoringMicroservices().size()); -// } -// -// /** -// * Test disableMicroserviceStraceDiagnostics with microserviceUuid which is not present -// */ -//// @Test -//// public void testDisableMicroserviceStraceDiagnosticsWhenMicroserviceUuidIsNotPresent() { -//// microserviceStraceData = new MicroserviceStraceData("newMicroserviceUuid", 1234, true); -//// straceDiagnosticManager.getMonitoringMicroservices().add(microserviceStraceData); -//// straceDiagnosticManager.disableMicroserviceStraceDiagnostics("Uuid"); -//// assertEquals(0, straceDiagnosticManager.getMonitoringMicroservices().size()); -//// -//// } -// -// /** -// * Test disableMicroserviceStraceDiagnostics with microserviceUuid null -// */ -// @Test -// public void testDisableMicroserviceStraceDiagnosticsWhenMicroserviceUuidIsNull() { -// straceDiagnosticManager.disableMicroserviceStraceDiagnostics(null); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, -// "Disabling microservice strace diagnostics for miroservice : null"); -// } -// -// /** -// * method to empty monitoringservices -// */ -// private static void removeDummyMonitoringServices() { -// if (straceDiagnosticManager.getMonitoringMicroservices() != null && -// !straceDiagnosticManager.getMonitoringMicroservices().isEmpty()) { -// for (MicroserviceStraceData data : straceDiagnosticManager.getMonitoringMicroservices()) { -// straceDiagnosticManager.getMonitoringMicroservices().remove(data); -// } -// } +// assertEquals(0, straceDiagnosticManager.getMonitoringMicroservices().size()); // // } -//} \ No newline at end of file + + /** + * Test disableMicroserviceStraceDiagnostics with microserviceUuid null + */ + @Test + public void testDisableMicroserviceStraceDiagnosticsWhenMicroserviceUuidIsNull() { + straceDiagnosticManager.disableMicroserviceStraceDiagnostics(null); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, + "Disabling microservice strace diagnostics for miroservice : null"); + } + + /** + * method to empty monitoringservices + */ + private static void removeDummyMonitoringServices() { + if (straceDiagnosticManager.getMonitoringMicroservices() != null && + !straceDiagnosticManager.getMonitoringMicroservices().isEmpty()) { + for (MicroserviceStraceData data : straceDiagnosticManager.getMonitoringMicroservices()) { + straceDiagnosticManager.getMonitoringMicroservices().remove(data); + } + } + + } +} \ No newline at end of file diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/VersionHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/VersionHandlerTest.java index 1ac932d3..52edf6ad 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/VersionHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/VersionHandlerTest.java @@ -1,354 +1,357 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.field_agent; -// -//import org.eclipse.iofog.command_line.util.CommandShellExecutor; -//import org.eclipse.iofog.command_line.util.CommandShellResultSet; -//import org.eclipse.iofog.field_agent.enums.VersionCommand; -//import org.eclipse.iofog.resource_manager.ResourceManager; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.jupiter.api.AfterEach; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Disabled; -//import org.junit.jupiter.api.Test; -//import org.junit.jupiter.api.extension.ExtendWith; -//import org.mockito.MockedConstruction; -//import org.mockito.MockedStatic; -//import org.mockito.Mockito; -//import org.mockito.junit.jupiter.MockitoExtension; -//import org.mockito.junit.jupiter.MockitoSettings; -//import org.mockito.quality.Strictness; -// -//import javax.json.Json; -//import javax.json.JsonObject; -//import javax.json.JsonObjectBuilder; -// -//import java.io.File; -//import java.io.IOException; -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Objects; -// -//import static org.junit.jupiter.api.Assertions.*; -//import static org.mockito.ArgumentMatchers.*; -//import static org.mockito.Mockito.*; -// -///** -// * @author nehanaithani -// */ -//@ExtendWith(MockitoExtension.class) -//@MockitoSettings(strictness = Strictness.LENIENT) -//public class VersionHandlerTest { -// private VersionHandler versionHandler; -// private JsonObject jsonObject; -// private JsonObjectBuilder jsonObjectBuilder = null; -// private String MODULE_NAME; -// private File file; -// private List error; -// private List value; -// private CommandShellResultSet, List> resultSetWithPath = null; -// private String[] fileList = {"file1", "file2"}; -// private Runtime runtime; -// private MockedStatic loggingServiceMockedStatic; -// private MockedStatic runtimeMockedStatic; -// private MockedStatic commandShellExecutorMockedStatic; -// private MockedConstruction fileMockedConstruction; -//// private MockedStatic versionCommandMockedStatic; -// @BeforeEach -// public void setUp() throws Exception { -// MODULE_NAME = "Version Handler"; -// versionHandler = spy(VersionHandler.class); -// loggingServiceMockedStatic = mockStatic(LoggingService.class); -// runtimeMockedStatic = mockStatic(Runtime.class); -// commandShellExecutorMockedStatic = mockStatic(CommandShellExecutor.class); -// file = mock(File.class); -// runtime = mock(Runtime.class); -// fileMockedConstruction = Mockito.mockConstruction(File.class, (mock, context) -> { -// Mockito.when(mock.list()).thenReturn(fileList); -// }); -//// whenNew(File.class).withParameterTypes(String.class).withArguments(any()).thenReturn(file); -//// VersionCommand versionCommand = mock(VersionCommand.class); -//// versionCommandMockedStatic = mockStatic(VersionCommand.class); -//// when(VersionCommand.parseJson(any())).thenReturn(mock(VersionCommand.class)); -//// when(file.list()).thenReturn(fileList); -// jsonObjectBuilder = Json.createObjectBuilder(); -// error = new ArrayList<>(); -// value = new ArrayList<>(); -// when(Runtime.getRuntime()).thenReturn(runtime); -// } -// -// @AfterEach -// public void tearDown() throws Exception { -// MODULE_NAME = null; -// jsonObject = null; -// error = null; -// value = null; -// fileList = null; -// jsonObjectBuilder = null; -// loggingServiceMockedStatic.close(); -// runtimeMockedStatic.close(); -// commandShellExecutorMockedStatic.close(); -// fileMockedConstruction.close(); -// reset(versionHandler); -//// versionCommandMockedStatic.close(); -// } -// -// /** -// * Test changeVersion when actionData is null -// */ -// @Test -// public void testChangeVersionCommandWhenNull() { -// VersionHandler.changeVersion(null); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Start performing change version operation, received from ioFog controller"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Error performing change version operation : Invalid command"), any()); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Finished performing change version operation, received from ioFog controller"); -// } -// -// /** -// * Test changeVersion when versionCommand is invalid -// */ -// @Test -// public void testChangeVersionCommandWhenNotNull() { -// jsonObject = jsonObjectBuilder -// .add("versionCommand", "versionCommand") -// .add("provisionKey", "provisionKey").build(); -// VersionHandler.changeVersion(jsonObject); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Start performing change version operation, received from ioFog controller"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Error performing change version operation : Invalid command"), any()); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Finished performing change version operation, received from ioFog controller"); -// } -// -// /** -// * Test changeVersion when versionCommand is VersionCommand.ROLLBACK -// * And is not ready to rollback -// */ -// @Test -// public void testChangeVersionCommandRollbackAndSystemIsNotReady() { -// JsonObject jsonObject1 = Json.createObjectBuilder() -// .add("versionCommand", VersionCommand.ROLLBACK.toString()) -// .add("provisionKey", "provisionKey").build(); -// when(file.list()).thenReturn(null); -// VersionHandler.changeVersion(jsonObject1); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Start performing change version operation, received from ioFog controller"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Checking is ready to rollback"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : false"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Finished performing change version operation, received from ioFog controller"); -// } -// -// /** -// * Test changeVersion when versionCommand is VersionCommand.ROLLBACK -// * And is ready to rollback -// * Runtime script exec throws IOException -// */ -// @Test -// @Disabled -// public void throwsIOEXceptionWhenChangeVersionCommandRollback() { -// try { -// jsonObject = jsonObjectBuilder -// .add("versionCommand", VersionCommand.ROLLBACK.toString()) -// .add("provisionKey", "provisionKey").build(); -// when(runtime.exec(anyString())).thenThrow(mock(IOException.class)); -// VersionHandler.changeVersion(jsonObject); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Checking is ready to rollback"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Is ready to rollback : true"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Error executing sh script to change version"), any()); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Finished performing change version operation, received from ioFog controller"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test changeVersion when versionCommand is VersionCommand.ROLLBACK -// * And is ready to rollback -// * Rollback success -// */ -// @Test -// @Disabled -// public void testChangeVersionCommandRollbackSuccess() { -// try { -// jsonObject = jsonObjectBuilder -// .add("versionCommand", VersionCommand.ROLLBACK.toString()) -// .add("provisionKey", "provisionKey").build(); -// when(runtime.exec(anyString())).thenReturn(mock(Process.class)); -// VersionHandler.changeVersion(jsonObject); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Checking is ready to rollback"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Is ready to rollback : true"); -// verify(LoggingService.class, never()); -// LoggingService.logError(eq(MODULE_NAME), eq("Error executing sh script to change version"), any()); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test changeVersion when versionCommand is VersionCommand.UPGRADE -// * And is not readyToUpgrade CommandShellExecutor returns null -// */ -// @Test -// public void testChangeVersionCommandUpgradeWhenCommandShellExecutorReturnsNull() { -// jsonObject = jsonObjectBuilder -// .add("versionCommand", VersionCommand.UPGRADE.toString()) -// .add("provisionKey", "provisionKey").build(); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// VersionHandler.changeVersion(jsonObject); -// verify(CommandShellExecutor.class, atLeastOnce()); -// CommandShellExecutor.executeCommand(any()); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : false"); -// verify(LoggingService.class, never()); -// LoggingService.logDebug(MODULE_NAME, "Performing change version operation"); -// } -// -// /** -// * Test changeVersion when versionCommand is VersionCommand.UPGRADE -// * And is ready to upgrade -// * CommandShellExecutor returns error for lock files -// * And value for fog installed version -// */ -// @Test -// public void testChangeVersionCommandUpgradeWhenCommandShellExecutorReturnsErrorForLockedFile() { -// jsonObject = jsonObjectBuilder -// .add("versionCommand", VersionCommand.UPGRADE.toString()) -// .add("provisionKey", "provisionKey").build(); -// error.add("error"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// List anotherError = new ArrayList<>(); -// List anotherValue = new ArrayList<>(); -// anotherValue.add("1.2.2"); -// CommandShellResultSet, List> anotherResultSetWithPath = new CommandShellResultSet<>(anotherValue, anotherError); -// List fogError = new ArrayList<>(); -// List fogValue = new ArrayList<>(); -// fogValue.add("1.2.3"); -// CommandShellResultSet, List> fogResultSetWithPath = new CommandShellResultSet<>(fogValue, fogError); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath, resultSetWithPath, anotherResultSetWithPath, fogResultSetWithPath); -// VersionHandler.changeVersion(jsonObject); -// verify(CommandShellExecutor.class, atLeastOnce()); -// CommandShellExecutor.executeCommand(any()); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Checking is ready to upgrade"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : true"); -// } -// -// /** -// * Test changeVersion when versionCommand is VersionCommand.UPGRADE -// * And is not ready to upgrade CommandShellExecutor returns locked files -// * And value for fog installed version -// */ -// @Test -// public void testChangeVersionCommandUpgradeWhenCommandShellExecutorReturnsValue() { -// jsonObject = jsonObjectBuilder -// .add("versionCommand", VersionCommand.UPGRADE.toString()) -// .add("provisionKey", "provisionKey").build(); -// value.add("valueSuccess"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// VersionHandler.changeVersion(jsonObject); -// verify(CommandShellExecutor.class, atLeastOnce()); -// CommandShellExecutor.executeCommand(any()); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : false"); -// } -// -// /** -// * Test isReadyToUpgrade -// * When there are no locked files -// * getFogInstalledVersion & getFogCandidateVersion are different -// */ -// @Test -// public void testIsReadyToUpgradeReturnsTrue() { -// error.add("error"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// List anotherError = new ArrayList<>(); -// List anotherValue = new ArrayList<>(); -// anotherValue.add("1.2.2"); -// CommandShellResultSet, List> anotherResultSetWithPath = new CommandShellResultSet<>(anotherValue, anotherError); -// List fogError = new ArrayList<>(); -// List fogValue = new ArrayList<>(); -// fogValue.add("1.2.3"); -// CommandShellResultSet, List> fogResultSetWithPath = new CommandShellResultSet<>(fogValue, fogError); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath, resultSetWithPath, anotherResultSetWithPath, fogResultSetWithPath); -// assertTrue(VersionHandler.isReadyToUpgrade()); -// verify(CommandShellExecutor.class, atLeastOnce()); -// CommandShellExecutor.executeCommand(any()); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Checking is ready to upgrade"); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : true"); -// } -// -// /** -// * Test isReadyToUpgrade -// * When there are no locked files -// * getFogInstalledVersion & getFogCandidateVersion are same -// */ -// @Test -// public void testIsReadyToUpgradeReturnsFalse() { -// error.add("error"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// List anotherError = new ArrayList<>(); -// List anotherValue = new ArrayList<>(); -// anotherValue.add("1.2.2"); -// CommandShellResultSet, List> anotherResultSetWithPath = new CommandShellResultSet<>(anotherValue, anotherError); -// List fogError = new ArrayList<>(); -// List fogValue = new ArrayList<>(); -// fogValue.add("1.2.2"); -// CommandShellResultSet, List> fogResultSetWithPath = new CommandShellResultSet<>(fogValue, fogError); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath, resultSetWithPath, anotherResultSetWithPath, fogResultSetWithPath); -// assertFalse(VersionHandler.isReadyToUpgrade()); -// verify(CommandShellExecutor.class, atLeastOnce()); -// CommandShellExecutor.executeCommand(any()); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : false"); -// } -// -// /** -// * Test isReadyToRollback when there are no backup files -// */ -// @Test -// public void isReadyToRollbackFalse() { -// when(file.list()).thenReturn(null); -// assertFalse(VersionHandler.isReadyToRollback()); +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.field_agent; + +import org.eclipse.iofog.command_line.util.CommandShellExecutor; +import org.eclipse.iofog.command_line.util.CommandShellResultSet; +import org.eclipse.iofog.field_agent.enums.VersionCommand; +import org.eclipse.iofog.resource_manager.ResourceManager; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@Disabled +public class VersionHandlerTest { + private VersionHandler versionHandler; + private JsonObject jsonObject; + private JsonObjectBuilder jsonObjectBuilder = null; + private String MODULE_NAME; + private File file; + private List error; + private List value; + private CommandShellResultSet, List> resultSetWithPath = null; + private String[] fileList = {"file1", "file2"}; + private Runtime runtime; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic runtimeMockedStatic; + private MockedStatic commandShellExecutorMockedStatic; + private MockedConstruction fileMockedConstruction; +// private MockedStatic versionCommandMockedStatic; + @BeforeEach + public void setUp() throws Exception { + MODULE_NAME = "Version Handler"; + versionHandler = spy(VersionHandler.class); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + runtimeMockedStatic = mockStatic(Runtime.class); + commandShellExecutorMockedStatic = mockStatic(CommandShellExecutor.class); + file = mock(File.class); + runtime = mock(Runtime.class); + fileMockedConstruction = Mockito.mockConstruction(File.class, (mock, context) -> { + Mockito.when(mock.list()).thenReturn(fileList); + }); +// whenNew(File.class).withParameterTypes(String.class).withArguments(any()).thenReturn(file); +// VersionCommand versionCommand = mock(VersionCommand.class); +// versionCommandMockedStatic = mockStatic(VersionCommand.class); +// when(VersionCommand.parseJson(any())).thenReturn(mock(VersionCommand.class)); +// when(file.list()).thenReturn(fileList); + jsonObjectBuilder = Json.createObjectBuilder(); + error = new ArrayList<>(); + value = new ArrayList<>(); + when(Runtime.getRuntime()).thenReturn(runtime); + } + + @AfterEach + public void tearDown() throws Exception { + MODULE_NAME = null; + jsonObject = null; + error = null; + value = null; + fileList = null; + jsonObjectBuilder = null; + loggingServiceMockedStatic.close(); + runtimeMockedStatic.close(); + commandShellExecutorMockedStatic.close(); + fileMockedConstruction.close(); + reset(versionHandler); +// versionCommandMockedStatic.close(); + } + + /** + * Test changeVersion when actionData is null + */ + @Test + public void testChangeVersionCommandWhenNull() { + VersionHandler.changeVersion(null); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Start performing change version operation, received from ioFog controller"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Error performing change version operation : Invalid command"), any()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Finished performing change version operation, received from ioFog controller"); + } + + /** + * Test changeVersion when versionCommand is invalid + */ + @Test + public void testChangeVersionCommandWhenNotNull() { + jsonObject = jsonObjectBuilder + .add("versionCommand", "versionCommand") + .add("provisionKey", "provisionKey").build(); + VersionHandler.changeVersion(jsonObject); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Start performing change version operation, received from ioFog controller"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Error performing change version operation : Invalid command"), any()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Finished performing change version operation, received from ioFog controller"); + } + + /** + * Test changeVersion when versionCommand is VersionCommand.ROLLBACK + * And is not ready to rollback + */ + @Test + public void testChangeVersionCommandRollbackAndSystemIsNotReady() { + JsonObject jsonObject1 = Json.createObjectBuilder() + .add("versionCommand", VersionCommand.ROLLBACK.toString()) + .add("provisionKey", "provisionKey").build(); + when(file.list()).thenReturn(null); + VersionHandler.changeVersion(jsonObject1); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Start performing change version operation, received from ioFog controller"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Checking is ready to rollback"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : false"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Finished performing change version operation, received from ioFog controller"); + } + + /** + * Test changeVersion when versionCommand is VersionCommand.ROLLBACK + * And is ready to rollback + * Runtime script exec throws IOException + */ + @Test + @Disabled + public void throwsIOEXceptionWhenChangeVersionCommandRollback() { + try { + jsonObject = jsonObjectBuilder + .add("versionCommand", VersionCommand.ROLLBACK.toString()) + .add("provisionKey", "provisionKey").build(); + when(runtime.exec(anyString())).thenThrow(mock(IOException.class)); + VersionHandler.changeVersion(jsonObject); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Checking is ready to rollback"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Is ready to rollback : true"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Error executing sh script to change version"), any()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Finished performing change version operation, received from ioFog controller"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test changeVersion when versionCommand is VersionCommand.ROLLBACK + * And is ready to rollback + * Rollback success + */ + @Test + @Disabled + public void testChangeVersionCommandRollbackSuccess() { + try { + jsonObject = jsonObjectBuilder + .add("versionCommand", VersionCommand.ROLLBACK.toString()) + .add("provisionKey", "provisionKey").build(); + when(runtime.exec(anyString())).thenReturn(mock(Process.class)); + VersionHandler.changeVersion(jsonObject); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Checking is ready to rollback"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Is ready to rollback : true"); + verify(LoggingService.class, never()); + LoggingService.logError(eq(MODULE_NAME), eq("Error executing sh script to change version"), any()); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test changeVersion when versionCommand is VersionCommand.UPGRADE + * And is not readyToUpgrade CommandShellExecutor returns null + */ + @Test + public void testChangeVersionCommandUpgradeWhenCommandShellExecutorReturnsNull() { + jsonObject = jsonObjectBuilder + .add("versionCommand", VersionCommand.UPGRADE.toString()) + .add("provisionKey", "provisionKey").build(); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + VersionHandler.changeVersion(jsonObject); + verify(CommandShellExecutor.class, atLeastOnce()); + CommandShellExecutor.executeCommand(any()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : false"); + verify(LoggingService.class, never()); + LoggingService.logDebug(MODULE_NAME, "Performing change version operation"); + } + + /** + * Test changeVersion when versionCommand is VersionCommand.UPGRADE + * And is ready to upgrade + * CommandShellExecutor returns error for lock files + * And value for fog installed version + */ + @Test + public void testChangeVersionCommandUpgradeWhenCommandShellExecutorReturnsErrorForLockedFile() { + jsonObject = jsonObjectBuilder + .add("versionCommand", VersionCommand.UPGRADE.toString()) + .add("provisionKey", "provisionKey").build(); + error.add("error"); + resultSetWithPath = new CommandShellResultSet<>(value, error); + List anotherError = new ArrayList<>(); + List anotherValue = new ArrayList<>(); + anotherValue.add("1.2.2"); + CommandShellResultSet, List> anotherResultSetWithPath = new CommandShellResultSet<>(anotherValue, anotherError); + List fogError = new ArrayList<>(); + List fogValue = new ArrayList<>(); + fogValue.add("1.2.3"); + CommandShellResultSet, List> fogResultSetWithPath = new CommandShellResultSet<>(fogValue, fogError); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath, resultSetWithPath, anotherResultSetWithPath, fogResultSetWithPath); + VersionHandler.changeVersion(jsonObject); + verify(CommandShellExecutor.class, atLeastOnce()); + CommandShellExecutor.executeCommand(any()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Checking is ready to upgrade"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : true"); + } + + /** + * Test changeVersion when versionCommand is VersionCommand.UPGRADE + * And is not ready to upgrade CommandShellExecutor returns locked files + * And value for fog installed version + */ + @Test + public void testChangeVersionCommandUpgradeWhenCommandShellExecutorReturnsValue() { + jsonObject = jsonObjectBuilder + .add("versionCommand", VersionCommand.UPGRADE.toString()) + .add("provisionKey", "provisionKey").build(); + value.add("valueSuccess"); + resultSetWithPath = new CommandShellResultSet<>(value, error); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + VersionHandler.changeVersion(jsonObject); + verify(CommandShellExecutor.class, atLeastOnce()); + CommandShellExecutor.executeCommand(any()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : false"); + } + + /** + * Test isReadyToUpgrade + * When there are no locked files + * getFogInstalledVersion & getFogCandidateVersion are different + */ + @Test + public void testIsReadyToUpgradeReturnsTrue() { + error.add("error"); + resultSetWithPath = new CommandShellResultSet<>(value, error); + List anotherError = new ArrayList<>(); + List anotherValue = new ArrayList<>(); + anotherValue.add("1.2.2"); + CommandShellResultSet, List> anotherResultSetWithPath = new CommandShellResultSet<>(anotherValue, anotherError); + List fogError = new ArrayList<>(); + List fogValue = new ArrayList<>(); + fogValue.add("1.2.3"); + CommandShellResultSet, List> fogResultSetWithPath = new CommandShellResultSet<>(fogValue, fogError); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath, resultSetWithPath, anotherResultSetWithPath, fogResultSetWithPath); + assertTrue(VersionHandler.isReadyToUpgrade()); + verify(CommandShellExecutor.class, atLeastOnce()); + CommandShellExecutor.executeCommand(any()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Checking is ready to upgrade"); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : true"); + } + + /** + * Test isReadyToUpgrade + * When there are no locked files + * getFogInstalledVersion & getFogCandidateVersion are same + */ + @Test + public void testIsReadyToUpgradeReturnsFalse() { + error.add("error"); + resultSetWithPath = new CommandShellResultSet<>(value, error); + List anotherError = new ArrayList<>(); + List anotherValue = new ArrayList<>(); + anotherValue.add("1.2.2"); + CommandShellResultSet, List> anotherResultSetWithPath = new CommandShellResultSet<>(anotherValue, anotherError); + List fogError = new ArrayList<>(); + List fogValue = new ArrayList<>(); + fogValue.add("1.2.2"); + CommandShellResultSet, List> fogResultSetWithPath = new CommandShellResultSet<>(fogValue, fogError); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath, resultSetWithPath, anotherResultSetWithPath, fogResultSetWithPath); + assertFalse(VersionHandler.isReadyToUpgrade()); + verify(CommandShellExecutor.class, atLeastOnce()); + CommandShellExecutor.executeCommand(any()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Is ready to upgrade : false"); + } + + /** + * Test isReadyToRollback when there are no backup files + */ + @Test + public void isReadyToRollbackFalse() { + fileMockedConstruction.close(); + fileMockedConstruction = Mockito.mockConstruction(File.class, (mock, context) -> { + Mockito.when(mock.list()).thenReturn(null); + }); + assertFalse(VersionHandler.isReadyToRollback()); + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : false"); + } + + /** + * Test isReadyToRollback when there are no backup files + */ + @Test + public void isReadyToRollbackTrue() { + assertTrue(VersionHandler.isReadyToRollback()); // Mockito.verify(file).list(); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : false"); -// } -// -// /** -// * Test isReadyToRollback when there are no backup files -// */ -// @Test -// public void isReadyToRollbackTrue() { -// assertTrue(VersionHandler.isReadyToRollback()); -// Mockito.verify(file).list(); -// verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : true"); -// } -//} \ No newline at end of file + verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : true"); + } +} \ No newline at end of file diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ApiHandlerHelpersTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ApiHandlerHelpersTest.java index ffac00e7..06f6471d 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ApiHandlerHelpersTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ApiHandlerHelpersTest.java @@ -1,330 +1,338 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.buffer.ByteBuf; -//import io.netty.handler.codec.http.*; -//import org.eclipse.iofog.microservice.MicroserviceStatus; -//import org.eclipse.iofog.utils.logging.LoggingService; -//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.MockedConstruction; -//import org.mockito.MockedStatic; -//import org.mockito.Mockito; -//import org.mockito.junit.jupiter.MockitoExtension; -//import org.mockito.junit.jupiter.MockitoSettings; -//import org.mockito.quality.Strictness; -// -//import java.io.BufferedReader; -//import java.io.FileReader; -//import java.io.IOException; -//import java.io.Reader; -// -//import static io.netty.handler.codec.http.HttpResponseStatus.*; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static org.junit.jupiter.api.Assertions.*; -//import static org.mockito.Mockito.*; -//import static org.mockito.Mockito.when; -// -///** -// * @author nehanaithani -// * -// */ -//@ExtendWith(MockitoExtension.class) -//@MockitoSettings(strictness = Strictness.LENIENT) -//public class ApiHandlerHelpersTest { -// private HttpRequest request; -// private HttpMethod expectedMethod; -// private String contentType; -// private String content; -// private HttpHeaders httpHeaders; -// private ByteBuf byteBuf; -// private DefaultFullHttpResponse defaultResponse; -// private BufferedReader bufferedReader; -// private FileReader fileReader; -// private MockedStatic apiHandlerHelpersMockedStatic; -// private MockedStatic loggingServiceMockedStatic; -// private MockedConstruction bufferedReaderMockedConstruction; -// -// @BeforeEach -// public void setUp() throws Exception { -// apiHandlerHelpersMockedStatic = mockStatic(ApiHandlerHelpers.class, Mockito.CALLS_REAL_METHODS); -// loggingServiceMockedStatic = mockStatic(LoggingService.class); -// request = mock(HttpRequest.class); -// httpHeaders = mock(HttpHeaders.class); -// byteBuf = mock(ByteBuf.class); -// bufferedReader = mock(BufferedReader.class); -// fileReader = mock(FileReader.class); -// expectedMethod = HttpMethod.POST; -// contentType = "Application/json"; -// content = "response content"; -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK); -// bufferedReaderMockedConstruction = mockConstruction(BufferedReader.class, (mock, context) -> { -// when(mock.readLine()).thenReturn("token"); -// }); -//// Mockito.whenNew(BufferedReader.class) -//// .withParameterTypes(Reader.class) -//// .withArguments(Mockito.any(Reader.class)) -//// .thenReturn(bufferedReader); -//// Mockito.whenNew(FileReader.class) -//// .withParameterTypes(String.class) -//// .withArguments(Mockito.anyString()) -//// .thenReturn(fileReader); -// } -// -// @AfterEach -// public void tearDown() throws Exception { -// Mockito.reset(request, httpHeaders, byteBuf); -// loggingServiceMockedStatic.close(); -// apiHandlerHelpersMockedStatic.close(); -// bufferedReaderMockedConstruction.close(); -// -// } -// -// /** -// * Test validate method when expectedMethod and request method are same -// */ -// @Test -// public void testValidateMethodWhenEqual() { -// try { -// Mockito.when(request.method()).thenReturn(HttpMethod.POST); -// assertTrue(ApiHandlerHelpers.validateMethod(request, expectedMethod)); -// } catch (Exception e){ -// fail("This should not happen"); -// } -// } -// /** -// * Test validate method when expectedMethod and request method are different -// */ -// @Test -// public void testValidateMethodWhenUnEqual() { -// try { -// Mockito.when(request.method()).thenReturn(HttpMethod.GET); -// assertFalse(ApiHandlerHelpers.validateMethod(request, expectedMethod)); -// } catch (Exception e){ -// fail("This should not happen"); -// } -// } -// -// /** -// * Test validateContentType when contentType is not present in request -// */ -// @Test -// public void testValidateContentType() { -// try { -// assertEquals("Incorrect content type ", ApiHandlerHelpers.validateContentType(request, contentType)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test validateContentType when contentType is not present in request -// */ -// @Test -// public void testValidateContentTypeAreDifferent() { -// try { -// Mockito.when(request.headers()).thenReturn(httpHeaders); -// Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn("text/html"); -// assertEquals("Incorrect content type text/html", ApiHandlerHelpers.validateContentType(request, contentType)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test validateContentType when contentType in request is same -// */ -// @Test -// public void testValidateContentTypeAreSame() { -// try { -// Mockito.when(request.headers()).thenReturn(httpHeaders); -// Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); -// assertNull(ApiHandlerHelpers.validateContentType(request, contentType)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test validateAccessToken when false -// */ -// @Test -// public void testValidateAccessTokenFalse() { -// try { -// assertFalse(ApiHandlerHelpers.validateAccessToken(request)); -//// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test validateAccessToken when true -// */ -// @Test -// public void testValidateAccessTokenTrue() { -// try { -// Mockito.when(request.headers()).thenReturn(httpHeaders); -// Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("token"); -//// Mockito.when(bufferedReader.readLine()).thenReturn("token"); -// assertTrue(ApiHandlerHelpers.validateAccessToken(request)); -//// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test validateAccessToken when true -// */ -// @Test -// public void testValidateAccesswhenFetchTokenThrowsException() { -// try { -// Mockito.when(request.headers()).thenReturn(httpHeaders); -// Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("token"); -// Mockito.when(bufferedReader.readLine()).thenThrow(mock(IOException.class)); -// assertFalse(ApiHandlerHelpers.validateAccessToken(request)); -//// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); -// LoggingService.logError(Mockito.eq("Local API"), Mockito.eq("unable to load api token"), -// Mockito.any()); -// -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test successResponse when outputBuffer and content is null & -// * returns DefaultFullHttpResponse -// */ -// @Test -// public void testSuccessResponseWhenByteBuffAndContentAreNull() { -// assertEquals(new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK), -// ApiHandlerHelpers.successResponse(null, null)); -// } -// -// /** -// * Test successResponse when outputBuffer and content is null -// */ -// @Test -// public void testSuccessResponseWhenContentIsNull() { -// assertEquals(defaultResponse, ApiHandlerHelpers.successResponse(byteBuf, null)); -// } -// -// /** -// * Test successResponse when outputBuffer and content is null -// */ -// @Test -// public void testSuccessResponseWhenContentNotNull() { -// FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, byteBuf); -// HttpUtil.setContentLength(res, byteBuf.readableBytes()); -// assertEquals(res, ApiHandlerHelpers.successResponse(byteBuf, content)); -// } -// -// /** -// * Test methodNotAllowedResponse -// */ -// @Test -// public void testMethodNotAllowedResponse() { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); -// assertEquals(defaultResponse, ApiHandlerHelpers.methodNotAllowedResponse()); -// } -// -// /** -// * Test badRequestResponse when byteBuf & content is null -// */ -// @Test -// public void testBadRequestResponseByteBufAndContentIsNull() { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); -// assertEquals(defaultResponse, ApiHandlerHelpers.badRequestResponse(null, null)); -// } -// -// /** -// * Test badRequestResponse when content is null -// */ -// @Test -// public void testBadRequestResponseContentIsNull() { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); -// assertEquals(defaultResponse, ApiHandlerHelpers.badRequestResponse(byteBuf, null)); -// } -// -// /** -// * Test badRequestResponse when content is not null -// */ -// @Test -// public void testBadRequestResponseNotNull() { -// FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// HttpUtil.setContentLength(res, byteBuf.readableBytes()); -// assertEquals(res, ApiHandlerHelpers.badRequestResponse(byteBuf, content)); -// } -// -// /** -// * Test unauthorizedResponse when byteBuf & content is null -// */ -// @Test -// public void testUnauthorizedResponseByteBufAndContentIsNull() { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED); -// assertEquals(defaultResponse, ApiHandlerHelpers.unauthorizedResponse(null, null)); -// -// } -// /** -// * Test unauthorizedResponse when byteBuf & content is not null -// */ -// @Test -// public void testUnauthorizedResponse() { -// FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); -// HttpUtil.setContentLength(res, byteBuf.readableBytes()); -// assertEquals(res, ApiHandlerHelpers.unauthorizedResponse(byteBuf, content)); -// } -// -// /** -// * Test notFoundResponse -// */ -// @Test -// public void testNotFoundResponseByteBufAndContentIsNull() { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); -// assertEquals(defaultResponse, ApiHandlerHelpers.notFoundResponse(null, null)); -// } -// -// /** -// * Test notFoundResponse -// */ -// @Test -// public void testNotFoundResponse() { -// FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, byteBuf); -// HttpUtil.setContentLength(res, byteBuf.readableBytes()); -// assertEquals(res, ApiHandlerHelpers.notFoundResponse(byteBuf, content)); -// } -// -// /** -// * Test internalServerErrorResponse -// */ -// @Test -// public void testInternalServerErrorResponseByteBufAndContentIsNull() { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR); -// assertEquals(defaultResponse, ApiHandlerHelpers.internalServerErrorResponse(null, null)); -// } -// /** -// * Test internalServerErrorResponse -// */ -// @Test -// public void testInternalServerErrorResponse() { -// FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, byteBuf); -// HttpUtil.setContentLength(res, byteBuf.readableBytes()); -// assertEquals(res, ApiHandlerHelpers.internalServerErrorResponse(byteBuf, content)); -// } -// -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.*; +import org.eclipse.iofog.microservice.MicroserviceStatus; +import org.eclipse.iofog.utils.logging.LoggingService; +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.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; + +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.mockito.Mockito.when; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class ApiHandlerHelpersTest { + private HttpRequest request; + private HttpMethod expectedMethod; + private String contentType; + private String content; + private HttpHeaders httpHeaders; + private ByteBuf byteBuf; + private DefaultFullHttpResponse defaultResponse; + private BufferedReader bufferedReader; + private FileReader fileReader; + private MockedStatic apiHandlerHelpersMockedStatic; + private MockedStatic loggingServiceMockedStatic; + private MockedConstruction bufferedReaderMockedConstruction; + private MockedConstruction fileReaderMockedConstruction; + + @BeforeEach + public void setUp() throws Exception { + apiHandlerHelpersMockedStatic = mockStatic(ApiHandlerHelpers.class, Mockito.CALLS_REAL_METHODS); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + request = mock(HttpRequest.class); + httpHeaders = mock(HttpHeaders.class); + byteBuf = mock(ByteBuf.class); + bufferedReader = mock(BufferedReader.class); + fileReader = mock(FileReader.class); + expectedMethod = HttpMethod.POST; + contentType = "Application/json"; + content = "response content"; + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK); + fileReaderMockedConstruction = mockConstruction(FileReader.class, (mock, context) -> { + + }); + bufferedReaderMockedConstruction = mockConstruction(BufferedReader.class, (mock, context) -> { + when(mock.readLine()).thenReturn("token"); + }); +// Mockito.whenNew(BufferedReader.class) +// .withParameterTypes(Reader.class) +// .withArguments(Mockito.any(Reader.class)) +// .thenReturn(bufferedReader); +// Mockito.whenNew(FileReader.class) +// .withParameterTypes(String.class) +// .withArguments(Mockito.anyString()) +// .thenReturn(fileReader); + } + + @AfterEach + public void tearDown() throws Exception { + Mockito.reset(request, httpHeaders, byteBuf); + loggingServiceMockedStatic.close(); + apiHandlerHelpersMockedStatic.close(); + bufferedReaderMockedConstruction.close(); + fileReaderMockedConstruction.close(); + + } + + /** + * Test validate method when expectedMethod and request method are same + */ + @Test + public void testValidateMethodWhenEqual() { + try { + Mockito.when(request.method()).thenReturn(HttpMethod.POST); + assertTrue(ApiHandlerHelpers.validateMethod(request, expectedMethod)); + } catch (Exception e){ + fail("This should not happen"); + } + } + /** + * Test validate method when expectedMethod and request method are different + */ + @Test + public void testValidateMethodWhenUnEqual() { + try { + Mockito.when(request.method()).thenReturn(HttpMethod.GET); + assertFalse(ApiHandlerHelpers.validateMethod(request, expectedMethod)); + } catch (Exception e){ + fail("This should not happen"); + } + } + + /** + * Test validateContentType when contentType is not present in request + */ + @Test + public void testValidateContentType() { + try { + assertEquals("Incorrect content type ", ApiHandlerHelpers.validateContentType(request, contentType)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test validateContentType when contentType is not present in request + */ + @Test + public void testValidateContentTypeAreDifferent() { + try { + Mockito.when(request.headers()).thenReturn(httpHeaders); + Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn("text/html"); + assertEquals("Incorrect content type text/html", ApiHandlerHelpers.validateContentType(request, contentType)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test validateContentType when contentType in request is same + */ + @Test + public void testValidateContentTypeAreSame() { + try { + Mockito.when(request.headers()).thenReturn(httpHeaders); + Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); + assertNull(ApiHandlerHelpers.validateContentType(request, contentType)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test validateAccessToken when false + */ + @Test + public void testValidateAccessTokenFalse() { + try { + assertFalse(ApiHandlerHelpers.validateAccessToken(request)); +// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test validateAccessToken when true + */ + @Test + public void testValidateAccessTokenTrue() { + try { + Mockito.when(request.headers()).thenReturn(httpHeaders); + Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("token"); +// Mockito.when(bufferedReader.readLine()).thenReturn("token"); + assertTrue(ApiHandlerHelpers.validateAccessToken(request)); +// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test validateAccessToken when true + */ + @Test + public void testValidateAccesswhenFetchTokenThrowsException() { + try { + Mockito.when(request.headers()).thenReturn(httpHeaders); + Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("token"); + bufferedReaderMockedConstruction.close(); + bufferedReaderMockedConstruction = mockConstruction(BufferedReader.class, (mock, context) -> { + when(mock.readLine()).thenThrow(IOException.class); + }); + assertFalse(ApiHandlerHelpers.validateAccessToken(request)); +// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); + LoggingService.logError(Mockito.eq("Local API"), Mockito.eq("unable to load api token"), + Mockito.any()); + + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test successResponse when outputBuffer and content is null & + * returns DefaultFullHttpResponse + */ + @Test + public void testSuccessResponseWhenByteBuffAndContentAreNull() { + assertEquals(new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK), + ApiHandlerHelpers.successResponse(null, null)); + } + + /** + * Test successResponse when outputBuffer and content is null + */ + @Test + public void testSuccessResponseWhenContentIsNull() { + assertEquals(defaultResponse, ApiHandlerHelpers.successResponse(byteBuf, null)); + } + + /** + * Test successResponse when outputBuffer and content is null + */ + @Test + public void testSuccessResponseWhenContentNotNull() { + FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK, byteBuf); + HttpUtil.setContentLength(res, byteBuf.readableBytes()); + assertEquals(res, ApiHandlerHelpers.successResponse(byteBuf, content)); + } + + /** + * Test methodNotAllowedResponse + */ + @Test + public void testMethodNotAllowedResponse() { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); + assertEquals(defaultResponse, ApiHandlerHelpers.methodNotAllowedResponse()); + } + + /** + * Test badRequestResponse when byteBuf & content is null + */ + @Test + public void testBadRequestResponseByteBufAndContentIsNull() { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); + assertEquals(defaultResponse, ApiHandlerHelpers.badRequestResponse(null, null)); + } + + /** + * Test badRequestResponse when content is null + */ + @Test + public void testBadRequestResponseContentIsNull() { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST); + assertEquals(defaultResponse, ApiHandlerHelpers.badRequestResponse(byteBuf, null)); + } + + /** + * Test badRequestResponse when content is not null + */ + @Test + public void testBadRequestResponseNotNull() { + FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + HttpUtil.setContentLength(res, byteBuf.readableBytes()); + assertEquals(res, ApiHandlerHelpers.badRequestResponse(byteBuf, content)); + } + + /** + * Test unauthorizedResponse when byteBuf & content is null + */ + @Test + public void testUnauthorizedResponseByteBufAndContentIsNull() { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED); + assertEquals(defaultResponse, ApiHandlerHelpers.unauthorizedResponse(null, null)); + + } + /** + * Test unauthorizedResponse when byteBuf & content is not null + */ + @Test + public void testUnauthorizedResponse() { + FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); + HttpUtil.setContentLength(res, byteBuf.readableBytes()); + assertEquals(res, ApiHandlerHelpers.unauthorizedResponse(byteBuf, content)); + } + + /** + * Test notFoundResponse + */ + @Test + public void testNotFoundResponseByteBufAndContentIsNull() { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND); + assertEquals(defaultResponse, ApiHandlerHelpers.notFoundResponse(null, null)); + } + + /** + * Test notFoundResponse + */ + @Test + public void testNotFoundResponse() { + FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, byteBuf); + HttpUtil.setContentLength(res, byteBuf.readableBytes()); + assertEquals(res, ApiHandlerHelpers.notFoundResponse(byteBuf, content)); + } + + /** + * Test internalServerErrorResponse + */ + @Test + public void testInternalServerErrorResponseByteBufAndContentIsNull() { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR); + assertEquals(defaultResponse, ApiHandlerHelpers.internalServerErrorResponse(null, null)); + } + /** + * Test internalServerErrorResponse + */ + @Test + public void testInternalServerErrorResponse() { + FullHttpResponse res = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, byteBuf); + HttpUtil.setContentLength(res, byteBuf.readableBytes()); + assertEquals(res, ApiHandlerHelpers.internalServerErrorResponse(byteBuf, content)); + } + +} \ No newline at end of file