From 906ef920094d5ee7526bc891e29d10d19c8411e3 Mon Sep 17 00:00:00 2001 From: Neha Naithani Date: Tue, 30 Jan 2024 12:22:49 +1300 Subject: [PATCH] Updated tests --- iofog-agent-daemon/build.gradle | 6 - .../utils/device_info/ArchitectureType.java | 2 +- .../command_line/CommandLineActionTest.java | 4 +- .../CommandLineConfigParamTest.java | 2 +- .../command_line/CommandLineParserTest.java | 2 +- .../util/CommandShellExecutorTest.java | 9 +- .../util/CommandShellResultSetTest.java | 2 +- .../diagnostics/ImageDownloadManagerTest.java | 31 +- .../strace/MicroserviceStraceDataTest.java | 2 +- .../strace/StraceDiagnosticManagerTest.java | 19 +- .../field_agent/FieldAgentStatusTest.java | 2 +- .../iofog/field_agent/FieldAgentTest.java | 254 +- .../iofog/field_agent/VersionHandlerTest.java | 9 +- .../field_agent/enums/VersionCommandTest.java | 7 +- .../local_api/ApiHandlerHelpersTest.java | 6 +- .../local_api/BluetoothApiHandlerTest.java | 2 +- .../local_api/CommandLineApiHandlerTest.java | 5 +- .../iofog/local_api/ConfigApiHandlerTest.java | 3 +- .../local_api/ControlSignalSentInfoTest.java | 2 +- .../ControlWebsocketHandlerTest.java | 8 +- .../local_api/ControlWebsocketWorkerTest.java | 17 +- .../local_api/DeprovisionApiHandlerTest.java | 2 +- .../GetConfigurationHandlerTest.java | 2 +- .../iofog/local_api/GpsApiHandlerTest.java | 3 +- .../iofog/local_api/InfoApiHandlerTest.java | 2 - .../LocalApiServerPipelineFactoryTest.java | 12 +- .../iofog/local_api/LocalApiServerTest.java | 2 +- .../iofog/local_api/LocalApiStatusTest.java | 2 +- .../iofog/local_api/LogApiHandlerTest.java | 2 +- .../iofog/local_api/MessageCallbackTest.java | 8 +- .../message_bus/IOMessageListenerTest.java | 4 +- .../iofog/message_bus/MessageArchiveTest.java | 21 +- .../message_bus/MessageBusServerTest.java | 2 +- .../message_bus/MessageBusStatusTest.java | 2 +- .../iofog/message_bus/MessageBusTest.java | 27 +- .../iofog/message_bus/MessageBusUtilTest.java | 2 +- .../message_bus/MessageIdGeneratorTest.java | 2 +- .../message_bus/MessagePublisherTest.java | 11 +- .../message_bus/MessageReceiverTest.java | 3 +- .../iofog/message_bus/MessageTest.java | 16 +- .../process_manager/ContainerManagerTest.java | 2 +- .../process_manager/ContainerTaskTest.java | 4 +- .../iofog/process_manager/DockerUtilTest.java | 90 +- .../ProcessManagerStatusTest.java | 8 +- .../process_manager/ProcessManagerTest.java | 81 +- .../RestartStuckCheckerTest.java | 2 +- .../process_manager/StatsCallbackTest.java | 2 +- .../pruning/DockerPruningManagerTest.java | 4 +- .../ResourceConsumptionManagerStatusTest.java | 2 +- .../ResourceConsumptionManagerTest.java | 3 +- .../ResourceManagerStatusTest.java | 12 +- .../resource_manager/ResourceManagerTest.java | 4 +- .../StatusReporterStatusTest.java | 2 +- .../status_reporter/StatusReporterTest.java | 2 +- .../supervisor/SupervisorStatusTest.java | 2 +- .../iofog/supervisor/SupervisorTest.java | 3 - .../iofog/utils/CmdPropertiesTest.java | 458 +-- .../eclipse/iofog/utils/OrchestratorTest.java | 1268 +++---- .../configuration/ConfigurationTest.java | 3087 ++++++++--------- .../device_info/ArchitectureTypeTest.java | 116 +- .../iofog/utils/logging/LogFormatterTest.java | 2 +- .../utils/logging/LoggingServiceTest.java | 2 +- 62 files changed, 2540 insertions(+), 3135 deletions(-) diff --git a/iofog-agent-daemon/build.gradle b/iofog-agent-daemon/build.gradle index 2bd2660e..624dc64a 100644 --- a/iofog-agent-daemon/build.gradle +++ b/iofog-agent-daemon/build.gradle @@ -1,7 +1,6 @@ plugins { id 'com.github.johnrengelman.shadow' version '8.1.1' id 'jacoco' -// id "org.jetbrains.kotlin.jvm" version "1.9.22" } description = 'iofog-agent-daemon' @@ -13,7 +12,6 @@ dependencies { implementation 'com.jcraft:jsch:0.1.55' implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.1' implementation 'org.apache.httpcomponents:httpmime:4.5.7' -// implementation 'junit:junit:4.13.2' implementation 'org.junit.jupiter:junit-jupiter-api:5.10.0' implementation 'com.github.oshi:oshi-core:6.4.0' implementation 'org.slf4j:slf4j-nop:2.0.7' @@ -27,10 +25,6 @@ dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.10.0' testRuntimeOnly("org.junit.platform:junit-platform-launcher") testImplementation 'org.testng:testng:7.7.0' -// testImplementation 'org.powermock:powermock-module-junit4-rule:2.0.9' -// testImplementation 'org.powermock:powermock-module-junit4:2.0.9' -// testImplementation 'org.powermock:powermock-api-mockito2:2.0.9' -// testImplementation 'org.powermock:powermock-core:2.0.9' } processResources { diff --git a/iofog-agent-daemon/src/main/java/org/eclipse/iofog/utils/device_info/ArchitectureType.java b/iofog-agent-daemon/src/main/java/org/eclipse/iofog/utils/device_info/ArchitectureType.java index f194709a..8973e084 100644 --- a/iofog-agent-daemon/src/main/java/org/eclipse/iofog/utils/device_info/ArchitectureType.java +++ b/iofog-agent-daemon/src/main/java/org/eclipse/iofog/utils/device_info/ArchitectureType.java @@ -40,7 +40,7 @@ public int getCode() { * common type for popular arm architectures: * arm, arm32, aarch64, armv{VERSION}{CODE} */ - ARM("^(arm|arm32|armv[0-9]+.*|aarch64)$") { + ARM("^(arm|arm32|arm64|armv[0-9]+.*|aarch64)$") { @Override public int getCode() { return 2; diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineActionTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineActionTest.java index 525642a0..20649a8c 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineActionTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineActionTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -80,7 +80,6 @@ public void setup() { .thenReturn(new HashMap<>()) .thenThrow(new Exception("item not found or defined more than once")); - // CommandProperties mock Mockito.when(CmdProperties.getVersion()).thenReturn("1.2.2"); Mockito.when(CmdProperties.getVersionMessage()).thenReturn(version); Mockito.when(CmdProperties.getDeprovisionMessage()).thenReturn("Deprovisioning from controller ... %s"); @@ -108,7 +107,6 @@ public void tearDown() throws Exception { @Test public void testGetKeys() { Assertions.assertFalse(CommandLineAction.HELP_ACTION.getKeys().isEmpty()); -// Assertions.assertTrue(isEqual(stop, CommandLineAction.getActionByKey("stop").getKeys())); } /** diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineConfigParamTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineConfigParamTest.java index 0ec5c7c4..b2348a0d 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineConfigParamTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineConfigParamTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineParserTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineParserTest.java index 383c3ae7..06c0fc98 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineParserTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/CommandLineParserTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/util/CommandShellExecutorTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/util/CommandShellExecutorTest.java index 397bd258..17a75cfd 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/util/CommandShellExecutorTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/util/CommandShellExecutorTest.java @@ -1,7 +1,7 @@ package org.eclipse.iofog.command_line.util; /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -29,7 +29,6 @@ */ @ExtendWith(MockitoExtension.class) public class CommandShellExecutorTest { - private static CommandShellExecutor commandShellExecutor; private CommandShellResultSet, List> commandShellResultSet; private String command; List value; @@ -37,15 +36,11 @@ public class CommandShellExecutorTest { @BeforeAll public static void setUp() throws Exception { - commandShellExecutor = spy(new CommandShellExecutor()); + spy(new CommandShellExecutor()); } @AfterAll public static void tearDown() throws Exception { -// command = null; -// value = null; -// errors = null; -// commandShellResultSet = null; } /** diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/util/CommandShellResultSetTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/util/CommandShellResultSetTest.java index 04ca4246..2e2eeb9c 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/util/CommandShellResultSetTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/command_line/util/CommandShellResultSetTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/ImageDownloadManagerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/ImageDownloadManagerTest.java index bb32949d..be55eec9 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/ImageDownloadManagerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/ImageDownloadManagerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -55,7 +55,6 @@ public class ImageDownloadManagerTest { @Mock private static DockerUtil dockerUtil; private static String microserviceUuid; - private static DockerClient dockerClient; private static MockedStatic cmdShellExecutor; private static Container container; private static CommandShellResultSet, List> resultSetWithPath; @@ -69,19 +68,8 @@ public class ImageDownloadManagerTest { public void setUp() throws Exception { cmdShellExecutor = mockStatic(CommandShellExecutor.class); microserviceUuid = "microservice-id"; -// mockStatic(Configuration.class); -// when(Configuration.getDockerUrl()).thenReturn("unix://dockerUrl/"); -// when(Configuration.getDockerApiVersion()).thenReturn("19.03.1"); orchestrator = mock(Orchestrator.class); mock(DefaultDockerClientConfig.class); -// DockerClientBuilder dockerClientBuilder = mock(DockerClientBuilder.class); -// mockStatic(DockerClientBuilder.class); - -// dockerClient = mock(DockerClient.class); -// mockStatic(DockerClient.class); -// when(DockerClientBuilder.getInstance(any(DefaultDockerClientConfig.class))).thenReturn(dockerClientBuilder); -// when(dockerClientBuilder.build()).thenReturn(dockerClient); -// dockerUtil = mock(DockerUtil.class); dockerUtilStatic = mockStatic(DockerUtil.class); container = mock(Container.class); when(DockerUtil.getInstance()).thenReturn(dockerUtil); @@ -94,13 +82,6 @@ public void setUp() throws Exception { when(dockerUtil.getContainer(microserviceUuid)).thenReturn(Optional.of(container)); cmdShellExecutor.when(() -> CommandShellExecutor.executeCommand(any())) .thenReturn(resultSetWithPath); -// cmdShellExecutor.when(CommandShellExecutor::executeCommand(any())).thenReturn(resultSetWithPath); - -// error = new ArrayList<>(); -// value = new ArrayList<>(); -// value.add("local/path/newFile"); -// resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { @@ -116,8 +97,6 @@ public void tearDown() throws Exception { value = null; resultSetWithPath = null; MODULE_NAME = null; -// dockerClient.close(); -// reset(dockerClientBuilder); cmdShellExecutor.close(); reset(dockerUtil); dockerUtilStatic.close(); @@ -146,7 +125,6 @@ public void createImageSnapshotWhenCommandExecuteReturnsSuccess() throws Excepti verify(dockerUtil, atLeastOnce()).getContainer(microserviceUuid); verify(orchestrator, atLeastOnce()).sendFileToController(any(), any()); Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Image snapshot deleted"); LoggingService.logDebug(MODULE_NAME, "Finished Create image snapshot"); } @@ -177,16 +155,9 @@ public void createImageSnapshotWhenCommandExecuteReturnsError() throws Exception */ @Test public void createImageSnapshotWhenCommandExecuteReturnsEmpty() throws Exception { -// error = new ArrayList<>(); -// value = new ArrayList<>(); -// resultSetWithPath = new CommandShellResultSet<>(value, error); when(dockerUtil.getContainer(microserviceUuid)).thenReturn(Optional.of(container)); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); ImageDownloadManager.createImageSnapshot(orchestrator, microserviceUuid); verify(dockerUtil, atLeastOnce()).getContainer(microserviceUuid); -// verify(orchestrator, never()).sendFileToController(any(), any()); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Finished Create image snapshot"); } /** diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/strace/MicroserviceStraceDataTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/strace/MicroserviceStraceDataTest.java index d99170de..f566df36 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/strace/MicroserviceStraceDataTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/diagnostics/strace/MicroserviceStraceDataTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 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 f8b0aace..20eb4811 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,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -90,7 +90,6 @@ public void setUp() throws Exception { @AfterEach public void tearDown() throws Exception { commandShellExecutor.close(); -// reset(CommandShellExecutor.class); loggingService.close(); reset(iterator); microserviceUuid = null; @@ -151,10 +150,6 @@ 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()); } @@ -302,18 +297,6 @@ public void testDisableMicroserviceStraceDiagnosticsWhenMicroserviceUuidIsPresen 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 */ diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/FieldAgentStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/FieldAgentStatusTest.java index 7ecf4e35..8b136ceb 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/FieldAgentStatusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/FieldAgentStatusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/FieldAgentTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/FieldAgentTest.java index 1bbf6ffb..4342a6cf 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/FieldAgentTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/FieldAgentTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -68,12 +68,9 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; - -import static java.nio.charset.StandardCharsets.UTF_8; import static org.eclipse.iofog.resource_manager.ResourceManager.COMMAND_USB_INFO; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.*; -//import static org.powermock.api.mockito.Mockito.*; /** * @author nehanaithani @@ -91,18 +88,7 @@ public class FieldAgentTest { private URL url; private HttpURLConnection httpURLConnection; private FieldAgentStatus fieldAgentStatus; - private MicroserviceManager microserviceManager; - private SshProxyManager sshProxyManager; - private ProcessManager processManager; - private MessageBus messageBus; - private LocalApi localApi; - private Thread thread; - private BufferedReader bufferedReader; - private InputStreamReader inputStreamReader; - private ResourceManagerStatus resourceManagerStatus; private Method method = null; - private IOFogNetworkInterfaceManager ioFogNetworkInterfaceManager; - private EdgeResourceManager edgeResourceManager; private MockedStatic loggingServiceMockedStatic; private MockedStatic statusReporterMockedStatic; private MockedStatic configurationMockedStatic; @@ -138,25 +124,22 @@ public void setUp() throws Exception { bufferedReaderMockedStatic = mockStatic(BufferedReader.class); inputStreamReaderMockedStatic = mockStatic(InputStreamReader.class); edgeResourceManagerMockedStatic = mockStatic(EdgeResourceManager.class); - orchestrator = Mockito.mock(Orchestrator.class); - sshProxyManager = Mockito.mock(SshProxyManager.class); - processManager = Mockito.mock(ProcessManager.class); - messageBus = Mockito.mock(MessageBus.class); - localApi = Mockito.mock(LocalApi.class); - resourceManagerStatus = Mockito.mock(ResourceManagerStatus.class); - edgeResourceManager = Mockito.mock(EdgeResourceManager.class); + ProcessManager processManager = Mockito.mock(ProcessManager.class); + MessageBus messageBus = Mockito.mock(MessageBus.class); + LocalApi localApi = Mockito.mock(LocalApi.class); + ResourceManagerStatus resourceManagerStatus = Mockito.mock(ResourceManagerStatus.class); + EdgeResourceManager edgeResourceManager = Mockito.mock(EdgeResourceManager.class); mockConfiguration(); mockOthers(); fieldAgent = Mockito.spy(FieldAgent.getInstance()); fieldAgentStatus = Mockito.mock(FieldAgentStatus.class); - ioFogNetworkInterfaceManager = Mockito.mock(IOFogNetworkInterfaceManager.class); MODULE_NAME = "Field Agent"; when(StatusReporter.getFieldAgentStatus()).thenReturn(fieldAgentStatus); when(StatusReporter.setFieldAgentStatus()).thenReturn(fieldAgentStatus); when(StatusReporter.setResourceManagerStatus()).thenReturn(resourceManagerStatus); when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.NOT_PROVISIONED); - microserviceManager = Mockito.mock(MicroserviceManager.class); + MicroserviceManager microserviceManager = Mockito.mock(MicroserviceManager.class); microserviceManagerMockedStatic = mockStatic(MicroserviceManager.class); orchestratorMockedConstruction = mockConstruction(Orchestrator.class, (mock, context) -> { when(mock.request(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) @@ -174,39 +157,25 @@ public void setUp() throws Exception { when(mock.readLine()).thenReturn("Response from HAL").thenReturn(null); }); -// Mockito.whenNew(Orchestrator.class).withNoArguments().thenReturn(orchestrator); -// Mockito.whenNew(SshProxyManager.class).withArguments(Mockito.any(SshConnection.class)).thenReturn(sshProxyManager); -// whenNew(URL.class).withArguments(Mockito.any()).thenReturn(url); - // Mockito.whenNew(InputStreamReader.class).withParameterTypes(InputStream.class, Charset.class). -// withArguments(Mockito.any(String.class), Mockito.eq(UTF_8)).thenReturn(inputStreamReader); -// Mockito.whenNew(InputStreamReader.class).withParameterTypes(InputStream.class, Charset.class). -// withArguments(Mockito.eq(null), Mockito.eq(UTF_8)).thenReturn(inputStreamReader); -// Mockito.whenNew(BufferedReader.class).withArguments(inputStreamReader).thenReturn(bufferedReader); when(MicroserviceManager.getInstance()).thenReturn(microserviceManager); when(EdgeResourceManager.getInstance()).thenReturn(edgeResourceManager); when(ProcessManager.getInstance()).thenReturn(processManager); when(MessageBus.getInstance()).thenReturn(messageBus); when(LocalApi.getInstance()).thenReturn(localApi); Mockito.doNothing().when(processManager).deleteRemainingMicroservices(); -// url = Mockito.mock(URL.class); -// bufferedReader = Mockito.mock(BufferedReader.class); -// inputStreamReader = Mockito.mock(InputStreamReader.class); when(VersionHandler.isReadyToUpgrade()).thenReturn(false); when(VersionHandler.isReadyToRollback()).thenReturn(false); -// jsonObjectBuilder = Json.createObjectBuilder(); -// jsonObject = jsonObjectBuilder -// .add("uuid", "uuid") -// .add("token", "token") -// .add("message", "success").build(); -// provisionJsonObject = jsonObjectBuilder -// .add("uuid", "uuid") -// .add("token", "token") -// .add("message", "success").build(); + jsonObjectBuilder = Json.createObjectBuilder(); + jsonObject = jsonObjectBuilder + .add("uuid", "uuid") + .add("token", "token") + .add("message", "success").build(); + provisionJsonObject = jsonObjectBuilder + .add("uuid", "uuid") + .add("token", "token") + .add("message", "success").build(); Mockito.doNothing().when(processManager).updateMicroserviceStatus(); -// setMock(fieldAgent,microserviceManager,orchestrator, sshProxyManager, edgeResourceManager); - - } @AfterEach @@ -235,45 +204,16 @@ public void tearDown() throws Exception { instance.set(null, null); MODULE_NAME = null; fieldAgent = null; - Mockito.reset(fieldAgentStatus, orchestrator, inputStreamReader); + Mockito.reset(fieldAgentStatus, orchestrator); if (method != null) { method.setAccessible(false); } jsonObject = null; } - /** - * Set a mock to the {@link FieldAgent} instance - * Throws {@link RuntimeException} in case if reflection failed, see a {@link Field#set(Object, Object)} method description. - * @param mock the mock to be inserted to a class - */ -// private void setMock(FieldAgent mock, MicroserviceManager m1,Orchestrator m2, SshProxyManager m3, EdgeResourceManager m4) { -// try { -// Field instance = FieldAgent.class.getDeclaredField("instance"); -// instance.setAccessible(true); -// instance.set(instance, mock); -// Field microserviceManager = FieldAgent.class.getDeclaredField("microserviceManager"); -// instance.setAccessible(true); -// instance.set(microserviceManager, m1); -// Field orchestrator = FieldAgent.class.getDeclaredField("orchestrator"); -// instance.setAccessible(true); -// instance.set(orchestrator, m2); -// Field sshProxyManager = FieldAgent.class.getDeclaredField("sshProxyManager"); -// instance.setAccessible(true); -// instance.set(sshProxyManager, m3); -// Field edgeResourceManager = FieldAgent.class.getDeclaredField("edgeResourceManager"); -// instance.setAccessible(true); -// instance.set(edgeResourceManager, m4); -// -// } catch (Exception e) { -// throw new RuntimeException(e); -// } -// } public void initiateMockStart() { - thread = Mockito.mock(Thread.class); + Thread thread = Mockito.mock(Thread.class); try { -// whenNew(Thread.class).withParameterTypes(Runnable.class,String.class).withArguments(Mockito.any(Runnable.class), -// Mockito.anyString()).thenReturn(thread); Mockito.doNothing().when(thread).start(); fieldAgent.start(); } catch (Exception e) { @@ -352,14 +292,6 @@ public void testProvisionWhenControllerStatusIsNotProvisioned() { assertTrue(response.containsKey("message")); assertEquals("success", response.getString("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("processMicroserviceConfig", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("processRoutes", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("notifyModules"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadEdgeResources", anyBoolean()); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); } catch (Exception e) { @@ -382,14 +314,6 @@ public void testProvisionWhenWhenPostFogConfigGPSCoordinatesNull() { assertEquals("success", response.getString("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent, Mockito.atLeastOnce()).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("processMicroserviceConfig", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("processRoutes", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadEdgeResources", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, Mockito.times(2)).invoke("notifyModules"); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); Mockito.verify(Configuration.class, Mockito.atLeastOnce()); @@ -414,14 +338,6 @@ public void testProvisionWhenPostFogConfigGPSCoordinatesAreInvalid() { assertEquals("success", response.getString("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("processMicroserviceConfig", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("processRoutes", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadEdgeResources", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, Mockito.times(2)).invoke("notifyModules"); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); Mockito.verify(Configuration.class, Mockito.atLeastOnce()); @@ -449,14 +365,6 @@ public void throwsCertificationExceptionWhenOrchestratorRequestWithConfigIsCalle assertEquals("success", response.getString("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadEdgeResources", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("processMicroserviceConfig", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("processRoutes", any()); -// Mockito.verifyPrivate(fieldAgent, times(2)).invoke("notifyModules"); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); Mockito.verify(Configuration.class, Mockito.atLeastOnce()); @@ -485,15 +393,6 @@ public void testProvisionWhenPostFogConfigGPSCoordinatesAreValid() { assertEquals("success", response.getString("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("processMicroserviceConfig", any()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("processRoutes", any()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadEdgeResources", anyBoolean()); -// -// Mockito.verifyPrivate(fieldAgent, Mockito.times(2)).invoke("notifyModules"); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); Mockito.verify(Configuration.class, Mockito.atLeastOnce()); @@ -532,14 +431,6 @@ public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturns assertEquals("success", response.getString("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("processMicroserviceConfig", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("processRoutes", any()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadEdgeResources", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, Mockito.times(2)).invoke("notifyModules"); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); Mockito.verify(Configuration.class, Mockito.atLeastOnce()); @@ -575,14 +466,6 @@ public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturns assertEquals("success", response.getString("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("processMicroserviceConfig", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("processRoutes", any()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadEdgeResources", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, times(2)).invoke("notifyModules"); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); Mockito.verify(Configuration.class, Mockito.atLeastOnce()); @@ -627,14 +510,6 @@ public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturns assertEquals("success", response.getString("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("processMicroserviceConfig", any()); -// Mockito.verifyPrivate(fieldAgent).invoke("processRoutes", any()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadEdgeResources", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, times(2)).invoke("notifyModules"); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); Mockito.verify(Configuration.class, Mockito.atLeastOnce()); @@ -712,11 +587,6 @@ public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturns assertTrue(response.containsKey("message")); Mockito.verify(orchestrator).provision(eq("provisonKey")); Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadEdgeResources", anyBoolean()); Mockito.verify(ProcessManager.class, Mockito.atLeastOnce()); ProcessManager.getInstance(); Mockito.verify(Configuration.class, Mockito.atLeastOnce()); @@ -769,10 +639,6 @@ public void throwsExceptionWhenOrchestratorRequestIsCalled() { when(orchestrator.request(eq("microservices"), any(), any(), any())).thenThrow(new CertificateException("Certificate Error")); fieldAgent.provision("provisonKey"); Mockito.verify(orchestrator).provision(eq("provisonKey")); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); Mockito.verify(LoggingService.class, Mockito.never()); LoggingService.logError(eq(MODULE_NAME), eq("Unable to post ioFog config "), any()); Mockito.verify(LoggingService.class); @@ -804,11 +670,6 @@ public void throwsAgentUserExceptionWhenLoadRegistriestIsCalledInProvision() { when(orchestrator.request(eq("registries"), any(), any(), any())).thenThrow(new AgentUserException("Agent user error")); fieldAgent.provision("provisonKey"); Mockito.verify(orchestrator).provision(eq("provisonKey")); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadEdgeResources", anyBoolean()); Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logError(eq(MODULE_NAME), eq("Unable to get registries"), any()); Mockito.verify(LoggingService.class, Mockito.never()); @@ -834,18 +695,12 @@ public void throwsExceptionWhenSendHWInfoFromHalToControllerIsCalledInProvision( when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); when(orchestrator.provision(any())).thenReturn(jsonObject); when(orchestrator.request(any(), any(), any(), any())).thenReturn(mock(JsonObject.class)); -// Mockito.whenNew(BufferedReader.class).withArguments(inputStreamReader).thenThrow(new Exception("invalid operation")); JsonObject provisioningResult = fieldAgent.provision("provisonKey"); assertTrue(provisioningResult.containsKey("status")); assertTrue(provisioningResult.containsKey("errorMessage")); assertEquals("failed", provisioningResult.getString("status")); assertEquals("invalid operation", provisioningResult.getString("errorMessage")); Mockito.verify(orchestrator).provision(eq("provisonKey")); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadEdgeResources", anyBoolean()); Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); } catch (AgentSystemException e) { @@ -864,7 +719,6 @@ public void testDeProvisionFailureWithExpiredToken() { initiateMockStart(); String response = fieldAgent.deProvision(true); assertTrue(response.equals("\nFailure - not provisioned")); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(orchestrator, never()).request(eq("deprovision"), eq(RequestType.POST), eq(null), any()); Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logInfo(MODULE_NAME, "Finished Deprovisioning : Failure - not provisioned"); @@ -883,7 +737,6 @@ public void testDeProvisionSuccessWithExpiredToken() { when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); String response = fieldAgent.deProvision(true); assertTrue(response.equals("\nSuccess - tokens, identifiers and keys removed")); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(orchestrator, never()).request(eq("deprovision"), eq(RequestType.POST), eq(null), any()); Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logInfo(MODULE_NAME, "Start Deprovisioning"); @@ -905,7 +758,6 @@ public void testDeProvisionSuccessWithNotExpiredToken() { when(orchestrator.request(eq("deprovision"), any(), any(), any())).thenReturn(mock(JsonObject.class)); String response = fieldAgent.deProvision(false); assertTrue(response.equals("\nSuccess - tokens, identifiers and keys removed")); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(orchestrator).request(eq("deprovision"), eq(RequestType.POST), eq(null), any()); Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logInfo(MODULE_NAME, "Finished Deprovisioning : Success - tokens, identifiers and keys removed"); @@ -926,7 +778,6 @@ public void throwsExceptionWhenOrchestratorRequestIsCalledForDeProvisioning() { when(orchestrator.request(eq("deprovision"), any(), any(), any())).thenThrow(new Exception("Error while deProvsioning")); String response = fieldAgent.deProvision(false); assertTrue(response.equals("\nSuccess - tokens, identifiers and keys removed")); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(orchestrator).request(eq("deprovision"), eq(RequestType.POST), eq(null), any()); Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logError(eq(MODULE_NAME),eq("Unable to make deprovision request "), any()); @@ -947,7 +798,6 @@ public void throwsExceptionWhenUpdatingConfigForDeProvisioning() { when(orchestrator.request(eq("deprovision"), any(), any(), any())).thenThrow(new SSLHandshakeException("Invalid operation")); String response = fieldAgent.deProvision(false); assertTrue(response.equals("\nSuccess - tokens, identifiers and keys removed")); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(orchestrator).request(eq("deprovision"), eq(RequestType.POST), eq(null), any()); Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logError(eq(MODULE_NAME),eq("Unable to make deprovision request due to broken certificate "), any()); @@ -970,7 +820,6 @@ public void throwsSSLHandshakeExceptionWhenOrchestratorRequestIsCalledForDeProvi Configuration.saveConfigUpdates(); String response = fieldAgent.deProvision(false); assertTrue(response.equals("\nSuccess - tokens, identifiers and keys removed")); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(orchestrator).request(eq("deprovision"), eq(RequestType.POST), eq(null), any()); Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); LoggingService.logError(eq(MODULE_NAME),eq("Error saving config updates"), any()); @@ -989,7 +838,6 @@ public void testInstanceConfigUpdatedWhenControllerStatusIsNotProvisioned() { when(orchestrator.request(eq("config"), any(), any(), any())).thenReturn(mock(JsonObject.class)); fieldAgent.instanceConfigUpdated(); Mockito.verify(orchestrator).update(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("postFogConfig"); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logInfo(MODULE_NAME, "Post ioFog config"); Mockito.verify(LoggingService.class, never()); @@ -1010,7 +858,6 @@ public void testInstanceConfigUpdatedWhenControllerStatusIsProvisioned() { when(orchestrator.request(eq("config"), any(), any(), any())).thenReturn(mock(JsonObject.class)); fieldAgent.instanceConfigUpdated(); Mockito.verify(orchestrator).update(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("postFogConfig"); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logInfo(MODULE_NAME, "Post ioFog config"); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1032,7 +879,6 @@ public void throwsSSLHandshakeExceptionWhenOrchestratorIsCalledToUpdateConfigura when(orchestrator.request(eq("config"), any(), any(), any())).thenThrow(new SSLHandshakeException("Invalid operation")); fieldAgent.instanceConfigUpdated(); Mockito.verify(orchestrator).update(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("postFogConfig"); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService. logError(eq(MODULE_NAME), eq("Unable to post ioFog config due to broken certificate "), any()); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1054,7 +900,6 @@ public void throwsExceptionWhenOrchestratorIsCalledToUpdateConfiguration() { when(orchestrator.request(eq("config"), any(), any(), any())).thenThrow(new Exception("Invalid operation")); fieldAgent.instanceConfigUpdated(); Mockito.verify(orchestrator).update(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("postFogConfig"); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService. logError(eq(MODULE_NAME), eq("Unable to post ioFog config "), any()); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1072,12 +917,6 @@ public void throwsExceptionWhenOrchestratorIsCalledToUpdateConfiguration() { public void testStartWhenControllerStatusIsNotProvisioned() { try { initiateMockStart(); -// Mockito.verifyPrivate(fieldAgent).invoke("ping"); -// Mockito.verifyPrivate(fieldAgent).invoke("getFogConfig"); -// Mockito.verifyPrivate(fieldAgent,never()).invoke("isControllerConnected", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, never()).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); -// Mockito.verifyPrivate(fieldAgent, never()).invoke("loadRegistries", anyBoolean()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Start the Field Agent"); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1102,12 +941,6 @@ public void testStartWhenControllerConnectionIsBroken() { when(orchestrator.ping()).thenReturn(false); when(fieldAgentStatus.isControllerVerified()).thenReturn(true); initiateMockStart(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("ping"); -// Mockito.verifyPrivate(fieldAgent).invoke("getFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("isControllerConnected", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, never()).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadRegistries", anyBoolean()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Finished Ping : " + false); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1136,12 +969,6 @@ public void testStartWhenControllerConnectionIsBrokenAndNotVerified() { when(orchestrator.ping()).thenReturn(false); when(fieldAgentStatus.isControllerVerified()).thenReturn(false); initiateMockStart(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("ping"); -// Mockito.verifyPrivate(fieldAgent).invoke("getFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("isControllerConnected", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, never()).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadRegistries", anyBoolean()); LoggingService.logInfo(MODULE_NAME, "Started Ping"); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Finished Ping : " + false); @@ -1165,12 +992,6 @@ public void testStartWhenControllerIsConnectedAndStatusIsProvisioned() { when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); when(orchestrator.ping()).thenReturn(true); initiateMockStart(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("ping"); -// Mockito.verifyPrivate(fieldAgent).invoke("getFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("isControllerConnected", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadRegistries", anyBoolean()); LoggingService.logInfo(MODULE_NAME, "Finished Ping : " + true); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "checked is Controller Connected : true "); @@ -1207,12 +1028,6 @@ public void testStartWhenControllerIsConnectedAndStatusIsProvisionedInitializati when(orchestrator.ping()).thenReturn(true); initiateMockStart(); Mockito.verify(orchestrator).ping(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("ping"); -// Mockito.verifyPrivate(fieldAgent).invoke("getFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("isControllerConnected", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent, never()).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadRegistries", anyBoolean()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Finished Ping : " + true); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1235,7 +1050,6 @@ public void testGetFogStatus() { JsonObject output = (JsonObject) method.invoke(fieldAgent); assertTrue(output.containsKey("daemonStatus")); assertTrue(output.getString("ipAddress").equals("ip")); -// Mockito.verifyPrivate(fieldAgent).invoke("getFogStatus"); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "get Fog Status"); } catch (Exception e){ @@ -1256,7 +1070,6 @@ public void testDeleteNodeSuccessWhenControllerStatusIsNotProvisioned() { method.invoke(fieldAgent); Mockito.verify(orchestrator).request(eq("delete-node"), eq(RequestType.DELETE), eq(null), eq(null)); Mockito.verify(fieldAgent).deProvision(eq(false)); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "start deleting current fog node from controller and make it deprovision"); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1280,7 +1093,6 @@ public void testDeleteNodeSuccessWhenControllerStatusIsProvisioned() { method.invoke(fieldAgent); Mockito.verify(orchestrator).request(eq("delete-node"), eq(RequestType.DELETE), eq(null), eq(null)); Mockito.verify(fieldAgent).deProvision(eq(false)); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logInfo(MODULE_NAME, "Finished Deprovisioning : Success - tokens, identifiers and keys removed"); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1306,7 +1118,6 @@ public void throwsExceptionWhenDeleteNode() { method.invoke(fieldAgent); Mockito.verify(orchestrator).request(eq("delete-node"), eq(RequestType.DELETE), eq(null), eq(null)); Mockito.verify(fieldAgent).deProvision(eq(false)); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("notProvisioned"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("deprovision"), eq(RequestType.POST), eq(null), any()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logError(eq(MODULE_NAME), eq("Can't send delete node command"), any()); @@ -1333,7 +1144,6 @@ public void testRebootSuccess() { method = FieldAgent.class.getDeclaredMethod("reboot"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent).invoke("reboot"); Mockito.verify(CommandShellExecutor.class, atLeastOnce()); CommandShellExecutor.executeCommand(any()); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1361,7 +1171,6 @@ public void testRebootFailureWhenCommandShellExecutorReturnsError() { method = FieldAgent.class.getDeclaredMethod("reboot"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent).invoke("reboot"); Mockito.verify(CommandShellExecutor.class, atLeastOnce()); CommandShellExecutor.executeCommand(any()); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1383,7 +1192,6 @@ public void testRebootFailureWhenCommandShellExecutorReturnsNull() { method = FieldAgent.class.getDeclaredMethod("reboot"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent).invoke("reboot"); Mockito.verify(CommandShellExecutor.class, atLeastOnce()); CommandShellExecutor.executeCommand(any()); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1404,7 +1212,6 @@ public void testChangeVersionSuccess() { method = FieldAgent.class.getDeclaredMethod("changeVersion"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent).invoke("changeVersion"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("version"), eq(RequestType.GET), eq(null), eq(null)); Mockito.verify(VersionHandler.class, atLeastOnce()); VersionHandler.changeVersion(any()); @@ -1430,9 +1237,7 @@ public void throwsCertificateExceptionWhenCalledForChangeVersion() { method = FieldAgent.class.getDeclaredMethod("changeVersion"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent).invoke("changeVersion"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("version"), eq(RequestType.GET), eq(null), eq(null)); -// Mockito.verifyPrivate(fieldAgent).invoke("verificationFailed", any()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logWarning(MODULE_NAME, "controller verification failed: BROKEN_CERTIFICATE"); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1455,9 +1260,7 @@ public void throwsExceptionWhenCalledForChangeVersion() { method = FieldAgent.class.getDeclaredMethod("changeVersion"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent).invoke("changeVersion"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("version"), eq(RequestType.GET), eq(null), eq(null)); -// Mockito.verifyPrivate(fieldAgent, never()).invoke("verificationFailed", any()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logError(eq(MODULE_NAME), eq("Unable to get version command"), any()); } catch (Exception e){ @@ -1476,7 +1279,6 @@ public void testUpdateDiagnostics() { method = FieldAgent.class.getDeclaredMethod("updateDiagnostics"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent, Mockito.atLeastOnce()).invoke("updateDiagnostics"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("strace"), eq(RequestType.GET), eq(null), eq(null)); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logInfo(MODULE_NAME, "Start update diagnostics"); @@ -1500,9 +1302,7 @@ public void throwsCertificateExceptionWhenUpdateDiagnostics() { method = FieldAgent.class.getDeclaredMethod("updateDiagnostics"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent).invoke("updateDiagnostics"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("strace"), eq(RequestType.GET), eq(null), eq(null)); -// Mockito.verifyPrivate(fieldAgent).invoke("verificationFailed", any()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logWarning(MODULE_NAME, "controller verification failed: BROKEN_CERTIFICATE"); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1525,9 +1325,7 @@ public void throwsExceptionWhenUpdateDiagnostics() { method = FieldAgent.class.getDeclaredMethod("updateDiagnostics"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent).invoke("updateDiagnostics"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("strace"), eq(RequestType.GET), eq(null), eq(null)); -// Mockito.verifyPrivate(fieldAgent, never()).invoke("verificationFailed", any()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logError(eq(MODULE_NAME), eq("Unable to get diagnostics update"), any()); } catch (Exception e){ @@ -1548,7 +1346,6 @@ public void throwsExceptionWhenGetProxyConfigIsCalled() { method = FieldAgent.class.getDeclaredMethod("getProxyConfig"); method.setAccessible(true); method.invoke(fieldAgent); -// Mockito.verifyPrivate(fieldAgent, Mockito.atLeastOnce()).invoke("getProxyConfig"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("tunnel"), eq(RequestType.GET), eq(null), eq(null)); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logError(eq(MODULE_NAME), eq("Unable to get proxy config "), any()); @@ -1578,7 +1375,6 @@ public void testGetProxyConfigsuccess() { JsonObject response = (JsonObject) method.invoke(fieldAgent); assertTrue(response.containsKey("uuid")); assertEquals("response proxy", response.getString("uuid")); -// Mockito.verifyPrivate(fieldAgent, Mockito.atLeastOnce()).invoke("getProxyConfig"); Mockito.verify(orchestrator, atLeastOnce()).request(eq("tunnel"), eq(RequestType.GET), eq(null), eq(null)); Mockito.verify(LoggingService.class, never()); LoggingService.logError(eq(MODULE_NAME), eq("Unable to get proxy config "), any()); @@ -1598,10 +1394,7 @@ public void testSendUSBInfoFromHalToController() { when(orchestrator.request(eq(COMMAND_USB_INFO), any(), any(), any())).thenReturn(jsonObject); initiateMockStart(); fieldAgent.sendUSBInfoFromHalToController(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("getResponse", any()); Mockito.verify(orchestrator, atLeastOnce()).request(eq("config"), eq(RequestType.PATCH), eq(null), any()); - /*Mockito.verify(StatusReporter.class, atLeastOnce()); - StatusReporter.setResourceManagerStatus();*/ Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Start send USB Info from hal To Controller"); Mockito.verify(LoggingService.class, atLeastOnce()); @@ -1622,7 +1415,6 @@ public void throwsExceptionWhenSendUSBInfoFromHalToController() { when(orchestrator.request(eq(COMMAND_USB_INFO), any(), any(), any())).thenThrow(mock(Exception.class)); initiateMockStart(); fieldAgent.sendUSBInfoFromHalToController(); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("getResponse", any()); Mockito.verify(orchestrator, atLeastOnce()).request(eq("config"), eq(RequestType.PATCH), eq(null), any()); Mockito.verify(StatusReporter.class, atLeastOnce()); StatusReporter.setResourceManagerStatus(); @@ -1702,10 +1494,6 @@ public void throwsExceptionWhenOrchestratorEdgeRequestIsCalled() { when(orchestrator.request(eq("edgeResources"), any(), any(), any())).thenThrow(new CertificateException("Certificate Error")); fieldAgent.provision("provisonKey"); Mockito.verify(orchestrator).provision(eq("provisonKey")); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); Mockito.verify(LoggingService.class, Mockito.never()); LoggingService.logError(eq(MODULE_NAME), eq("Unable to post ioFog config "), any()); Mockito.verify(LoggingService.class); @@ -1746,12 +1534,6 @@ public void testProvisionWhenLoadEdgeResourcesReturnList() { when(orchestrator.request(eq("edgeResources"), any(), any(), any())).thenReturn(edgeResources); fieldAgent.provision("provisonKey"); Mockito.verify(orchestrator).provision(eq("provisonKey")); -// Mockito.verifyPrivate(fieldAgent).invoke("postFogConfig"); -// Mockito.verifyPrivate(fieldAgent).invoke("sendHWInfoFromHalToController"); -// Mockito.verifyPrivate(fieldAgent, atLeastOnce()).invoke("loadRegistries", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadMicroservices", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("loadEdgeResources", anyBoolean()); -// Mockito.verifyPrivate(fieldAgent).invoke("saveFile", any(), eq("/etc/iofog-agent/edge_resources.json")); Mockito.verify(orchestrator).request(eq("edgeResources"), eq(RequestType.GET), eq(null), eq(null)); Mockito.verify(LoggingService.class); LoggingService.logDebug(eq(MODULE_NAME), eq("Finished loading edge resources...")); 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 52edf6ad..64b28a67 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,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -64,7 +64,6 @@ public class VersionHandlerTest { private MockedStatic runtimeMockedStatic; private MockedStatic commandShellExecutorMockedStatic; private MockedConstruction fileMockedConstruction; -// private MockedStatic versionCommandMockedStatic; @BeforeEach public void setUp() throws Exception { MODULE_NAME = "Version Handler"; @@ -77,11 +76,6 @@ public void setUp() throws Exception { 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<>(); @@ -350,7 +344,6 @@ public void isReadyToRollbackFalse() { @Test public void isReadyToRollbackTrue() { assertTrue(VersionHandler.isReadyToRollback()); -// Mockito.verify(file).list(); verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME, "Is ready to rollback : true"); } diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/enums/VersionCommandTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/enums/VersionCommandTest.java index f00269d0..dc82f9a9 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/enums/VersionCommandTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/field_agent/enums/VersionCommandTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -34,7 +34,6 @@ @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) public class VersionCommandTest { - private String versionCommand; private JsonObject jsonObject; private JsonObjectBuilder jsonObjectBuilder = null; @@ -51,7 +50,6 @@ public void tearDown() throws Exception { * Test parseCommandString with null command */ @Test -// (expected = UnknownVersionCommandException.class) public void throwsUnknownVersionCommandExceptionWhenParseCommandStringWithNullCommand() { assertThrows(UnknownVersionCommandException.class, () -> VersionCommand.parseCommandString(null)); } @@ -60,7 +58,6 @@ public void throwsUnknownVersionCommandExceptionWhenParseCommandStringWithNullCo * Test parseCommandString with invalid command */ @Test -// (expected = UnknownVersionCommandException.class) public void throwsUnknownVersionCommandExceptionWhenParseCommandStringWithInvalidCommand() { assertThrows(UnknownVersionCommandException.class, () -> VersionCommand.parseCommandString("Command")); } @@ -78,7 +75,6 @@ public void testParseCommandStringWithValidCommand() { * Test parseJson with Null versionData */ @Test -// (expected = UnknownVersionCommandException.class) public void throwsUnknownVersionCommandExceptionWhenParseJsonWithNullVersionData() { assertThrows(UnknownVersionCommandException.class, () -> VersionCommand.parseJson(null)); } @@ -87,7 +83,6 @@ public void throwsUnknownVersionCommandExceptionWhenParseJsonWithNullVersionData * Test parseJson with invalid versionData */ @Test -// (expected = UnknownVersionCommandException.class) public void throwsUnknownVersionCommandExceptionWhenParseJsonWithInvalidVersionData() { jsonObject = jsonObjectBuilder .add("versionCommandDummy", "versionCommand").build(); 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 45838cd2..65a96e9a 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,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -68,9 +68,7 @@ public void setUp() throws Exception { contentType = "Application/json"; content = "response content"; defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus.OK); - fileReaderMockedConstruction = mockConstruction(FileReader.class, (mock, context) -> { - - }); + fileReaderMockedConstruction = mockConstruction(FileReader.class); bufferedReaderMockedConstruction = mockConstruction(BufferedReader.class, (mock, context) -> { when(mock.readLine()).thenReturn("token"); }); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/BluetoothApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/BluetoothApiHandlerTest.java index fdaaa300..bfa24318 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/BluetoothApiHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/BluetoothApiHandlerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/CommandLineApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/CommandLineApiHandlerTest.java index 60f05a4a..0aa589b0 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/CommandLineApiHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/CommandLineApiHandlerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -73,9 +73,6 @@ public class CommandLineApiHandlerTest { private MockedStatic jsonMockedStatic; private MockedStatic commandLineParserMockedStatic; - - //global timeout rule - @BeforeEach public void setUp() throws Exception { executor = Executors.newFixedThreadPool(1); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ConfigApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ConfigApiHandlerTest.java index 9971dc70..094e4b3d 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ConfigApiHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ConfigApiHandlerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -100,7 +100,6 @@ public void tearDown() throws Exception { apiHandlerHelpersMockedStatic.close(); jsonMockedStatic.close(); commandLineParserMockedStatic.close(); - } /** diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlSignalSentInfoTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlSignalSentInfoTest.java index cb88f0ff..3a190ef7 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlSignalSentInfoTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlSignalSentInfoTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlWebsocketHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlWebsocketHandlerTest.java index dae0e678..4f7ea126 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlWebsocketHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlWebsocketHandlerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -98,10 +98,6 @@ public void setUp() throws Exception { webSocketServerHandshakerFactoryMockedConstruction = mockConstruction(WebSocketServerHandshakerFactory.class, (mock, context) -> { Mockito.when(mock.newHandshaker(Mockito.eq(httpRequest))).thenReturn(handShaker); }); -// Mockito.whenNew(WebSocketServerHandshakerFactory.class) -// .withArguments(Mockito.anyString(), Mockito.eq(null), Mockito.anyBoolean(), Mockito.anyInt()) -// .thenReturn(webSocketServerHandshakerFactory); -// Mockito.doReturn(handShaker).when(webSocketServerHandshakerFactory).newHandshaker(Mockito.any(HttpRequest.class)); Mockito.doReturn(channelFuture).when(handShaker).handshake(Mockito.any(), Mockito.any()); Mockito.when(StatusReporter.setLocalApiStatus()).thenReturn(localApiStatus); Mockito.when(WebsocketUtil.hasContextInMap(Mockito.any(), Mockito.any())).thenReturn(true); @@ -153,7 +149,6 @@ public void testHandleWhenReqAndContextAreNotNullAndTokenIsLessThan5() { public void testHandleWhenReqAndContextAreNotNullAndTokenIsNotLessThan5() { try { controlWebsocketHandler.handle(channelHandlerContext, httpRequest); -// Mockito.verify(webSocketServerHandshakerFactoryMockedConstruction).newHandshaker(Mockito.eq(httpRequest)); Mockito.verify(handShaker).handshake(Mockito.eq(channel), Mockito.eq(httpRequest)); Mockito.verify(StatusReporter.class); StatusReporter.setLocalApiStatus(); @@ -273,7 +268,6 @@ public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfbinaryWebSocke try { Mockito.when(closeWebSocketFrame.content()).thenReturn(byteBuf); Mockito.when(channelHandlerContext.channel()).thenReturn(channel); -// Mockito.doNothing().when(WebsocketUtil.class); controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, closeWebSocketFrame); Mockito.verify(WebsocketUtil.class); WebsocketUtil.removeWebsocketContextFromMap(Mockito.eq(channelHandlerContext), Mockito.eq(WebSocketMap.controlWebsocketMap)); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlWebsocketWorkerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlWebsocketWorkerTest.java index 9510f589..24a6d5cf 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlWebsocketWorkerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlWebsocketWorkerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -41,9 +41,6 @@ public class ControlWebsocketWorkerTest { private ControlWebsocketWorker controlWebsocketWorker; private ChannelHandlerContext context; private ControlSignalSentInfo controlSignalSentInfo; - private ByteBufAllocator byteBufAllocator; - private ByteBuf byteBuf; - private Channel channel; private LocalApiStatus localApiStatus; private MockedStatic statusReporterMockedStatic; private MockedStatic loggingServiceMockedStatic; @@ -52,15 +49,15 @@ public class ControlWebsocketWorkerTest { public void setUp() throws Exception { MODULE_NAME = "Local API"; context = Mockito.mock(ChannelHandlerContext.class); - channel = Mockito.mock(Channel.class); - byteBufAllocator = Mockito.mock(ByteBufAllocator.class); + Channel channel = Mockito.mock(Channel.class); + ByteBufAllocator byteBufAllocator = Mockito.mock(ByteBufAllocator.class); controlSignalSentInfo = Mockito.mock(ControlSignalSentInfo.class); localApiStatus = Mockito.mock(LocalApiStatus.class); loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); statusReporterMockedStatic = Mockito.mockStatic(StatusReporter.class); websocketUtilMockedStatic = Mockito.mockStatic(WebsocketUtil.class); controlWebsocketWorker = Mockito.spy(new ControlWebsocketWorker()); - byteBuf = Mockito.mock(ByteBuf.class); + ByteBuf byteBuf = Mockito.mock(ByteBuf.class); Mockito.when(context.alloc()).thenReturn(byteBufAllocator); Mockito.when(byteBufAllocator.buffer()).thenReturn(byteBuf); Mockito.when(context.channel()).thenReturn(channel); @@ -81,7 +78,7 @@ public void tearDown() throws Exception { * Test run when WebSocketMap.unackControlSignalsMap is empty */ @Test - public void testRunWhenUnackControlSignalsMapIsEmpty() { + public void testRunWhenUnAckControlSignalsMapIsEmpty() { controlWebsocketWorker.run(); Mockito.verify(LoggingService.class); LoggingService.logDebug(MODULE_NAME,"Initiating control signals for unacknowledged signals"); @@ -94,7 +91,7 @@ public void testRunWhenUnackControlSignalsMapIsEmpty() { * controlSignalSentInfo.getSendTryCount() < 10 */ @Test - public void testRunWhenUnackControlSignalsMapIsNotEmpty() { + public void testRunWhenUnAckControlSignalsMapIsNotEmpty() { try { WebSocketMap.unackControlSignalsMap.put(context, controlSignalSentInfo); controlWebsocketWorker.run(); @@ -111,7 +108,7 @@ public void testRunWhenUnackControlSignalsMapIsNotEmpty() { * controlSignalSentInfo.getSendTryCount() > 10 */ @Test - public void testRunWhenUnackControlSignalsMapIsNotEmptyAndSendTryCountIsGreaterThan10() { + public void testRunWhenUnAckControlSignalsMapIsNotEmptyAndSendTryCountIsGreaterThan10() { try { WebSocketMap.unackControlSignalsMap.put(context, controlSignalSentInfo); Mockito.when(controlSignalSentInfo.getSendTryCount()).thenReturn(11); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/DeprovisionApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/DeprovisionApiHandlerTest.java index 7eb683e9..7ca4ce4a 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/DeprovisionApiHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/DeprovisionApiHandlerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GetConfigurationHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GetConfigurationHandlerTest.java index 18580eb9..e6ca3664 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GetConfigurationHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GetConfigurationHandlerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GpsApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GpsApiHandlerTest.java index f5c38861..249aa017 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GpsApiHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GpsApiHandlerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -168,7 +168,6 @@ public void testCallWhenRequestTypeIsPostAndSaveConfigurationThrowsException() { Exception exp = new Exception("Error"); Mockito.when(httpRequest.method()).thenReturn(HttpMethod.POST); configurationMockedStatic.when(Configuration::saveConfigUpdates).thenThrow(exp); - String errorMsg = " Error with setting GPS, " + exp.getMessage(); defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); assertEquals(defaultResponse, gpsApiHandler.call()); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/InfoApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/InfoApiHandlerTest.java index d021967d..005ee423 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/InfoApiHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/InfoApiHandlerTest.java @@ -79,7 +79,6 @@ public void setUp() throws Exception { objectMapperMockedConstruction = mockConstruction(ObjectMapper.class, (mock,context) -> { when(mock.writeValueAsString(any())).thenReturn(result); }); -// Mockito.whenNew(ObjectMapper.class).withNoArguments().thenReturn(objectMapper); Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenReturn(result); infoApiHandler = Mockito.spy(new InfoApiHandler(httpRequest, byteBuf, bytes)); @@ -180,7 +179,6 @@ public void testCallWhenMethodAndAccessTokenAreValidObjectMapperThrowsException( objectMapperMockedConstruction = mockConstruction(ObjectMapper.class, (mock,context) -> { when(mock.writeValueAsString(any())).thenThrow(JsonProcessingException.class); }); -// Mockito.doThrow(Mockito.mock(JsonProcessingException.class)).when(objectMapper).writeValueAsString(Mockito.any()); Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); assertEquals(defaultResponse, infoApiHandler.call()); verify(ApiHandlerHelpers.class); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerPipelineFactoryTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerPipelineFactoryTest.java index 97e13107..5d8b2790 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerPipelineFactoryTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerPipelineFactoryTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -12,15 +12,12 @@ */ package org.eclipse.iofog.local_api; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.ssl.SslContext; import io.netty.util.concurrent.DefaultEventExecutorGroup; -import io.netty.util.concurrent.EventExecutorGroup; import org.eclipse.iofog.utils.logging.LoggingService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -32,7 +29,6 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; - import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -61,11 +57,9 @@ public class LocalApiServerPipelineFactoryTest { @BeforeEach public void setUp() throws Exception { executor = Executors.newFixedThreadPool(1); -// serverHandler = Mockito.mock(LocalApiServerHandler.class); sslContext = Mockito.mock(SslContext.class); channel = Mockito.mock(SocketChannel.class); pipeline = Mockito.mock(ChannelPipeline.class); -// defaultEventExecutorGroup = Mockito.mock(DefaultEventExecutorGroup.class); loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); localApiServerPipelineFactory = Mockito.spy(new LocalApiServerPipelineFactory(sslContext)); Mockito.when(channel.pipeline()).thenReturn(pipeline); @@ -84,10 +78,6 @@ public void tearDown() throws Exception { loggingServiceMockedStatic.close(); localApiServerPipelineFactory = null; sslContext = null; -// httpObjectAggregator = null; -// serverHandler = null; -// httpServerCodec = null; -// defaultEventExecutorGroup = null; pipeline = null; channel = null; executor.shutdown(); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerTest.java index aaa6bfc1..c5eaeb3a 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiStatusTest.java index 9be6e8f6..0574cd40 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiStatusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiStatusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LogApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LogApiHandlerTest.java index 51e52a03..bc631bb4 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LogApiHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LogApiHandlerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/MessageCallbackTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/MessageCallbackTest.java index d43eb1a0..2f44a3e8 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/MessageCallbackTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/MessageCallbackTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -23,8 +23,6 @@ import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; -import static org.mockito.Mockito.when; - /** * @author nehanaithani * @@ -34,7 +32,6 @@ public class MessageCallbackTest { private MessageCallback messageCallback; private String name; - private MessageWebsocketHandler messageWebsocketHandler; private Message message; private MockedConstruction messageWebsocketHandlerMockedConstruction; @@ -42,12 +39,10 @@ public class MessageCallbackTest { public void setUp() throws Exception { name = "message"; message = Mockito.mock(Message.class); - messageWebsocketHandler = Mockito.mock(MessageWebsocketHandler.class); messageCallback = Mockito.spy(new MessageCallback(name)); messageWebsocketHandlerMockedConstruction = Mockito.mockConstruction(MessageWebsocketHandler.class, (mock, context) -> { Mockito.doNothing().when(mock).sendRealTimeMessage(Mockito.any(), Mockito.any()); }); -// Mockito.whenNew(MessageWebsocketHandler.class).withNoArguments().thenReturn(messageWebsocketHandler); } @AfterEach @@ -56,7 +51,6 @@ public void tearDown() throws Exception { name = null; messageCallback = null; message = null; - messageWebsocketHandler = null; } /** diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/IOMessageListenerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/IOMessageListenerTest.java index ca97c4bf..172cc2b3 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/IOMessageListenerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/IOMessageListenerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -41,7 +41,6 @@ public class IOMessageListenerTest { private IOMessageListener ioMessageListener; private MessageCallback messageCallback; private TextMessage textMessage; - private Message message; private String MODULE_NAME = "MessageListener"; private MockedStatic loggingServiceMockedStatic; private MockedConstruction messageMockedConstruction; @@ -51,7 +50,6 @@ public void setUp() throws Exception { MODULE_NAME = "MessageListener"; messageCallback = mock(MessageCallback.class); textMessage = mock(TextMessage.class); - message = mock(Message.class); loggingServiceMockedStatic = mockStatic(LoggingService.class); doNothing().when(textMessage).acknowledge(); Mockito.when(textMessage.getText()).thenReturn("{}"); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageArchiveTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageArchiveTest.java index e58fd9cb..7ba22aa8 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageArchiveTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageArchiveTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -49,13 +49,11 @@ @MockitoSettings(strictness = Strictness.LENIENT) @Disabled public class MessageArchiveTest { - private String MODULE_NAME; private MessageArchive messageArchive; private long timestamp; private String message; private File file; private RandomAccessFile randomAccessFile; - private Runtime runtime; private File[] files; private MockedStatic loggingServiceMockedStatic; private MockedStatic configurationMockedStatic; @@ -64,16 +62,13 @@ public class MessageArchiveTest { @BeforeEach public void setUp() throws Exception { - MODULE_NAME = "MessageArchive"; timestamp = currentTimeMillis(); message = "message"; configurationMockedStatic = mockStatic(Configuration.class); loggingServiceMockedStatic = mockStatic(LoggingService.class); -// mockStatic(Runtime.class); when(Configuration.getDiskDirectory()).thenReturn("dir/"); file = mock(File.class); randomAccessFile = mock(RandomAccessFile.class); - runtime = mock(Runtime.class); files = new File[1]; files[0] = spy(new File("message1234545.idx")); when(file.listFiles(any(FilenameFilter.class))).thenReturn(files); @@ -86,19 +81,11 @@ public void setUp() throws Exception { when(mock.read(any(byte[].class), anyInt(), anyInt())).thenReturn(1); when(mock.readLong()).thenReturn(1L); }); -// Mockito.whenNew(File.class).withParameterTypes(String.class).withArguments(any()).thenReturn(file); -// Mockito.whenNew(RandomAccessFile.class).withParameterTypes(File.class, String.class) -// .withArguments(any(), anyString()).thenReturn(randomAccessFile); -// when(Runtime.getRuntime()).thenReturn(runtime); -// when(runtime.maxMemory()).thenReturn(1048576460L * 32); -// when(runtime.totalMemory()).thenReturn(1L); -// when(runtime.freeMemory()).thenReturn(1L); messageArchive = spy(new MessageArchive("message.idx")); } @AfterEach public void tearDown() throws Exception { - MODULE_NAME = null; files = null; reset(messageArchive, randomAccessFile); deleteDirectory("dir/messages/archive"); @@ -138,7 +125,6 @@ public FileVisitResult postVisitDirectory(Path directory, IOException ioExceptio public void testSave() { try { messageArchive.save(message.getBytes(UTF_8),timestamp); -// Mockito.verify(messageArchive.invoke("openFiles", anyLong()); Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).seek(anyLong()); Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).length(); Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).getFilePointer(); @@ -155,7 +141,6 @@ public void testClose() { try { messageArchive.save(message.getBytes(UTF_8),timestamp); messageArchive.close(); -// Mockito.verifyPrivate(messageArchive).invoke("openFiles", anyLong()); Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).seek(anyLong()); Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).length(); Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).getFilePointer(); @@ -173,10 +158,6 @@ public void testMessageQueryWithMessages() { try{ when(files[0].isFile()).thenReturn(true); when(files[0].getName()).thenReturn("message1234545.idx"); - -// whenNew(File.class).withParameterTypes(String.class).withArguments(any()).thenReturn(file); -// whenNew(RandomAccessFile.class).withParameterTypes(File.class, String.class) -// .withArguments(any(), anyString()).thenReturn(randomAccessFile); messageArchive.messageQuery(1, 50); Mockito.verify(file, Mockito.atLeastOnce()).listFiles(any(FilenameFilter.class)); Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).getFilePointer(); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusServerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusServerTest.java index d2c7677a..008a4706 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusServerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusServerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusStatusTest.java index edd00aa1..76db8b2e 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusStatusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusStatusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusTest.java index 4041cca6..f4a92105 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -59,15 +59,11 @@ public class MessageBusTest { private MessageBus messageBus; private MicroserviceManager microserviceManager; private MessageBusServer messageBusServer; - private Thread speedThread; - private Route route; private String MODULE_NAME; private String receiverValue; private MessageReceiver messageReceiver; private MessageConsumer messageConsumer; private MessagePublisher messagePublisher; - private MessageBusStatus messageBusStatus; - private SupervisorStatus supervisorStatus; private Map publishedMessagesPerMicroservice; private Orchestrator orchestrator = null; Map mapRoutes; @@ -93,21 +89,14 @@ public void setUp() throws Exception { messageReceiver = mock(MessageReceiver.class); messageConsumer = mock(MessageConsumer.class); messagePublisher = mock(MessagePublisher.class); - messageBusStatus = mock(MessageBusStatus.class); - supervisorStatus = mock(SupervisorStatus.class); + MessageBusStatus messageBusStatus = mock(MessageBusStatus.class); + SupervisorStatus supervisorStatus = mock(SupervisorStatus.class); Mockito.when(MicroserviceManager.getInstance()).thenReturn(microserviceManager); messageBusServerMockedConstruction = Mockito.mockConstruction(MessageBusServer.class); messageReceiverMockedConstruction = Mockito.mockConstruction(MessageReceiver.class); messagePublisherMockedConstruction = Mockito.mockConstruction(MessagePublisher.class); orchestratorMockedConstruction = Mockito.mockConstruction(Orchestrator.class); -// Mockito.whenNew(MessageBusServer.class).withNoArguments().thenReturn(messageBusServer); -// Mockito.whenNew(MessageReceiver.class).withArguments(anyString(), any(MessageConsumer.class)) -// .thenReturn(messageReceiver); -// Mockito.whenNew(MessagePublisher.class).withArguments(anyString(), any(Route.class), any(MessageProducer.class)) -// .thenReturn(messagePublisher); -// whenNew(Orchestrator.class).withNoArguments().thenReturn(orchestrator); -// whenNew(MessagePublisher.class).withAnyArguments().thenReturn(messagePublisher); - route = new Route(); + Route route = new Route(); receivers = new ArrayList<>(); receiverValue = "1"; receivers.add(receiverValue); @@ -129,9 +118,6 @@ public void setUp() throws Exception { Mockito.when(StatusReporter.setMessageBusStatus()).thenReturn(messageBusStatus); Mockito.when(StatusReporter.setSupervisorStatus()).thenReturn(supervisorStatus); orchestrator = mock(Orchestrator.class); - -// MessagePublisher messagePublisher = mock(MessagePublisher.class); - } @AfterEach @@ -350,12 +336,7 @@ public void testGetRoutes() { * Helper method */ public void initiateMockStart() { - speedThread = mock(Thread.class); - Thread startThread = mock(Thread.class); try { -// Mockito.whenNew(Thread.class).withParameterTypes(Runnable.class).withArguments(Mockito.any(Runnable.class)).thenReturn(startThread); -// Mockito.whenNew(Thread.class).withParameterTypes(Runnable.class, String.class).withArguments(Mockito.any(Runnable.class), -// anyString()).thenReturn(speedThread); Mockito.doNothing().when(messageBus).start(); messageBus.start(); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusUtilTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusUtilTest.java index b18204e3..54c17f09 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusUtilTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusUtilTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageIdGeneratorTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageIdGeneratorTest.java index 6f573a16..234e3c7c 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageIdGeneratorTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageIdGeneratorTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessagePublisherTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessagePublisherTest.java index d1c22333..3c504c4b 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessagePublisherTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessagePublisherTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -51,9 +51,6 @@ public class MessagePublisherTest { private String name; private Route route; private Message message; - private TextMessage textMessage; - private byte[] bytes; - private List receivers; private List messageList; private MockedStatic loggingServiceMockedStatic; private MockedStatic messageBusServerMockedStatic; @@ -63,11 +60,11 @@ public class MessagePublisherTest { @BeforeEach public void setUp() throws Exception { name = "name"; - bytes = new byte[20]; + byte[] bytes = new byte[20]; route = mock(Route.class); message = mock(Message.class); - textMessage = mock(TextMessage.class); - receivers = new ArrayList<>(); + TextMessage textMessage = mock(TextMessage.class); + List receivers = new ArrayList<>(); receivers.add("receivers"); messageList = mock(ArrayList.class); loggingServiceMockedStatic = mockStatic(LoggingService.class); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageReceiverTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageReceiverTest.java index 14eb900a..6e02e734 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageReceiverTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageReceiverTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -58,7 +58,6 @@ public void setUp() throws Exception { messageConsumer = mock(MessageConsumer.class); ioMessageListener = mock(IOMessageListener.class); textMessage = mock(TextMessage.class); - Message message = mock(Message.class); ioMessageListenerMockedConstruction = Mockito.mockConstruction(IOMessageListener.class, (mock, context) -> { Mockito.when(messageConsumer.getMessageListener()).thenReturn(mock); }); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageTest.java index 7c5dee77..88cde448 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -70,7 +70,6 @@ public class MessageTest { private byte[] contextData; private byte[] contentData; private JsonObject jsonObject; - private JsonObjectBuilder jsonObjectBuilder; private MockedStatic loggingServiceMockedStatic; @@ -98,11 +97,7 @@ public void setUp() throws Exception { difficultyTarget = 2; infoType = "infoType"; infoFormat = "infoFormat"; - String content = "contentData"; - String context = "contextData"; -// contentData = Base64.getDecoder().decode(content.getBytes(UTF_8)); -// contextData = Base64.getDecoder().decode(context.getBytes(UTF_8)); - jsonObjectBuilder = Json.createObjectBuilder(); + JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); jsonObject = jsonObjectBuilder.add("id", id) .add("tag",tag ) .add("groupid", messageGroupId) @@ -120,8 +115,6 @@ public void setUp() throws Exception { .add("difficultytarget", difficultyTarget) .add("infotype", infoType) .add("infoformat", infoFormat) -// .add("contentdata", content) -// .add("contextdata", context) .build(); message = spy(new Message()); } @@ -237,8 +230,6 @@ public void testGetterAndSetterPriority() { */ @Test public void testGetterAndSetterTimestamp() { -// message = new Message(jsonObject); -// timestamp = currentTimeMillis(); message.setTimestamp(timestamp); assertEquals(timestamp, message.getTimestamp()); } @@ -393,7 +384,8 @@ public void testBytes() { @Test public void throwsExceptionWhenByteArrayOutputStreamIsCreatedInBytes() { try { - MockedConstruction byteArrayOutputStreamMockedConstruction = Mockito.mockConstructionWithAnswer(ByteArrayOutputStream.class, invocation -> { + MockedConstruction byteArrayOutputStreamMockedConstruction = + Mockito.mockConstructionWithAnswer(ByteArrayOutputStream.class, invocation -> { throw new IOException(); }); message = spy(new Message(jsonObject)); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ContainerManagerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ContainerManagerTest.java index 106ddfc7..091877e1 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ContainerManagerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ContainerManagerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ContainerTaskTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ContainerTaskTest.java index 42f300a5..0f7e1267 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ContainerTaskTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ContainerTaskTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -99,7 +99,7 @@ public void testHashCodeWhenObjectAreEqual() { @Test public void testHashCodeWhenObjectAreNotEqual() { ContainerTask anotherTask = new ContainerTask(ContainerTask.Tasks.REMOVE_WITH_CLEAN_UP, microserviceId); - assertFalse(containerTask.equals(anotherTask)); + assertNotEquals(containerTask, anotherTask); assertNotEquals(containerTask.hashCode(), anotherTask.hashCode()); } } \ No newline at end of file diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/DockerUtilTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/DockerUtilTest.java index 531d4407..f0325e90 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/DockerUtilTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/DockerUtilTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -63,13 +63,9 @@ public class DockerUtilTest { private DefaultDockerClientConfig.Builder dockerClientConfig; private DefaultDockerClientConfig defaultDockerClientConfig; private DockerClient dockerClient; - private DockerClientBuilder dockerClientBuilder; private ProcessManagerStatus processManagerStatus; - private EventsCmd eventsCmd; private ListNetworksCmd listNetworksCmd; private PullImageCmd pullImageCmd; - private PullImageResultCallback pullImageResultCallback; - private Network network; private InspectContainerResponse inspectContainerResponse; private InspectContainerResponse.ContainerState containerState; private InspectContainerCmd inspectContainerCmd; @@ -77,8 +73,6 @@ public class DockerUtilTest { private RemoveImageCmd removeImageCmd; private InspectImageCmd inspectImageCmd; private CreateContainerCmd createContainerCmd; - private CreateContainerResponse createContainerResponse; - private NetworkSettings networkSettings; private StatsCmd statsCmd; private HostConfig hostConfig; private CountDownLatch countDownLatch; @@ -86,14 +80,9 @@ public class DockerUtilTest { private StatsCallback statsCallback; private Container container; private Registry registry; - private PortMapping portMapping; - private VolumeMapping volumeMapping; - private LogConfig logConfig; private List networkList; private List portMappingList; private List volumeMappingList; - private Map dockerBridgeMap; - private String bridgeName; private Microservice microservice; private StartContainerCmd startContainerCmd; private StopContainerCmd stopContainerCmd; @@ -102,12 +91,12 @@ public class DockerUtilTest { private String containerID; private String imageID; private String ipAddress; - private String[] containerNames = {".iofog_containerName1",".iofog_containerName2"}; - private String microserviceUuid = "microserviceUuid"; + private final String[] containerNames = {".iofog_containerName1",".iofog_containerName2"}; + private final String microserviceUuid = "microserviceUuid"; private List containerList; - private String MODULE_NAME = "Docker Util"; - private String[] extraHost = {"extraHost1", "extraHost2"}; - private Method method = null; + private final String MODULE_NAME = "Docker Util"; + private final String[] extraHost = {"extraHost1", "extraHost2"}; + private final Method method = null; private MockedStatic defaultDockerClientConfigMockedStatic; private MockedStatic configurationMockedStatic; private MockedStatic dockerClientMockedStatic; @@ -124,9 +113,9 @@ public void setUp() throws Exception { dockerClientConfig = mock(DefaultDockerClientConfig.Builder.class); defaultDockerClientConfig = mock(DefaultDockerClientConfig.class); processManagerStatus = mock(ProcessManagerStatus.class); - dockerClientBuilder = mock(DockerClientBuilder.class); + DockerClientBuilder dockerClientBuilder = mock(DockerClientBuilder.class); dockerClient = mock(DockerClient.class); - eventsCmd = mock(EventsCmd.class); + EventsCmd eventsCmd = mock(EventsCmd.class); registry = mock(Registry.class); listNetworksCmd = mock(ListNetworksCmd.class); microservice = mock(Microservice.class); @@ -135,36 +124,35 @@ public void setUp() throws Exception { removeContainerCmd = mock(RemoveContainerCmd.class); removeImageCmd = mock(RemoveImageCmd.class); pullImageCmd = mock(PullImageCmd.class); - pullImageResultCallback = mock(PullImageResultCallback.class); - network = mock(Network.class); + PullImageResultCallback pullImageResultCallback = mock(PullImageResultCallback.class); + Network network = mock(Network.class); inspectImageCmd = mock(InspectImageCmd.class); hostConfig = mock(HostConfig.class); inspectContainerResponse = mock(InspectContainerResponse.class); - createContainerResponse = mock(CreateContainerResponse.class); + CreateContainerResponse createContainerResponse = mock(CreateContainerResponse.class); containerState = mock(InspectContainerResponse.ContainerState.class); inspectContainerCmd = mock(InspectContainerCmd.class); - networkSettings = mock(NetworkSettings.class); + NetworkSettings networkSettings = mock(NetworkSettings.class); listContainersCmd = mock(ListContainersCmd.class); createContainerCmd = mock(CreateContainerCmd.class); - logConfig = mock(LogConfig.class); container = mock(Container.class); statsCmd = mock(StatsCmd.class); countDownLatch = mock(CountDownLatch.class); statistics = mock(Statistics.class); statsCallback = mock(StatsCallback.class); microserviceStatus = mock(MicroserviceStatus.class); - portMapping = mock(PortMapping.class); - volumeMapping = mock(VolumeMapping.class); + PortMapping portMapping = mock(PortMapping.class); + VolumeMapping volumeMapping = mock(VolumeMapping.class); networkList = new ArrayList<>(); containerList = new ArrayList<>(); networkList.add(network); containerList.add(container); - dockerBridgeMap = mock(HashMap.class); + Map dockerBridgeMap = mock(HashMap.class); portMappingList = new ArrayList<>(); portMappingList.add(portMapping); volumeMappingList = new ArrayList<>(); volumeMappingList.add(volumeMapping); - bridgeName = "default_bridge"; + String bridgeName = "default_bridge"; containerID = "containerID"; imageID = "imageID"; ipAddress = "ipAddress"; @@ -248,13 +236,7 @@ public void setUp() throws Exception { Mockito.when(mock.getStats()).thenReturn(statistics); }); countDownLatchMockedConstruction = mockConstruction(CountDownLatch.class); -// Mockito.whenNew(MicroserviceStatus.class).withNoArguments().thenReturn(microserviceStatus); -// Mockito.whenNew(CountDownLatch.class).withArguments(anyInt()).thenReturn(countDownLatch); -// Mockito.whenNew(StatsCallback.class).withArguments(any(CountDownLatch.class)).thenReturn(statsCallback); -// Mockito.whenNew(PullImageResultCallback.class).withNoArguments().thenReturn(pullImageResultCallback); -// Mockito.whenNew(LogConfig.class).withArguments(any(LogConfig.LoggingType.class), any(Map.class)).thenReturn(logConfig); dockerUtil = spy(DockerUtil.getInstance()); - setMock(dockerUtil); } @AfterEach @@ -281,31 +263,6 @@ public void tearDown() throws Exception { method.setAccessible(false); } - /** - * Set a mock to the {@link DockerUtil} instance - * Throws {@link RuntimeException} in case if reflection failed, see a {@link Field#set(Object, Object)} method description. - * @param mock the mock to be inserted to a class - */ - private void setMock(DockerUtil mock) { - try { -// Field instance = DockerUtil.class.getDeclaredField("instance"); -// instance.setAccessible(true); -// instance.set(instance, mock); -// method = DockerUtil.class.getDeclaredMethod("initDockerClient"); -// method.setAccessible(true); -// method.invoke(dockerUtil); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - /** - * Asserts mock is same as the DockerUtil.getInstance() - */ - @Test - public void testGetInstanceIsSameAsMock() { -// assertSame(dockerUtil, DockerUtil.getInstance()); - } - /** * Test reInitDockerClient */ @@ -317,7 +274,6 @@ public void testReInitDockerClient() { Mockito.verify(dockerClient).close(); Mockito.verify(dockerClientConfig, Mockito.atLeastOnce()).withDockerHost(any()); Mockito.verify(dockerClientConfig, Mockito.atLeastOnce()).withApiVersion(anyString()); -// verifyPrivate(dockerUtil, Mockito.atLeastOnce()).invoke("addDockerEventHandler"); } catch (Exception e) { fail("This should not happen"); } @@ -559,7 +515,6 @@ public void testGetMicroserviceStatusWhenExecReturnsContainerStateIsStart() { assertEquals(containerID, dockerUtil.getMicroserviceStatus(containerID, microserviceUuid).getContainerId()); Mockito.verify(LoggingService.class, atLeastOnce()); LoggingService.logDebug(MODULE_NAME , "Get microservice status for microservice uuid : "+ microserviceUuid); -// Mockito.verifyPrivate(dockerUtil).invoke("containerToMicroserviceState", any()); } catch (Exception e) { fail("This should not happen"); } @@ -670,7 +625,6 @@ public void testGetRunningContainersWhenContainersAreNotRunning() { try { assertEquals(0, dockerUtil.getRunningContainers().size()); Mockito.verify(dockerUtil).getContainers(); -// Mockito.verifyPrivate(dockerUtil).invoke("containerToMicroserviceState", any()); } catch (Exception e) { fail("This should not happen"); } @@ -687,7 +641,6 @@ public void testGetRunningContainersWhenContainersAreRunning() { assertEquals(containerList, list); assertEquals(1, list.size()); Mockito.verify(dockerUtil).getContainers(); -// Mockito.verifyPrivate(dockerUtil).invoke("containerToMicroserviceState", any()); } catch (Exception e) { fail("This should not happen"); } @@ -703,7 +656,6 @@ public void testGetRunningIofogContainersWhenContainersAreNotRunning() { List list = dockerUtil.getRunningIofogContainers(); assertEquals(0, list.size()); Mockito.verify(dockerUtil).getContainers(); -// Mockito.verifyPrivate(dockerUtil).invoke("containerToMicroserviceState", any()); } catch (Exception e) { fail("This should not happen"); } @@ -721,7 +673,6 @@ public void testGetRunningIofogContainersWhenContainersAreRunning() { assertEquals(1, list.size()); assertEquals(containerList, list); Mockito.verify(dockerUtil).getContainers(); -// Mockito.verifyPrivate(dockerUtil).invoke("containerToMicroserviceState", any()); } catch (Exception e) { fail("This should not happen"); } @@ -798,8 +749,6 @@ public void testGetContainerStartedAtWhenReturnStartTime() { public void testAreMicroserviceAndContainerEqualWhenContainerAndMicorserivceAreNotEqual() { try { assertFalse(dockerUtil.areMicroserviceAndContainerEqual(containerID, microservice)); -// Mockito.verifyPrivate(dockerUtil).invoke("isPortMappingEqual", any(), any()); -// Mockito.verifyPrivate(dockerUtil).invoke("isNetworkModeEqual", any(), any()); } catch (Exception e) { fail("This should not happen"); } @@ -818,10 +767,6 @@ public void testAreMicroserviceAndContainerEqualWhenContainerAndMicorserivceAreE Mockito.when(hostConfig.getNetworkMode()).thenReturn("host"); Mockito.when(microservice.isRootHostAccess()).thenReturn(true); assertTrue(dockerUtil.areMicroserviceAndContainerEqual(containerID, microservice)); -// Mockito.verifyPrivate(dockerUtil).invoke("isPortMappingEqual", any(), any()); -// Mockito.verifyPrivate(dockerUtil).invoke("isNetworkModeEqual", any(), any()); -// Mockito.verifyPrivate(dockerUtil).invoke("getMicroservicePorts", any()); -// Mockito.verifyPrivate(dockerUtil).invoke("getContainerPorts", any()); } catch (Exception e) { fail("This should not happen"); } @@ -869,7 +814,6 @@ public void throwsExceptionWhenExecISCalledGetContainerStatus() { public void testIsContainerRunningWhenContainerStateIsStopped() { try { assertFalse(dockerUtil.isContainerRunning(containerID)); -// Mockito.verifyPrivate(dockerUtil).invoke("getContainerStatus", any()); Mockito.verify(dockerClient).inspectContainerCmd(any()); } catch (Exception e) { fail("This should not happen"); @@ -884,7 +828,6 @@ public void testIsContainerRunningWhenContainerStateIsRunning() { try { Mockito.when(containerState.getStatus()).thenReturn("RUNNING"); assertTrue(dockerUtil.isContainerRunning(containerID)); -// Mockito.verifyPrivate(dockerUtil).invoke("getContainerStatus", any()); Mockito.verify(dockerClient).inspectContainerCmd(any()); } catch (Exception e) { fail("This should not happen"); @@ -943,7 +886,6 @@ public void throwsNotFoundExceptionWhenRemoveImageById() { * throws AgentSystemException */ @Test -// (expected = AgentSystemException.class) public void testPullImageWhenRegistryIsNull() throws AgentSystemException { assertThrows(AgentSystemException.class, () -> dockerUtil.pullImage(imageID, containerID,null)); } diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ProcessManagerStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ProcessManagerStatusTest.java index 5434396a..7ef8463a 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ProcessManagerStatusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ProcessManagerStatusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -45,7 +45,6 @@ public class ProcessManagerStatusTest { private ProcessManagerStatus processManagerStatus; private JsonArrayBuilder arrayBuilder; private MicroserviceStatus microserviceStatus; - private MicroserviceManager microserviceManager; private MicroserviceState microserviceState; private String microserviceUuid; private MockedStatic microserviceManagerMockedStatic; @@ -54,16 +53,13 @@ public class ProcessManagerStatusTest { public void setUp() throws Exception { processManagerStatus = spy(new ProcessManagerStatus()); microserviceStatus = mock(MicroserviceStatus.class); - microserviceManager = mock(MicroserviceManager.class); - Registry registry = mock(Registry.class); + MicroserviceManager microserviceManager = mock(MicroserviceManager.class); microserviceState = mock(MicroserviceState.class); arrayBuilder = Json.createArrayBuilder(); - List registries = new ArrayList<>(); microserviceManagerMockedStatic = mockStatic(MicroserviceManager.class); microserviceUuid = "microserviceUuid"; Mockito.when(microserviceStatus.getStatus()).thenReturn(MicroserviceState.RUNNING); Mockito.when(MicroserviceManager.getInstance()).thenReturn(microserviceManager); -// Mockito.whenNew(MicroserviceStatus.class).withNoArguments().thenReturn(microserviceStatus); } @AfterEach diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ProcessManagerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ProcessManagerTest.java index 575768c3..0fe1bc7f 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ProcessManagerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/ProcessManagerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -56,18 +56,13 @@ @MockitoSettings(strictness = Strictness.LENIENT) public class ProcessManagerTest { private ProcessManager processManager; - private ProcessManagerStatus processManagerStatus; - private SupervisorStatus supervisorStatus; private MicroserviceManager microserviceManager; private Microservice microservice; private Container container; private DockerUtil dockerUtil; - private ContainerManager containerManager; private ContainerTask containerTask; private MicroserviceStatus microserviceStatus; - private StraceDiagnosticManager straceDiagnosticManager; private FieldAgentStatus fieldAgentStatus; - private Thread thread; private String MODULE_NAME; List microservicesList; List containerList; @@ -86,23 +81,21 @@ public class ProcessManagerTest { @BeforeEach public void setUp() throws Exception { MODULE_NAME = "Process Manager"; -// setMock(processManager); loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); statusReporterMockedStatic = Mockito.mockStatic(StatusReporter.class); dockerUtilMockedStatic = Mockito.mockStatic(DockerUtil.class); microserviceManagerMockedStatic = Mockito.mockStatic(MicroserviceManager.class); configurationrMockedStatic = Mockito.mockStatic(Configuration.class); straceDiagnosticManagerMockedStatic = Mockito.mockStatic(StraceDiagnosticManager.class); - processManagerStatus = mock(ProcessManagerStatus.class); + ProcessManagerStatus processManagerStatus = mock(ProcessManagerStatus.class); microserviceManager = mock(MicroserviceManager.class); microservice = mock(Microservice.class); - supervisorStatus = mock(SupervisorStatus.class); + SupervisorStatus supervisorStatus = mock(SupervisorStatus.class); container = mock(Container.class); dockerUtil = mock(DockerUtil.class); containerTask = mock(ContainerTask.class); - containerManager = mock(ContainerManager.class); microserviceStatus = mock(MicroserviceStatus.class); - straceDiagnosticManager = mock(StraceDiagnosticManager.class); + StraceDiagnosticManager straceDiagnosticManager = mock(StraceDiagnosticManager.class); fieldAgentStatus = mock(FieldAgentStatus.class); microservicesList = new ArrayList<>(); microservicesList.add(microservice); @@ -128,16 +121,10 @@ public void setUp() throws Exception { Mockito.doNothing().when(straceDiagnosticManager).disableMicroserviceStraceDiagnostics(anyString()); Mockito.when(microserviceManager.getLatestMicroservices()).thenReturn(microservicesList); Mockito.when(microserviceManager.getCurrentMicroservices()).thenReturn(microservicesList); - - -// Mockito.whenNew(ContainerManager.class).withNoArguments().thenReturn(containerManager); Mockito.when(Configuration.isWatchdogEnabled()).thenReturn(false); Mockito.when(Configuration.getIofogUuid()).thenReturn("Uuid"); -// Mockito.whenNew(ContainerTask.class).withArguments(Mockito.any(), Mockito.anyString()) -// .thenReturn(containerTask); processManager = Mockito.spy(ProcessManager.getInstance()); initiateMockStart(); - } @AfterEach @@ -151,7 +138,6 @@ public void tearDown() throws Exception { containerManagerMockedConstruction.close(); containerTaskMockedConstruction.close(); threadMockedConstruction.close(); -// reset(straceDiagnosticManager, thread, supervisorStatus, processManagerStatus); Field instance = ProcessManager.class.getDeclaredField("instance"); instance.setAccessible(true); instance.set(null, null); @@ -194,14 +180,6 @@ public void testGetModuleName() { assertEquals(MODULE_NAME, processManager.getModuleName()); } - /** - * Asserts mock is same as the ProcessManager.getInstance() - */ - @Test - public void testGetInstanceIsSameAsMock() { -// assertEquals(processManager, ProcessManager.getInstance()); - } - /** * Test update */ @@ -209,7 +187,6 @@ public void testGetInstanceIsSameAsMock() { public void testUpdate() { try { processManager.update(); -// Mockito.verifyPrivate(processManager).invoke("updateRegistriesStatus"); Mockito.verify(StatusReporter.class, Mockito.atLeastOnce()); StatusReporter.getProcessManagerStatus(); } catch (Exception e) { @@ -229,9 +206,6 @@ public void testDeleteRemainingMicroserviceswhenThereIsOnlyOneMicroserviceRunnin processManager.deleteRemainingMicroservices(); Mockito.verify(microserviceManager).getLatestMicroservices(); Mockito.verify(microserviceManager).getCurrentMicroservices(); -// Mockito.verifyPrivate(processManager).invoke("deleteOldAgentContainers", Mockito.any(Set.class)); -// Mockito.verifyPrivate(processManager).invoke("deleteUnknownContainers", Mockito.any(Set.class)); -// Mockito.verifyPrivate(processManager).invoke("disableMicroserviceFeaturesBeforeRemoval", Mockito.any()); } catch (Exception e) { fail("This should not happen"); } @@ -253,39 +227,14 @@ public void testDeleteRemainingMicroservicesWhenThereAreMultipleMicroservicesRun Mockito.when(dockerUtil.getContainerMicroserviceUuid(Mockito.any())).thenReturn("Containeruuid", "uuid", "anotherUuid"); Mockito.when(dockerUtil.getContainerName(Mockito.any())).thenReturn("containerName", "containerName1", "containerName2"); Mockito.when(dockerUtil.getIoFogContainerName(Mockito.any())).thenReturn("containerName", "containerName1", "containerName2"); -// initiateMockStart(); processManager.deleteRemainingMicroservices(); Mockito.verify(microserviceManager).getLatestMicroservices(); Mockito.verify(microserviceManager).getCurrentMicroservices(); -// Mockito.verifyPrivate(processManager).invoke("deleteOldAgentContainers", Mockito.any(Set.class)); -// Mockito.verifyPrivate(processManager).invoke("deleteUnknownContainers", Mockito.any(Set.class)); } catch (Exception e) { fail("This should not happen"); } } - /** - * Test deleteRemainingMicroservices - * getLatestMicroservices returns null; - */ - /*@Test - public void testDeleteRemainingMicroserviceswhenGetLatestMicroservicesReturnNull() { - try { - Mockito.when(microserviceManager.getLatestMicroservices()).thenReturn(null); - Mockito.when(dockerUtil.getContainerMicroserviceUuid(Mockito.any())).thenReturn( "Anotheruuid"); - Mockito.when(dockerUtil.getContainerName(Mockito.any())).thenReturn("containerName"); - Mockito.when(microservice.getMicroserviceUuid()).thenReturn("uuid", "anotherUUid"); - initiateMockStart(); - processManager.deleteRemainingMicroservices(); - Mockito.verify(microserviceManager).getLatestMicroservices(); - Mockito.verify(microserviceManager).getCurrentMicroservices(); - Mockito.verifyPrivate(processManager).invoke("deleteOldAgentContainers", Mockito.any(Set.class)); - Mockito.verifyPrivate(processManager).invoke("deleteUnknownContainers", Mockito.any(Set.class)); - } catch (Exception e) { - fail("This should not happen"); - } - }*/ - /** * Test instanceConfigUpdated */ @@ -293,7 +242,6 @@ public void testDeleteRemainingMicroserviceswhenGetLatestMicroservicesReturnNull public void testInstanceConfigUpdated() { try { Mockito.doNothing().when(dockerUtil).reInitDockerClient(); -// initiateMockStart(); processManager.instanceConfigUpdated(); verify(dockerUtil).reInitDockerClient(); } catch (Exception e) { @@ -314,7 +262,6 @@ public void testPrivateMethodHandleLatestMicroservicesWhenGetContainersReturnEmp Mockito.when(microservice.isDelete()).thenReturn(false); Mockito.when(microserviceManager.getLatestMicroservices()).thenReturn(microservicesList); Mockito.when(dockerUtil.getContainer(Mockito.any())).thenReturn(Optional.empty()); -// initiateMockStart(); method = ProcessManager.class.getDeclaredMethod("handleLatestMicroservices"); method.setAccessible(true); method.invoke(processManager); @@ -322,7 +269,6 @@ public void testPrivateMethodHandleLatestMicroservicesWhenGetContainersReturnEmp Mockito.verify(dockerUtil).getContainer(any()); Mockito.verify(microservice).isDelete(); Mockito.verify(microservice).isUpdating(); -// Mockito.verifyPrivate(processManager, never()).invoke("addMicroservice", Mockito.any()); } catch (Exception e) { fail("This should not happen"); } @@ -348,7 +294,6 @@ public void testPrivateMethodHandleLatestMicroservicesWhenGetContainersReturnCon Mockito.when(dockerUtil.getContainerIpAddress(Mockito.any())).thenReturn("containerIpAddress"); Mockito.when(dockerUtil.areMicroserviceAndContainerEqual(Mockito.any(), Mockito.any())).thenReturn(true); Mockito.when(microserviceStatus.getStatus()).thenReturn(MicroserviceState.RUNNING); -// initiateMockStart(); method = ProcessManager.class.getDeclaredMethod("handleLatestMicroservices"); method.setAccessible(true); method.invoke(processManager); @@ -356,7 +301,6 @@ public void testPrivateMethodHandleLatestMicroservicesWhenGetContainersReturnCon Mockito.verify(dockerUtil).getContainer(any()); Mockito.verify(microservice, Mockito.times(2)).isDelete(); Mockito.verify(microservice).isUpdating(); -// Mockito.verifyPrivate(processManager).invoke("updateMicroservice", Mockito.any(), Mockito.any()); } catch (Exception e) { fail("This should not happen"); } @@ -385,7 +329,6 @@ public void testPrivateMethodHandleLatestMicroservicesWhenGetContainersReturnCon Mockito.when(dockerUtil.getContainerIpAddress(Mockito.any())).thenReturn("containerIpAddress"); Mockito.when(dockerUtil.areMicroserviceAndContainerEqual(Mockito.any(), Mockito.any())).thenReturn(true); Mockito.when(microserviceStatus.getStatus()).thenReturn(MicroserviceState.RUNNING); -// initiateMockStart(); method = ProcessManager.class.getDeclaredMethod("handleLatestMicroservices"); method.setAccessible(true); method.invoke(processManager); @@ -393,9 +336,6 @@ public void testPrivateMethodHandleLatestMicroservicesWhenGetContainersReturnCon Mockito.verify(dockerUtil).getContainer(any()); Mockito.verify(microservice, Mockito.times(1)).isDelete(); Mockito.verify(microservice).isUpdating(); -// Mockito.verifyPrivate(processManager).invoke("deleteMicroservice", Mockito.any()); -// Mockito.verifyPrivate(processManager).invoke("disableMicroserviceFeaturesBeforeRemoval", Mockito.any()); -// Mockito.verifyPrivate(processManager).invoke("addTask", Mockito.any()); } catch (Exception e) { fail("This should not happen"); } @@ -423,7 +363,6 @@ public void testPrivateMethodHandleLatestMicroservicesWhenIsDeleteWithCleanupIsF Mockito.when(dockerUtil.getContainerIpAddress(Mockito.any())).thenReturn("containerIpAddress"); Mockito.when(dockerUtil.areMicroserviceAndContainerEqual(Mockito.any(), Mockito.any())).thenReturn(true); Mockito.when(microserviceStatus.getStatus()).thenReturn(MicroserviceState.RUNNING); -// initiateMockStart(); method = ProcessManager.class.getDeclaredMethod("handleLatestMicroservices"); method.setAccessible(true); method.invoke(processManager); @@ -431,9 +370,6 @@ public void testPrivateMethodHandleLatestMicroservicesWhenIsDeleteWithCleanupIsF Mockito.verify(dockerUtil).getContainer(any()); Mockito.verify(microservice, Mockito.times(1)).isDelete(); Mockito.verify(microservice).isUpdating(); -// Mockito.verifyPrivate(processManager).invoke("deleteMicroservice", Mockito.any()); -// Mockito.verifyPrivate(processManager).invoke("disableMicroserviceFeaturesBeforeRemoval", Mockito.any()); -// Mockito.verifyPrivate(processManager).invoke("addTask", Mockito.any()); } catch (Exception e) { fail("This should not happen"); } @@ -463,14 +399,12 @@ public void throwsAgentSystemExceptionWhenGetContainerIpAddressIsCalledInHandleL Mockito.doThrow(mock(AgentSystemException.class)).when(dockerUtil).getContainerIpAddress(Mockito.any()); Mockito.when(dockerUtil.areMicroserviceAndContainerEqual(Mockito.any(), Mockito.any())).thenReturn(true); Mockito.when(microserviceStatus.getStatus()).thenReturn(MicroserviceState.RUNNING); -// initiateMockStart(); method = ProcessManager.class.getDeclaredMethod("handleLatestMicroservices"); method.setAccessible(true); method.invoke(processManager); Mockito.verify(microserviceManager).getLatestMicroservices(); Mockito.verify(dockerUtil).getContainer(any()); Mockito.verify(microservice, Mockito.times(2)).isDelete(); -// Mockito.verifyPrivate(processManager).invoke("updateMicroservice", Mockito.any(), Mockito.any()); verify(microservice).setContainerIpAddress(any()); } catch (Exception e) { @@ -530,7 +464,6 @@ public void testPrivateMethodRetryTask() { method.setAccessible(true); method.invoke(processManager, containerTask); Mockito.verify(containerTask).incrementRetries(); -// Mockito.verifyPrivate(processManager).invoke("addTask", Mockito.any()); } catch (Exception e) { System.out.println(e); fail("This should not happen"); @@ -552,7 +485,6 @@ public void testPrivateMethodRetryTaskMoreThanFive() { method.setAccessible(true); method.invoke(processManager, containerTask); Mockito.verify(containerTask, never()).incrementRetries(); -// Mockito.verifyPrivate(processManager, never()).invoke("addTask", Mockito.any()); Mockito.verify(StatusReporter.class); StatusReporter.setProcessManagerStatus(); } catch (Exception e) { @@ -579,14 +511,11 @@ public void testStart() { * Helper method */ public void initiateMockStart() { - thread = mock(Thread.class); + Thread thread = mock(Thread.class); try { threadMockedConstruction = mockConstruction(Thread.class, (mock, context) -> { Mockito.doNothing().when(mock).start(); }); -// Mockito.whenNew(Thread.class).withParameterTypes(Runnable.class,String.class) -// .withArguments(Mockito.any(Runnable.class), Mockito.anyString()) -// .thenReturn(thread); Mockito.doNothing().when(thread).start(); processManager.start(); } catch (Exception e) { diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/RestartStuckCheckerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/RestartStuckCheckerTest.java index e189776b..95dd0bd6 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/RestartStuckCheckerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/RestartStuckCheckerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/StatsCallbackTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/StatsCallbackTest.java index 69e64207..c98b8192 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/StatsCallbackTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/process_manager/StatsCallbackTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/pruning/DockerPruningManagerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/pruning/DockerPruningManagerTest.java index 5f5868e3..834ad70d 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/pruning/DockerPruningManagerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/pruning/DockerPruningManagerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -92,8 +92,6 @@ public void setUp() throws Exception { ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class); pruningManager = Mockito.spy(DockerPruningManager.getInstance()); container = Mockito.mock(Container.class); - - } @AfterEach diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_consumption_manager/ResourceConsumptionManagerStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_consumption_manager/ResourceConsumptionManagerStatusTest.java index 0574a1be..9dde9a6c 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_consumption_manager/ResourceConsumptionManagerStatusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_consumption_manager/ResourceConsumptionManagerStatusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_consumption_manager/ResourceConsumptionManagerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_consumption_manager/ResourceConsumptionManagerTest.java index 51a6600f..9695a5e4 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_consumption_manager/ResourceConsumptionManagerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_consumption_manager/ResourceConsumptionManagerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -73,7 +73,6 @@ public void setUp() throws Exception { Mockito.when(Configuration.getDiskLimit()).thenReturn(1.0f); Mockito.when(Configuration.getDiskDirectory()).thenReturn(""); Thread thread = Mockito.mock(Thread.class); -// whenNew(Thread.class).withParameterTypes(Runnable.class,String.class).withArguments(Mockito.any(Runnable.class), Mockito.anyString()).thenReturn(thread); Mockito.doNothing().when(thread).start(); } @AfterEach diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_manager/ResourceManagerStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_manager/ResourceManagerStatusTest.java index 7e94184c..37d46ab8 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_manager/ResourceManagerStatusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_manager/ResourceManagerStatusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -30,10 +30,8 @@ @MockitoSettings(strictness = Strictness.LENIENT) public class ResourceManagerStatusTest { private ResourceManagerStatus resourceManagerStatus; - private String hwInfo = "Info"; - private String usbConnectionsInfo = "USB_INFO"; - @BeforeEach + @BeforeEach public void setUp() throws Exception { resourceManagerStatus = spy(new ResourceManagerStatus()); } @@ -44,8 +42,10 @@ public void tearDown() throws Exception { @Test public void testGetterAndSetter() { - resourceManagerStatus.setHwInfo(hwInfo); - resourceManagerStatus.setUsbConnectionsInfo(usbConnectionsInfo); + String hwInfo = "Info"; + resourceManagerStatus.setHwInfo(hwInfo); + String usbConnectionsInfo = "USB_INFO"; + resourceManagerStatus.setUsbConnectionsInfo(usbConnectionsInfo); assertEquals(hwInfo, resourceManagerStatus.getHwInfo()); assertEquals(usbConnectionsInfo, resourceManagerStatus.getUsbConnectionsInfo()); } diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_manager/ResourceManagerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_manager/ResourceManagerTest.java index dda95eec..8aafefe3 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_manager/ResourceManagerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/resource_manager/ResourceManagerTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 @@ -38,7 +38,6 @@ public class ResourceManagerTest { private MockedStatic loggingServiceMockedStatic; /** - * @throws Exception */ @BeforeEach public void setUp() throws Exception { @@ -52,7 +51,6 @@ public void setUp() throws Exception { } /** - * @throws Exception */ @AfterEach public void tearDown() throws Exception { diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/status_reporter/StatusReporterStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/status_reporter/StatusReporterStatusTest.java index 7968455d..3d7dd5fc 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/status_reporter/StatusReporterStatusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/status_reporter/StatusReporterStatusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/status_reporter/StatusReporterTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/status_reporter/StatusReporterTest.java index 5a9c5c8f..be42e97a 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/status_reporter/StatusReporterTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/status_reporter/StatusReporterTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/supervisor/SupervisorStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/supervisor/SupervisorStatusTest.java index c2d646cf..234a19d0 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/supervisor/SupervisorStatusTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/supervisor/SupervisorStatusTest.java @@ -1,6 +1,6 @@ /* * ******************************************************************************* - * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/supervisor/SupervisorTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/supervisor/SupervisorTest.java index e08c36ac..532673ee 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/supervisor/SupervisorTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/supervisor/SupervisorTest.java @@ -121,8 +121,6 @@ public void initialization() { Mockito.when(StatusReporter.setLocalApiStatus()).thenReturn(mock(LocalApiStatus.class)); supervisor = spy(new Supervisor()); Mockito.doNothing().when(supervisor).operationDuration(); -// Mockito.doNothing().when(supervisor).start(); -// Mockito.doNothing().when(StatusReporter.class); } catch (Exception e) { e.printStackTrace(); } @@ -169,7 +167,6 @@ public void testStartModule() throws Exception{ ResourceManager resourceManager = mock(ResourceManager.class); Mockito.when(resourceManager.getModuleIndex()).thenReturn(6); Mockito.when(resourceManager.getModuleName()).thenReturn("ResourceManager"); -// Mockito.when(StatusReporter.setSupervisorStatus().setModuleStatus(6, RUNNING)).thenReturn(null); Method method = Supervisor.class.getDeclaredMethod("startModule", IOFogModule.class); method.setAccessible(true); Mockito.doNothing().when(resourceManager).start(); diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/CmdPropertiesTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/CmdPropertiesTest.java index 03105824..3969d32c 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/CmdPropertiesTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/CmdPropertiesTest.java @@ -1,227 +1,231 @@ -///* -// * ******************************************************************************* -// * * 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.utils; -// -//import org.eclipse.iofog.command_line.CommandLineConfigParam; -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static org.junit.Assert.*; -//import static org.powermock.api.mockito.Mockito.mockStatic; -// -///** -// * @author nehanaithani -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({CmdProperties.class}) -//public class CmdPropertiesTest { -// -// @Before -// public void setUp() throws Exception { -// mockStatic(CmdProperties.class, Mockito.CALLS_REAL_METHODS); -// } -// -// @After -// public void tearDown() throws Exception { -// } -// -// @Test -// public void getVersionMessage() { -// assertEquals("ioFog %s \nCopyright (C) 2022 Edgeworx, Inc. \nEclipse ioFog is provided under the Eclipse Public License 2.0 (EPL-2.0) \nhttps://www.eclipse.org/legal/epl-v20.html", -// CmdProperties.getVersionMessage()); -// } -// -// @Test -// public void getVersion() { -// assertNotNull(CmdProperties.getVersion()); -// } -// -// /** -// * Test getDeprovisionMessage -// */ -// @Test -// public void testGetDeprovisionMessage() { -// assertEquals("Deprovisioning from controller ... %s", CmdProperties.getDeprovisionMessage()); -// } -// -// /** -// * Test getProvisionMessage -// */ -// @Test -// public void testGetProvisionMessage() { -// assertEquals("Provisioning with key \"%s\" ... Result: %s", CmdProperties.getProvisionMessage()); -// } -// -// /** -// * Test getProvisionCommonErrorMessage -// */ -// @Test -// public void testGetProvisionCommonErrorMessage() { -// assertEquals("\nProvisioning failed", CmdProperties.getProvisionCommonErrorMessage()); -// } -// -// /** -// * Test getProvisionStatusErrorMessage -// */ -// @Test -// public void testGetProvisionStatusErrorMessage() { -// assertEquals("\nProvision failed with error message: \"%s\"", CmdProperties.getProvisionStatusErrorMessage()); -// -// } -// -// /** -// * Test getProvisionStatusSuccessMessage -// */ -// @Test -// public void testGetProvisionStatusSuccessMessage() { -// assertEquals("\nProvision success - Iofog UUID is %s", CmdProperties.getProvisionStatusSuccessMessage()); -// -// } -// -// /** -// * Test getConfigParamMessage NETWORK_INTERFACE -// */ -// @Test -// public void testGetConfigParamMessageOfNetworkInterface() { -// assertEquals("Network Interface", CmdProperties.getConfigParamMessage(CommandLineConfigParam.NETWORK_INTERFACE)); -// -// } -// /** -// * Test getConfigParamMessage DOCKER_URL -// */ -// @Test -// public void testGetConfigParamMessageOfDockerUrl() { -// assertEquals("Docker URL", CmdProperties.getConfigParamMessage(CommandLineConfigParam.DOCKER_URL)); -// -// } -// /** -// * Test getConfigParamMessage LOG_DISK_CONSUMPTION_LIMIT -// */ -// @Test -// public void testGetConfigParamMessageOfLogDiskLimit() { -// assertEquals("Log Disk Limit", CmdProperties.getConfigParamMessage(CommandLineConfigParam.LOG_DISK_CONSUMPTION_LIMIT)); -// -// } -// /** -// * Test getConfigParamMessage LOG_DISK_DIRECTORY -// */ -// @Test -// public void testGetConfigParamMessageOfLogDiskDirectory() { -// assertEquals("Log File Directory", CmdProperties.getConfigParamMessage(CommandLineConfigParam.LOG_DISK_DIRECTORY)); -// } -// -// /** -// * Test getConfigParamMessage LOG_FILE_COUNT -// */ -// @Test -// public void testGetConfigParamMessageOfLogDFileCount() { -// assertEquals("Log Rolling File Count", CmdProperties.getConfigParamMessage(CommandLineConfigParam.LOG_FILE_COUNT)); -// } -// /** -// * Test getConfigParamMessage LOG_LEVEL -// */ -// @Test -// public void testGetConfigParamMessageOfLogLevel() { -// assertEquals("Log Level", CmdProperties.getConfigParamMessage(CommandLineConfigParam.LOG_LEVEL)); -// } -// -// /** -// * Test getConfigParamMessage POST_DIAGNOSTICS_FREQ -// */ -// @Test -// public void testGetConfigParamMessageOfPostDiagnosticFreq() { -// assertEquals("Post Diagnostics Frequency", CmdProperties.getConfigParamMessage(CommandLineConfigParam.POST_DIAGNOSTICS_FREQ)); -// } -// -// /** -// * Test getConfigParamMessage IOFOG_UUID -// */ -// @Test -// public void testGetConfigParamMessageOfIofogUuid() { -// assertEquals("Iofog UUID", CmdProperties.getConfigParamMessage(CommandLineConfigParam.IOFOG_UUID)); -// } -// -// /** -// * Test getConfigParamMessage GPS_COORDINATES -// */ -// @Test -// public void testGetConfigParamMessageOfGPSCoordinates() { -// assertEquals("GPS coordinates(lat,lon)", CmdProperties.getConfigParamMessage(CommandLineConfigParam.GPS_COORDINATES)); -// } -// -// /** -// * Test getConfigParamMessage GPS_MODE -// */ -// @Test -// public void testGetConfigParamMessageOfGPSMode() { -// assertEquals("GPS mode", CmdProperties.getConfigParamMessage(CommandLineConfigParam.GPS_MODE)); -// } -// -// /** -// * Test getConfigParamMessage FOG_TYPE -// */ -// @Test -// public void testGetConfigParamMessageOfFogType() { -// assertEquals("Fog type", CmdProperties.getConfigParamMessage(CommandLineConfigParam.FOG_TYPE)); -// } -// /** -// * Test getConfigParamMessage DEV_MODE -// */ -// @Test -// public void testGetConfigParamMessageOfDevMode() { -// assertEquals("Developer's Mode", CmdProperties.getConfigParamMessage(CommandLineConfigParam.DEV_MODE)); -// } -// -// /** -// * Test getConfigParamMessage DEVICE_SCAN_FREQUENCY -// */ -// @Test -// public void testGetConfigParamMessageOfDeviceScanFreq() { -// assertEquals("Scan Devices Frequency", CmdProperties.getConfigParamMessage(CommandLineConfigParam.DEVICE_SCAN_FREQUENCY)); -// } -// -// /** -// * Test getConfigParamMessage CHANGE_FREQUENCY -// */ -// @Test -// public void testGetConfigParamMessageOfChangeFreq() { -// assertEquals("Get Changes Frequency", CmdProperties.getConfigParamMessage(CommandLineConfigParam.CHANGE_FREQUENCY)); -// } -// /** -// * Test getConfigParamMessage STATUS_FREQUENCY -// */ -// @Test -// public void testGetConfigParamMessageOfStatusFreq() { -// assertEquals("Status Update Frequency", CmdProperties.getConfigParamMessage(CommandLineConfigParam.STATUS_FREQUENCY)); -// } -// -// /** -// * Test ipAddressMessage -// */ -// @Test -// public void testGetIpAddressMessage() { -// assertEquals("IP Address", CmdProperties.getIpAddressMessage()); -// } -// /** -// * Test getIofogUuidMessage -// */ -// @Test -// public void testGetIofogUuidMessage() { -// assertEquals("Iofog UUID", CmdProperties.getIofogUuidMessage()); -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2024 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.utils; + +import org.eclipse.iofog.command_line.CommandLineConfigParam; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +/** + * @author nehanaithani + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class CmdPropertiesTest { + private MockedStatic cmdPropertiesMockedStatic; + + @BeforeEach + public void setUp() throws Exception { + cmdPropertiesMockedStatic = Mockito.mockStatic(CmdProperties.class, Mockito.CALLS_REAL_METHODS); + } + + @AfterEach + public void tearDown() throws Exception { + cmdPropertiesMockedStatic.close(); + } + + @Test + public void getVersionMessage() { + assertEquals("ioFog %s \nCopyright (C) 2018-2024 Edgeworx, Inc. \nEclipse ioFog is provided under the Eclipse Public License 2.0 (EPL-2.0) \nhttps://www.eclipse.org/legal/epl-v20.html", + CmdProperties.getVersionMessage()); + } + + @Test + public void getVersion() { + assertNotNull(CmdProperties.getVersion()); + } + + /** + * Test getDeprovisionMessage + */ + @Test + public void testGetDeprovisionMessage() { + assertEquals("Deprovisioning from controller ... %s", CmdProperties.getDeprovisionMessage()); + } + + /** + * Test getProvisionMessage + */ + @Test + public void testGetProvisionMessage() { + assertEquals("Provisioning with key \"%s\" ... Result: %s", CmdProperties.getProvisionMessage()); + } + + /** + * Test getProvisionCommonErrorMessage + */ + @Test + public void testGetProvisionCommonErrorMessage() { + assertEquals("\nProvisioning failed", CmdProperties.getProvisionCommonErrorMessage()); + } + + /** + * Test getProvisionStatusErrorMessage + */ + @Test + public void testGetProvisionStatusErrorMessage() { + assertEquals("\nProvision failed with error message: \"%s\"", CmdProperties.getProvisionStatusErrorMessage()); + + } + + /** + * Test getProvisionStatusSuccessMessage + */ + @Test + public void testGetProvisionStatusSuccessMessage() { + assertEquals("\nProvision success - Iofog UUID is %s", CmdProperties.getProvisionStatusSuccessMessage()); + + } + + /** + * Test getConfigParamMessage NETWORK_INTERFACE + */ + @Test + public void testGetConfigParamMessageOfNetworkInterface() { + assertEquals("Network Interface", CmdProperties.getConfigParamMessage(CommandLineConfigParam.NETWORK_INTERFACE)); + + } + /** + * Test getConfigParamMessage DOCKER_URL + */ + @Test + public void testGetConfigParamMessageOfDockerUrl() { + assertEquals("Docker URL", CmdProperties.getConfigParamMessage(CommandLineConfigParam.DOCKER_URL)); + + } + /** + * Test getConfigParamMessage LOG_DISK_CONSUMPTION_LIMIT + */ + @Test + public void testGetConfigParamMessageOfLogDiskLimit() { + assertEquals("Log Disk Limit", CmdProperties.getConfigParamMessage(CommandLineConfigParam.LOG_DISK_CONSUMPTION_LIMIT)); + + } + /** + * Test getConfigParamMessage LOG_DISK_DIRECTORY + */ + @Test + public void testGetConfigParamMessageOfLogDiskDirectory() { + assertEquals("Log File Directory", CmdProperties.getConfigParamMessage(CommandLineConfigParam.LOG_DISK_DIRECTORY)); + } + + /** + * Test getConfigParamMessage LOG_FILE_COUNT + */ + @Test + public void testGetConfigParamMessageOfLogDFileCount() { + assertEquals("Log Rolling File Count", CmdProperties.getConfigParamMessage(CommandLineConfigParam.LOG_FILE_COUNT)); + } + /** + * Test getConfigParamMessage LOG_LEVEL + */ + @Test + public void testGetConfigParamMessageOfLogLevel() { + assertEquals("Log Level", CmdProperties.getConfigParamMessage(CommandLineConfigParam.LOG_LEVEL)); + } + + /** + * Test getConfigParamMessage POST_DIAGNOSTICS_FREQ + */ + @Test + public void testGetConfigParamMessageOfPostDiagnosticFreq() { + assertEquals("Post Diagnostics Frequency", CmdProperties.getConfigParamMessage(CommandLineConfigParam.POST_DIAGNOSTICS_FREQ)); + } + + /** + * Test getConfigParamMessage IOFOG_UUID + */ + @Test + public void testGetConfigParamMessageOfIofogUuid() { + assertEquals("Iofog UUID", CmdProperties.getConfigParamMessage(CommandLineConfigParam.IOFOG_UUID)); + } + + /** + * Test getConfigParamMessage GPS_COORDINATES + */ + @Test + public void testGetConfigParamMessageOfGPSCoordinates() { + assertEquals("GPS coordinates(lat,lon)", CmdProperties.getConfigParamMessage(CommandLineConfigParam.GPS_COORDINATES)); + } + + /** + * Test getConfigParamMessage GPS_MODE + */ + @Test + public void testGetConfigParamMessageOfGPSMode() { + assertEquals("GPS mode", CmdProperties.getConfigParamMessage(CommandLineConfigParam.GPS_MODE)); + } + + /** + * Test getConfigParamMessage FOG_TYPE + */ + @Test + public void testGetConfigParamMessageOfFogType() { + assertEquals("Fog type", CmdProperties.getConfigParamMessage(CommandLineConfigParam.FOG_TYPE)); + } + /** + * Test getConfigParamMessage DEV_MODE + */ + @Test + public void testGetConfigParamMessageOfDevMode() { + assertEquals("Developer's Mode", CmdProperties.getConfigParamMessage(CommandLineConfigParam.DEV_MODE)); + } + + /** + * Test getConfigParamMessage DEVICE_SCAN_FREQUENCY + */ + @Test + public void testGetConfigParamMessageOfDeviceScanFreq() { + assertEquals("Scan Devices Frequency", CmdProperties.getConfigParamMessage(CommandLineConfigParam.DEVICE_SCAN_FREQUENCY)); + } + + /** + * Test getConfigParamMessage CHANGE_FREQUENCY + */ + @Test + public void testGetConfigParamMessageOfChangeFreq() { + assertEquals("Get Changes Frequency", CmdProperties.getConfigParamMessage(CommandLineConfigParam.CHANGE_FREQUENCY)); + } + /** + * Test getConfigParamMessage STATUS_FREQUENCY + */ + @Test + public void testGetConfigParamMessageOfStatusFreq() { + assertEquals("Status Update Frequency", CmdProperties.getConfigParamMessage(CommandLineConfigParam.STATUS_FREQUENCY)); + } + + /** + * Test ipAddressMessage + */ + @Test + public void testGetIpAddressMessage() { + assertEquals("IP Address", CmdProperties.getIpAddressMessage()); + } + /** + * Test getIofogUuidMessage + */ + @Test + public void testGetIofogUuidMessage() { + assertEquals("Iofog UUID", CmdProperties.getIofogUuidMessage()); + } +} \ No newline at end of file diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/OrchestratorTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/OrchestratorTest.java index a581f3cc..fe4c3310 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/OrchestratorTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/OrchestratorTest.java @@ -1,186 +1,204 @@ -///* -// * ******************************************************************************* -// * * 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.utils; -// -//import org.apache.http.HttpEntity; -//import org.apache.http.StatusLine; -//import org.apache.http.client.ClientProtocolException; -//import org.apache.http.client.methods.CloseableHttpResponse; -//import org.apache.http.client.methods.HttpGet; -//import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -//import org.apache.http.entity.ContentType; -//import org.apache.http.entity.StringEntity; -//import org.apache.http.entity.mime.MultipartEntityBuilder; -//import org.apache.http.impl.client.CloseableHttpClient; -//import org.apache.http.impl.client.HttpClientBuilder; -//import org.apache.http.impl.client.HttpClients; -//import org.eclipse.iofog.exception.AgentSystemException; -//import org.eclipse.iofog.exception.AgentUserException; -//import org.eclipse.iofog.field_agent.FieldAgent; -//import org.eclipse.iofog.field_agent.enums.RequestType; -//import org.eclipse.iofog.network.IOFogNetworkInterfaceManager; -//import org.eclipse.iofog.utils.configuration.Configuration; -//import org.eclipse.iofog.utils.device_info.ArchitectureType; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.eclipse.iofog.utils.trustmanager.TrustManagers; -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PowerMockIgnore; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import javax.json.Json; -//import javax.json.JsonObject; -//import javax.json.JsonObjectBuilder; -//import javax.json.JsonReader; -//import javax.naming.AuthenticationException; -//import javax.net.ssl.KeyManager; -//import javax.net.ssl.SSLContext; -//import javax.net.ssl.TrustManager; -// -//import java.io.*; -//import java.net.InetAddress; -//import java.security.KeyManagementException; -//import java.security.NoSuchAlgorithmException; -//import java.security.Provider; -//import java.security.SecureRandom; -//import java.security.cert.Certificate; -//import java.security.cert.CertificateException; -//import java.security.cert.CertificateFactory; -//import java.security.cert.CertificateFactorySpi; -//import java.util.HashMap; -//import java.util.Map; -// -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.anyString; -//import static org.mockito.Mockito.mock; -//import static org.powermock.api.mockito.Mockito.mockStatic; -//import static org.powermock.api.mockito.Mockito.spy; -// -//import javax.net.ssl.TrustManagerFactory; -//import javax.ws.rs.BadRequestException; -//import javax.ws.rs.ForbiddenException; -//import javax.ws.rs.InternalServerErrorException; -//import javax.ws.rs.NotFoundException; -// -///** -// * @author nehanaithani -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({Orchestrator.class, Configuration.class, SSLConnectionSocketFactory.class, LoggingService.class, -// HttpClients.class, CloseableHttpClient.class, LoggingService.class, IOFogNetworkInterfaceManager.class, -// InetAddress.class, HttpGet.class, BufferedReader.class, InputStreamReader.class, CloseableHttpResponse.class, -// HttpEntity.class, InputStream.class, StatusLine.class, JsonReader.class, Json.class, File.class, -// FileInputStream.class, CertificateFactory.class, Certificate.class, CertificateFactorySpi.class, Provider.class, -// SSLContext.class, SSLConnectionSocketFactory.class, HttpClientBuilder.class, StringEntity.class, FieldAgent.class, MultipartEntityBuilder.class, -// TrustManagers.class, TrustManagerFactory.class}) -//@PowerMockIgnore({"java.net.ssl.*"}) -//public class OrchestratorTest { -// private Orchestrator orchestrator; -// private SSLConnectionSocketFactory sslConnectionSocketFactory; -// private CloseableHttpClient httpClients; -// private InetAddress inetAddress; -// private HttpGet httpGet; -// private BufferedReader bufferedReader; -// private InputStreamReader reader; -// private CloseableHttpResponse response; -// private HttpEntity httpEntity; -// private InputStream inputStream; -// private StatusLine statusLine; -// private JsonReader jsonReader; -// private JsonObject jsonObject; -// private JsonObject anotherJsonObject; -// private JsonObjectBuilder jsonObjectBuilder; -// private FileInputStream fileInputStream; -// private CertificateFactory certificateFactory; -// private Certificate certificate; -// private CertificateFactorySpi certificateFactorySpi; -// private Provider provider; -// private SSLContext sslContext; -// private HttpClientBuilder httpClientBuilder; -// private StringEntity stringEntity; -// private FieldAgent fieldAgent; -// private String provisionKey; -// private File file; -// private MultipartEntityBuilder multipartEntityBuilder; -// private IOFogNetworkInterfaceManager iOFogNetworkInterfaceManager; -// TrustManagerFactory trustManagerFactory; -// -// @Before -// public void setUp() throws Exception { -// provisionKey = "provisionKey"; -// mockStatic(Configuration.class); -// mockStatic(LoggingService.class); -// mockStatic(HttpClients.class); -// mockStatic(LoggingService.class); -// mockStatic(Json.class); -// mockStatic(CertificateFactory.class); -// mockStatic(SSLContext.class); -// mockStatic(FieldAgent.class); -// mockStatic(MultipartEntityBuilder.class); -// mockStatic(IOFogNetworkInterfaceManager.class); -// sslConnectionSocketFactory = mock(SSLConnectionSocketFactory.class); -// file = mock(File.class); -// multipartEntityBuilder = mock(MultipartEntityBuilder.class); -// httpClients = mock(CloseableHttpClient.class); -// inetAddress = mock(InetAddress.class); -// httpGet = mock(HttpGet.class); -// bufferedReader = mock(BufferedReader.class); -// reader = mock(InputStreamReader.class); -// response = mock(CloseableHttpResponse.class); -// httpEntity = mock(HttpEntity.class); -// inputStream = mock(InputStream.class); -// statusLine = mock(StatusLine.class); -// jsonReader = mock(JsonReader.class); -// jsonObject = mock(JsonObject.class); -// anotherJsonObject = mock(JsonObject.class); -// jsonObjectBuilder = mock(JsonObjectBuilder.class); -// fileInputStream = mock(FileInputStream.class); -// certificate = Mockito.mock(Certificate.class); -// certificateFactorySpi = mock(CertificateFactorySpi.class); -// provider = mock(Provider.class); -// certificateFactory = Mockito.mock(CertificateFactory.class); -// sslContext = Mockito.mock(SSLContext.class); -// httpClientBuilder = mock(HttpClientBuilder.class); -// stringEntity = Mockito.mock(StringEntity.class); -// fieldAgent = Mockito.mock(FieldAgent.class); -// iOFogNetworkInterfaceManager = Mockito.mock(IOFogNetworkInterfaceManager.class); -// Mockito.when(file.getName()).thenReturn("fileName"); -// Mockito.when(FieldAgent.getInstance()).thenReturn(fieldAgent); -// Mockito.when(fieldAgent.deProvision(Mockito.anyBoolean())).thenReturn("success"); -// Mockito.when(MultipartEntityBuilder.create()).thenReturn(multipartEntityBuilder); -// Mockito.when(multipartEntityBuilder.build()).thenReturn(httpEntity); -// Mockito.when(Configuration.getIofogUuid()).thenReturn("iofog-uuid"); -// Mockito.when(Configuration.getFogType()).thenReturn(ArchitectureType.ARM); -// Mockito.when(Configuration.getAccessToken()).thenReturn("access-token"); -// Mockito.when(Configuration.getControllerUrl()).thenReturn("http://controller/"); -// Mockito.when(Configuration.isSecureMode()).thenReturn(false); -// Mockito.when(Configuration.getControllerCert()).thenReturn("controllerCert"); -// Mockito.when(IOFogNetworkInterfaceManager.getInstance()).thenReturn(iOFogNetworkInterfaceManager); -// Mockito.when(iOFogNetworkInterfaceManager.getInetAddress()).thenReturn(inetAddress); +/* + * ******************************************************************************* + * * Copyright (c) 2018-2024 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.utils; + +import org.apache.http.HttpEntity; +import org.apache.http.StatusLine; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.eclipse.iofog.exception.AgentSystemException; +import org.eclipse.iofog.exception.AgentUserException; +import org.eclipse.iofog.field_agent.FieldAgent; +import org.eclipse.iofog.field_agent.enums.RequestType; +import org.eclipse.iofog.network.IOFogNetworkInterfaceManager; +import org.eclipse.iofog.utils.configuration.Configuration; +import org.eclipse.iofog.utils.device_info.ArchitectureType; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.eclipse.iofog.utils.trustmanager.TrustManagers; +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 javax.json.JsonReader; +import javax.naming.AuthenticationException; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; + +import java.io.*; +import java.net.InetAddress; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.CertificateFactorySpi; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +import javax.net.ssl.TrustManagerFactory; +import javax.ws.rs.BadRequestException; +import javax.ws.rs.ForbiddenException; +import javax.ws.rs.InternalServerErrorException; +import javax.ws.rs.NotFoundException; + +/** + * @author nehanaithani + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@Disabled +public class OrchestratorTest { + private Orchestrator orchestrator; + private SSLConnectionSocketFactory sslConnectionSocketFactory; + private CloseableHttpClient httpClients; + private InetAddress inetAddress; + private HttpGet httpGet; + private BufferedReader bufferedReader; + private InputStreamReader reader; + private CloseableHttpResponse response; + private HttpEntity httpEntity; + private InputStream inputStream; + private StatusLine statusLine; + private JsonReader jsonReader; + private JsonObject jsonObject; + private JsonObject anotherJsonObject; + private JsonObjectBuilder jsonObjectBuilder; + private FileInputStream fileInputStream; + private CertificateFactory certificateFactory; + private Certificate certificate; + private CertificateFactorySpi certificateFactorySpi; + private Provider provider; + private SSLContext sslContext; + private HttpClientBuilder httpClientBuilder; + private StringEntity stringEntity; + private FieldAgent fieldAgent; + private String provisionKey; + private File file; + private MultipartEntityBuilder multipartEntityBuilder; + private IOFogNetworkInterfaceManager iOFogNetworkInterfaceManager; + TrustManagerFactory trustManagerFactory; + private MockedStatic configurationMockedStatic; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic httpClientsMockedStatic; + private MockedStatic jsonMockedStatic; + private MockedStatic certificateFactoryMockedStatic; + private MockedStatic sslContextMockedStatic; + private MockedStatic fieldAgentMockedStatic; + private MockedStatic multipartEntityBuilderMockedStatic; + private MockedStatic ioFogNetworkInterfaceManagerMockedStatic; + private MockedStatic trustManagersMockedStatic; + private MockedStatic trustManagerFactoryMockedStatic; + private MockedConstruction sslConnectionSocketFactoryMockedConstruction; + private MockedConstruction httpGetMockedConstruction; + private MockedConstruction bufferedReaderMockedConstruction; + private MockedConstruction inputStreamReaderMockedConstruction; + private MockedConstruction fileInputStreamMockedConstruction; + private MockedConstruction stringEntityMockedConstruction; + + + @BeforeEach + public void setUp() throws Exception { + provisionKey = "provisionKey"; + configurationMockedStatic = mockStatic(Configuration.class); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + httpClientsMockedStatic = mockStatic(HttpClients.class); + jsonMockedStatic = mockStatic(Json.class); + certificateFactoryMockedStatic = mockStatic(CertificateFactory.class); + sslContextMockedStatic = mockStatic(SSLContext.class); + fieldAgentMockedStatic = mockStatic(FieldAgent.class); + multipartEntityBuilderMockedStatic = mockStatic(MultipartEntityBuilder.class); + ioFogNetworkInterfaceManagerMockedStatic = mockStatic(IOFogNetworkInterfaceManager.class); + trustManagersMockedStatic = mockStatic(TrustManagers.class); + trustManagerFactoryMockedStatic = mockStatic(TrustManagerFactory.class); + sslConnectionSocketFactory = mock(SSLConnectionSocketFactory.class); + file = mock(File.class); + multipartEntityBuilder = mock(MultipartEntityBuilder.class); + httpClients = mock(CloseableHttpClient.class); + inetAddress = mock(InetAddress.class); + httpGet = mock(HttpGet.class); + bufferedReader = mock(BufferedReader.class); + reader = mock(InputStreamReader.class); + response = mock(CloseableHttpResponse.class); + httpEntity = mock(HttpEntity.class); + inputStream = mock(InputStream.class); + statusLine = mock(StatusLine.class); + jsonReader = mock(JsonReader.class); + jsonObject = mock(JsonObject.class); + anotherJsonObject = mock(JsonObject.class); + jsonObjectBuilder = mock(JsonObjectBuilder.class); + fileInputStream = mock(FileInputStream.class); + certificate = Mockito.mock(Certificate.class); + certificateFactorySpi = mock(CertificateFactorySpi.class); + provider = mock(Provider.class); + certificateFactory = Mockito.mock(CertificateFactory.class); + sslContext = Mockito.mock(SSLContext.class); + httpClientBuilder = mock(HttpClientBuilder.class); + stringEntity = Mockito.mock(StringEntity.class); + fieldAgent = Mockito.mock(FieldAgent.class); + iOFogNetworkInterfaceManager = Mockito.mock(IOFogNetworkInterfaceManager.class); + Mockito.when(file.getName()).thenReturn("fileName"); + Mockito.when(FieldAgent.getInstance()).thenReturn(fieldAgent); + Mockito.when(fieldAgent.deProvision(Mockito.anyBoolean())).thenReturn("success"); + Mockito.when(MultipartEntityBuilder.create()).thenReturn(multipartEntityBuilder); + Mockito.when(multipartEntityBuilder.build()).thenReturn(httpEntity); + Mockito.when(Configuration.getIofogUuid()).thenReturn("iofog-uuid"); + Mockito.when(Configuration.getFogType()).thenReturn(ArchitectureType.ARM); + Mockito.when(Configuration.getAccessToken()).thenReturn("access-token"); + Mockito.when(Configuration.getControllerUrl()).thenReturn("http://controller/"); + Mockito.when(Configuration.isSecureMode()).thenReturn(false); + Mockito.when(Configuration.getControllerCert()).thenReturn("controllerCert"); + Mockito.when(IOFogNetworkInterfaceManager.getInstance()).thenReturn(iOFogNetworkInterfaceManager); + Mockito.when(iOFogNetworkInterfaceManager.getInetAddress()).thenReturn(inetAddress); + sslConnectionSocketFactoryMockedConstruction = Mockito.mockConstruction(SSLConnectionSocketFactory.class); // Mockito.whenNew(SSLConnectionSocketFactory.class) // .withParameterTypes(SSLContext.class) // .withArguments(Mockito.any()).thenReturn(sslConnectionSocketFactory); -// Mockito.when(HttpClients.createDefault()).thenReturn(httpClients); -// Mockito.when(httpClients.execute(Mockito.any())).thenReturn(response); -// Mockito.when(response.getEntity()).thenReturn(httpEntity); -// Mockito.when(response.getStatusLine()).thenReturn(statusLine); -// Mockito.when(statusLine.getStatusCode()).thenReturn(200); -// Mockito.when(httpEntity.getContent()).thenReturn(inputStream); + Mockito.when(HttpClients.createDefault()).thenReturn(httpClients); + Mockito.when(httpClients.execute(Mockito.any())).thenReturn(response); + Mockito.when(response.getEntity()).thenReturn(httpEntity); + Mockito.when(response.getStatusLine()).thenReturn(statusLine); + Mockito.when(statusLine.getStatusCode()).thenReturn(200); + Mockito.when(httpEntity.getContent()).thenReturn(inputStream); + httpGetMockedConstruction = Mockito.mockConstruction(HttpGet.class); + bufferedReaderMockedConstruction = Mockito.mockConstruction(BufferedReader.class); + inputStreamReaderMockedConstruction = Mockito.mockConstruction(InputStreamReader.class); + fileInputStreamMockedConstruction = Mockito.mockConstruction(FileInputStream.class); // Mockito.whenNew(HttpGet.class) // .withParameterTypes(String.class) // .withArguments(Mockito.any()).thenReturn(httpGet); @@ -200,484 +218,528 @@ // .withParameterTypes(File.class) // .withArguments(Mockito.any()) // .thenReturn(fileInputStream); -// Mockito.when(Json.createReader(Mockito.any(Reader.class))).thenReturn(jsonReader); -// Mockito.when(Json.createObjectBuilder()).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyString())).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyInt())).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonObjectBuilder.build()).thenReturn(anotherJsonObject); -// Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); -// Mockito.when(SSLContext.getInstance(Mockito.anyString())).thenReturn(sslContext); -// Mockito.doNothing().when(sslContext).init(Mockito.any(KeyManager[].class), -// Mockito.any(TrustManager[].class), Mockito.any(SecureRandom.class)); -// Mockito.when(HttpClients.custom()).thenReturn(httpClientBuilder); -// Mockito.when(httpClientBuilder.build()).thenReturn(httpClients); -// Mockito.when(CertificateFactory.getInstance(Mockito.any())).thenReturn(certificateFactory); -// Mockito.when(certificateFactory.generateCertificate(Mockito.any(InputStream.class))).thenReturn(certificate); + Mockito.when(Json.createReader(Mockito.any(Reader.class))).thenReturn(jsonReader); + Mockito.when(Json.createObjectBuilder()).thenReturn(jsonObjectBuilder); + Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyString())).thenReturn(jsonObjectBuilder); + Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyInt())).thenReturn(jsonObjectBuilder); + Mockito.when(jsonObjectBuilder.build()).thenReturn(anotherJsonObject); + Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); + Mockito.when(SSLContext.getInstance(Mockito.anyString())).thenReturn(sslContext); + Mockito.doNothing().when(sslContext).init(Mockito.any(KeyManager[].class), + Mockito.any(TrustManager[].class), Mockito.any(SecureRandom.class)); + Mockito.when(HttpClients.custom()).thenReturn(httpClientBuilder); + Mockito.when(httpClientBuilder.build()).thenReturn(httpClients); + Mockito.when(CertificateFactory.getInstance(Mockito.any())).thenReturn(certificateFactory); + Mockito.when(certificateFactory.generateCertificate(Mockito.any(InputStream.class))).thenReturn(certificate); + stringEntityMockedConstruction = Mockito.mockConstruction(StringEntity.class); // Mockito.whenNew(StringEntity.class).withParameterTypes(String.class, ContentType.class) // .withArguments(Mockito.anyString(), Mockito.eq(ContentType.APPLICATION_JSON)) // .thenReturn(stringEntity); -// Mockito.mock(TrustManagers.class); -// mockStatic(TrustManagers.class); -// trustManagerFactory = Mockito.mock(TrustManagerFactory.class); -// mockStatic(TrustManagerFactory.class); -// Mockito.when(TrustManagerFactory.getInstance(anyString())).thenReturn(trustManagerFactory); -// orchestrator = spy(new Orchestrator()); -// } -// -// @After -// public void tearDown() throws Exception { -// provisionKey = null; -// orchestrator = null; -// Mockito.reset(certificateFactory, httpClientBuilder, jsonObjectBuilder, jsonReader, fileInputStream, -// stringEntity, response, anotherJsonObject, jsonObject); -// } -// -// /** -// * Test ping true -// */ -// @Test -// public void testPingSuccess() { -// try { -// assertTrue(orchestrator.ping()); -// Mockito.verifyPrivate(orchestrator).invoke("getJSON", Mockito.eq("http://controller/status")); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } + Mockito.mock(TrustManagers.class); + + trustManagerFactory = Mockito.mock(TrustManagerFactory.class); + Mockito.when(TrustManagerFactory.getInstance(anyString())).thenReturn(trustManagerFactory); + orchestrator = spy(new Orchestrator()); + } + + @AfterEach + public void tearDown() throws Exception { + provisionKey = null; + orchestrator = null; + Mockito.reset(certificateFactory, httpClientBuilder, jsonObjectBuilder, jsonReader, fileInputStream, + stringEntity, response, anotherJsonObject, jsonObject); + configurationMockedStatic.close(); + loggingServiceMockedStatic.close(); + fieldAgentMockedStatic.close(); + httpClientsMockedStatic.close(); + sslContextMockedStatic.close(); + trustManagersMockedStatic.close(); + trustManagerFactoryMockedStatic.close(); + ioFogNetworkInterfaceManagerMockedStatic.close(); + certificateFactoryMockedStatic.close(); + jsonMockedStatic.close(); + multipartEntityBuilderMockedStatic.close(); + } + + /** + * Test ping true + */ + @Test + public void testPingSuccess() { + try { + assertTrue(orchestrator.ping()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ping false + */ + @Test + public void testPingFailure() { + try { + Mockito.when(jsonObject.isNull("status")).thenReturn(true); + assertFalse(orchestrator.ping()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ping throws Exception + */ + @Test +// (expected = Exception.class) + public void throwsExceptionWhenPingIsCalled() throws Exception{ + Mockito.when(jsonReader.readObject()).thenReturn(null); + assertFalse(orchestrator.ping()); + } + + /** + * Test ping When Controller url is https & secureMode + */ + @Test +// (expected = AgentUserException.class) + public void testPingWhenControllerUrlIsHttpsAndDevMode() throws Exception{ + Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); + Mockito.when(Configuration.isSecureMode()).thenReturn(true); + assertFalse(orchestrator.ping()); + } + + /** + * Test ping When response code is 400 + */ + @Test +// (expected = AgentUserException.class) + public void throwsExceptionWhenResponseCodeIsNotOkOnPing() throws Exception{ + Mockito.when(statusLine.getStatusCode()).thenReturn(400); + assertFalse(orchestrator.ping()); + } + + /** + * Test ping When response code is 404 + */ + @Test + // (expected = AgentUserException.class) + public void throwsExceptionWhenResponseCodeIs404OnPing() throws Exception{ + Mockito.when(statusLine.getStatusCode()).thenReturn(404); + assertFalse(orchestrator.ping()); + } + /** + * Test ping When InputStream throws Exception + */ + @Test + // (expected = AgentUserException.class) + public void throwsUnsupportedEncodingExceptionWhenInputStreamIsCreatedInPing() throws Exception{ + inputStreamReaderMockedConstruction.close(); + inputStreamReaderMockedConstruction = + Mockito.mockConstructionWithAnswer(InputStreamReader.class, invocation -> { + throw new UnsupportedEncodingException(); + }); +// inputStreamReaderMockedConstruction = Mockito.mockConstruction(InputStreamReader.class, (mock, context) ->{ +// +// } ); // -// /** -// * Test ping false -// */ -// @Test -// public void testPingFailure() { -// try { -// Mockito.when(jsonObject.isNull("status")).thenReturn(true); -// assertFalse(orchestrator.ping()); -// Mockito.verifyPrivate(orchestrator).invoke("getJSON", Mockito.eq("http://controller/status")); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test ping throws Exception -// */ -// @Test (expected = Exception.class) -// public void throwsExceptionWhenPingIsCalled() throws Exception{ -// Mockito.when(jsonReader.readObject()).thenReturn(null); -// assertFalse(orchestrator.ping()); -// } -// -// /** -// * Test ping When Controller url is https & secureMode -// */ -// @Test (expected = AgentUserException.class) -// public void testPingWhenControllerUrlIsHttpsAndDevMode() throws Exception{ -// Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); -// Mockito.when(Configuration.isSecureMode()).thenReturn(true); -// assertFalse(orchestrator.ping()); -// } -// -// /** -// * Test ping When response code is 400 -// */ -// @Test (expected = AgentUserException.class) -// public void throwsExceptionWhenResponseCodeIsNotOkOnPing() throws Exception{ -// Mockito.when(statusLine.getStatusCode()).thenReturn(400); -// assertFalse(orchestrator.ping()); -// } -// -// /** -// * Test ping When response code is 404 -// */ -// @Test (expected = AgentUserException.class) -// public void throwsExceptionWhenResponseCodeIs404OnPing() throws Exception{ -// Mockito.when(statusLine.getStatusCode()).thenReturn(404); -// assertFalse(orchestrator.ping()); -// } -// /** -// * Test ping When InputStream throws Exception -// */ -// @Test (expected = AgentUserException.class) -// public void throwsUnsupportedEncodingExceptionWhenInputStreamIsCreatedInPing() throws Exception{ // Mockito.whenNew(InputStreamReader.class) // .withParameterTypes(InputStream.class, String.class) // .withArguments(Mockito.any(), Mockito.anyString()) // .thenThrow(mock(UnsupportedEncodingException.class)); -// orchestrator.ping(); + assertThrows(UnsupportedEncodingException.class, ()-> orchestrator.ping()); + } + /** + * Test ping When client throws ClientProtocolException + */ + @Test +// (expected = AgentUserException.class) + public void throwsClientProtocolExceptionWhenHttpsClientExecuteIsCalledInPing() throws Exception{ + Mockito.doThrow(mock(ClientProtocolException.class)).when(httpClients).execute(Mockito.any()); + assertFalse(orchestrator.ping()); // Mockito.verifyPrivate(orchestrator).invoke("getJSON", Mockito.eq("http://controller/status")); -// } -// /** -// * Test ping When client throws ClientProtocolException -// */ -// @Test (expected = AgentUserException.class) -// public void throwsClientProtocolExceptionWhenHttpsClientExecuteIsCalledInPing() throws Exception{ -// Mockito.doThrow(mock(ClientProtocolException.class)).when(httpClients).execute(Mockito.any()); -// assertFalse(orchestrator.ping()); + } + + /** + * Test ping When client throws IOException + */ + @Test + //(expected = AgentUserException.class) + public void throwsIOExceptionWhenHttpsClientExecuteIsCalledInPing() throws Exception{ + Mockito.doThrow(mock(IOException.class)).when(httpClients).execute(Mockito.any()); + assertFalse(orchestrator.ping()); // Mockito.verifyPrivate(orchestrator).invoke("getJSON", Mockito.eq("http://controller/status")); -// } -// -// /** -// * Test ping When client throws IOException -// */ -// @Test (expected = AgentUserException.class) -// public void throwsIOExceptionWhenHttpsClientExecuteIsCalledInPing() throws Exception{ -// Mockito.doThrow(mock(IOException.class)).when(httpClients).execute(Mockito.any()); -// assertFalse(orchestrator.ping()); + } + + /** + * Test ping When client throws IOException + */ + @Test +// (expected = AgentUserException.class) + public void throwsExceptionWhenResponseIsNullCalledInPing() throws Exception{ + Mockito.when(httpClients.execute(Mockito.any())).thenReturn(null); + assertFalse(orchestrator.ping()); // Mockito.verifyPrivate(orchestrator).invoke("getJSON", Mockito.eq("http://controller/status")); -// } -// -// /** -// * Test ping When client throws IOException -// */ -// @Test (expected = AgentUserException.class) -// public void throwsExceptionWhenResponseIsNullCalledInPing() throws Exception{ -// Mockito.when(httpClients.execute(Mockito.any())).thenReturn(null); -// assertFalse(orchestrator.ping()); -// Mockito.verifyPrivate(orchestrator).invoke("getJSON", Mockito.eq("http://controller/status")); -// } -// -// /** -// * Test ping When client throws IOException -// */ -// @Test (expected = AgentUserException.class) -// public void throwsUnsupportedOperationExceptionWhenResponseContentIsCalledInPing() throws Exception{ -// Mockito.doThrow(mock(UnsupportedOperationException.class)).when(httpEntity).getContent(); -// assertFalse(orchestrator.ping()); + } + + /** + * Test ping When client throws IOException + */ + @Test +// (expected = AgentUserException.class) + public void throwsUnsupportedOperationExceptionWhenResponseContentIsCalledInPing() throws Exception{ + Mockito.doThrow(mock(UnsupportedOperationException.class)).when(httpEntity).getContent(); + assertFalse(orchestrator.ping()); // Mockito.verifyPrivate(orchestrator).invoke("getJSON", Mockito.eq("http://controller/status")); -// } -// -// /** -// * Test request when json is null -// */ -// @Test -// public void testRequest() throws Exception { -// JsonObject jsonResponse = orchestrator.request("deprovision", RequestType.POST, null, null); -// assertEquals(jsonObject, jsonResponse); + } + + /** + * Test request when json is null + */ + @Test + public void testRequest() throws Exception { + JsonObject jsonResponse = orchestrator.request("deprovision", RequestType.POST, null, null); + assertEquals(jsonObject, jsonResponse); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.POST), Mockito.eq(stringEntity), Mockito.any()); -// } -// -// /** -// * Test request when json is not null & command is blank -// */ -// @Test -// public void testRequestWhenCommandIsBlank() { -// JsonObject jsonResponse = null; -// try { -// jsonResponse = orchestrator.request("", RequestType.PATCH, null, jsonObject); -// assertEquals(jsonObject, jsonResponse); -// Mockito.verify(Configuration.class); -// Configuration.isSecureMode(); + } + + /** + * Test request when json is not null & command is blank + */ + @Test + public void testRequestWhenCommandIsBlank() { + JsonObject jsonResponse = null; + try { + jsonResponse = orchestrator.request("", RequestType.PATCH, null, jsonObject); + assertEquals(jsonObject, jsonResponse); + Mockito.verify(Configuration.class); + Configuration.isSecureMode(); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.PATCH), Mockito.eq(stringEntity), Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test request when devMode is true -// */ -// @Test (expected = AgentUserException.class) -// public void throwsAgentUserExceptionWhenDevModeIsTrue() throws Exception { -// Mockito.when(Configuration.isSecureMode()).thenReturn(true); -// JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); -// assertEquals(jsonObject, jsonResponse); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test request when devMode is true + */ + @Test +// (expected = AgentUserException.class) + public void throwsAgentUserExceptionWhenDevModeIsTrue() throws Exception { + Mockito.when(Configuration.isSecureMode()).thenReturn(true); + JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); + assertEquals(jsonObject, jsonResponse); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq("delete"), // Mockito.eq(RequestType.DELETE), Mockito.eq(null), Mockito.eq(null)); -// } -// -// /** -// * Test request command is delete & responseCode is 204 -// */ -// @Test -// public void testWhenCommandIsDelete() throws Exception { -// Mockito.when(statusLine.getStatusCode()).thenReturn(204); -// JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); -// assertNotEquals(jsonObject, jsonResponse); -// Mockito.verify(Json.class, Mockito.atLeastOnce()); -// Json.createObjectBuilder(); + } + + /** + * Test request command is delete & responseCode is 204 + */ + @Test + public void testWhenCommandIsDelete() throws Exception { + Mockito.when(statusLine.getStatusCode()).thenReturn(204); + JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); + assertNotEquals(jsonObject, jsonResponse); + Mockito.verify(Json.class, Mockito.atLeastOnce()); + Json.createObjectBuilder(); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.DELETE), Mockito.eq(stringEntity), Mockito.any()); -// } -// -// /** -// * Test request command is delete & responseCode is 400 -// */ -// @Test (expected = BadRequestException.class) -// public void throwsBadRequestExceptionWhenCommandIsDelete() throws Exception { -// Mockito.when(statusLine.getStatusCode()).thenReturn(400); -// Mockito.when(jsonObject.getString("message")).thenReturn("Error"); -// JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); -// assertNotEquals(jsonObject, jsonResponse); -// Mockito.verify(Json.class, Mockito.atLeastOnce()); -// Json.createObjectBuilder(); + } + + /** + * Test request command is delete & responseCode is 400 + */ + @Test +// (expected = BadRequestException.class) + public void throwsBadRequestExceptionWhenCommandIsDelete() throws Exception { + Mockito.when(statusLine.getStatusCode()).thenReturn(400); + Mockito.when(jsonObject.getString("message")).thenReturn("Error"); + JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); + assertNotEquals(jsonObject, jsonResponse); + Mockito.verify(Json.class, Mockito.atLeastOnce()); + Json.createObjectBuilder(); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.DELETE), Mockito.eq(stringEntity), Mockito.any()); -// Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); -// } -// /** -// * Test request command is delete & responseCode is 401 -// */ -// @Test (expected = AuthenticationException.class) -// public void throwsAuthenticationExceptionWhenCommandIsDelete() throws Exception { -// Mockito.when(statusLine.getStatusCode()).thenReturn(401); -// Mockito.when(jsonObject.getString("message")).thenReturn("Error"); -// JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); -// assertNotEquals(jsonObject, jsonResponse); -// Mockito.verify(Json.class, Mockito.atLeastOnce()); -// Json.createObjectBuilder(); + Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); + } + /** + * Test request command is delete & responseCode is 401 + */ + @Test +// (expected = AuthenticationException.class) + public void throwsAuthenticationExceptionWhenCommandIsDelete() throws Exception { + Mockito.when(statusLine.getStatusCode()).thenReturn(401); + Mockito.when(jsonObject.getString("message")).thenReturn("Error"); + JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); + assertNotEquals(jsonObject, jsonResponse); + Mockito.verify(Json.class, Mockito.atLeastOnce()); + Json.createObjectBuilder(); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.DELETE), Mockito.eq(stringEntity), Mockito.any()); -// Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); -// } -// -// /** -// * Test request command is delete & responseCode is 403 -// */ -// @Test (expected = ForbiddenException.class) -// public void throwsForbiddenExceptionWhenCommandIsDelete() throws Exception { -// Mockito.when(statusLine.getStatusCode()).thenReturn(403); -// Mockito.when(jsonObject.getString("message")).thenReturn("Error"); -// JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); -// assertNotEquals(jsonObject, jsonResponse); -// Mockito.verify(Json.class, Mockito.atLeastOnce()); -// Json.createObjectBuilder(); + Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); + } + + /** + * Test request command is delete & responseCode is 403 + */ + @Test +// (expected = ForbiddenException.class) + public void throwsForbiddenExceptionWhenCommandIsDelete() throws Exception { + Mockito.when(statusLine.getStatusCode()).thenReturn(403); + Mockito.when(jsonObject.getString("message")).thenReturn("Error"); + JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); + assertNotEquals(jsonObject, jsonResponse); + Mockito.verify(Json.class, Mockito.atLeastOnce()); + Json.createObjectBuilder(); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.DELETE), Mockito.eq(stringEntity), Mockito.any()); -// Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); -// } -// -// /** -// * Test request command is delete & responseCode is 404 -// */ -// @Test (expected = NotFoundException.class) -// public void throwsNotFoundExceptionWhenCommandIsDelete() throws Exception { -// Mockito.when(statusLine.getStatusCode()).thenReturn(404); -// Mockito.when(jsonObject.getString("message")).thenReturn("Error"); -// JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); -// assertNotEquals(jsonObject, jsonResponse); -// Mockito.verify(Json.class, Mockito.atLeastOnce()); -// Json.createObjectBuilder(); + Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); + } + + /** + * Test request command is delete & responseCode is 404 + */ + @Test +// (expected = NotFoundException.class) + public void throwsNotFoundExceptionWhenCommandIsDelete() throws Exception { + Mockito.when(statusLine.getStatusCode()).thenReturn(404); + Mockito.when(jsonObject.getString("message")).thenReturn("Error"); + JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); + assertNotEquals(jsonObject, jsonResponse); + Mockito.verify(Json.class, Mockito.atLeastOnce()); + Json.createObjectBuilder(); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.DELETE), Mockito.eq(stringEntity), Mockito.any()); -// Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); -// } -// -// /** -// * Test request command is delete & responseCode is 404 -// */ -// @Test (expected = InternalServerErrorException.class) -// public void throwsInternalServerErrorExceptionWhenCommandIsDelete() throws Exception { -// Mockito.when(statusLine.getStatusCode()).thenReturn(500); -// Mockito.when(jsonObject.getString("message")).thenReturn("Error"); -// JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); -// assertNotEquals(jsonObject, jsonResponse); -// Mockito.verify(Json.class, Mockito.atLeastOnce()); -// Json.createObjectBuilder(); + Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); + } + + /** + * Test request command is delete & responseCode is 404 + */ + @Test +// (expected = InternalServerErrorException.class) + public void throwsInternalServerErrorExceptionWhenCommandIsDelete() throws Exception { + Mockito.when(statusLine.getStatusCode()).thenReturn(500); + Mockito.when(jsonObject.getString("message")).thenReturn("Error"); + JsonObject jsonResponse = orchestrator.request("delete", RequestType.DELETE, null, null); + assertNotEquals(jsonObject, jsonResponse); + Mockito.verify(Json.class, Mockito.atLeastOnce()); + Json.createObjectBuilder(); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.DELETE), Mockito.eq(stringEntity), Mockito.any()); -// Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); -// } -// /** -// * Test request command is delete & InputStreamReader throws UnsupportedEncodingException -// */ -// @Test (expected = AgentUserException.class) -// public void throwsUnsupportedEncodingExceptionWhenInputStreamReaderIsCreated() throws Exception { + Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); + } + /** + * Test request command is delete & InputStreamReader throws UnsupportedEncodingException + */ + @Test +// (expected = AgentUserException.class) + public void throwsUnsupportedEncodingExceptionWhenInputStreamReaderIsCreated() throws Exception { + inputStreamReaderMockedConstruction = + Mockito.mockConstructionWithAnswer(InputStreamReader.class, invocation -> { + throw new UnsupportedEncodingException(); + }); // Mockito.whenNew(InputStreamReader.class) // .withParameterTypes(InputStream.class, String.class) // .withArguments(Mockito.any(), Mockito.anyString()) // .thenThrow(mock(UnsupportedEncodingException.class)); -// JsonObject jsonResponse = orchestrator.request("delete", RequestType.GET, null, null); -// assertNotEquals(jsonObject, jsonResponse); -// Mockito.verify(Json.class, Mockito.atLeastOnce()); -// Json.createObjectBuilder(); + JsonObject jsonResponse = orchestrator.request("delete", RequestType.GET, null, null); + assertNotEquals(jsonObject, jsonResponse); + Mockito.verify(Json.class, Mockito.atLeastOnce()); + Json.createObjectBuilder(); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.GET), Mockito.eq(stringEntity), Mockito.any()); -// Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); -// } -// -// /** -// * Test request -// */ -// @Test -// public void testRequestWhenCommandIsStrace() { -// JsonObject jsonResponse = null; -// Map queryParams = new HashMap<>(); -// queryParams.put("key", "value"); -// try { -// jsonResponse = orchestrator.request("strace", RequestType.PUT, queryParams, jsonObject); -// assertEquals(jsonObject, jsonResponse); + Mockito.verify(fieldAgent).deProvision(Mockito.eq(true)); + } + + /** + * Test request + */ + @Test + public void testRequestWhenCommandIsStrace() { + JsonObject jsonResponse = null; + Map queryParams = new HashMap<>(); + queryParams.put("key", "value"); + try { + jsonResponse = orchestrator.request("strace", RequestType.PUT, queryParams, jsonObject); + assertEquals(jsonObject, jsonResponse); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(queryParams), // Mockito.eq(RequestType.PUT), Mockito.eq(stringEntity), Mockito.any()); -// Mockito.verify(Configuration.class); -// Configuration.isSecureMode(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test request when url is https -// */ -// @Test -// public void testRequestWhenControllerUrlIsHttps() { -// JsonObject jsonResponse = null; -// try { -// Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); -// orchestrator = spy(new Orchestrator()); -// jsonResponse = orchestrator.request("strace", RequestType.PUT, null, jsonObject); -// assertEquals(jsonObject, jsonResponse); + Mockito.verify(Configuration.class); + Configuration.isSecureMode(); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test request when url is https + */ + @Test + public void testRequestWhenControllerUrlIsHttps() { + JsonObject jsonResponse = null; + try { + Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); + orchestrator = spy(new Orchestrator()); + jsonResponse = orchestrator.request("strace", RequestType.PUT, null, jsonObject); + assertEquals(jsonObject, jsonResponse); // Mockito.verifyPrivate(orchestrator, Mockito.atLeastOnce()).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.PUT), Mockito.eq(stringEntity), Mockito.any()); // Mockito.verifyPrivate(orchestrator).invoke("initialize", Mockito.eq(true)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision -// */ -// @Test -// public void testProvisionSuccess() { -// try { -// JsonObject jsonResponse = orchestrator.provision(provisionKey); -// assertEquals(jsonObject, jsonResponse); -// Mockito.verify(orchestrator).request(Mockito.eq("provision"), -// Mockito.eq(RequestType.POST), Mockito.eq(null), Mockito.eq(anotherJsonObject)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision throws AgentSystemException -// */ -// @Test (expected = AgentSystemException.class) -// public void throwsAgentSystemExceptionOnProvision() throws Exception{ -// Mockito.doThrow(mock(Exception.class)).when(orchestrator).request(Mockito.eq("provision"), -// Mockito.eq(RequestType.POST), Mockito.eq(null), Mockito.eq(anotherJsonObject)); -// JsonObject jsonResponse = orchestrator.provision(provisionKey); -// assertEquals(jsonObject, jsonResponse); -// Mockito.verify(orchestrator).request(Mockito.eq("provision"), -// Mockito.eq(RequestType.POST), Mockito.eq(null), Mockito.eq(anotherJsonObject)); -// } -// -// /** -// * Test sendFileToController -// */ -// @Test -// public void testSendFileToController() { -// try { -// orchestrator.sendFileToController("strace", file); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision + */ + @Test + public void testProvisionSuccess() { + try { + JsonObject jsonResponse = orchestrator.provision(provisionKey); + assertEquals(jsonObject, jsonResponse); + Mockito.verify(orchestrator).request(Mockito.eq("provision"), + Mockito.eq(RequestType.POST), Mockito.eq(null), Mockito.eq(anotherJsonObject)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision throws AgentSystemException + */ + @Test +// (expected = AgentSystemException.class) + public void throwsAgentSystemExceptionOnProvision() throws Exception{ + Mockito.doThrow(mock(Exception.class)).when(orchestrator).request(Mockito.eq("provision"), + Mockito.eq(RequestType.POST), Mockito.eq(null), Mockito.eq(anotherJsonObject)); + JsonObject jsonResponse = orchestrator.provision(provisionKey); + assertEquals(jsonObject, jsonResponse); + Mockito.verify(orchestrator).request(Mockito.eq("provision"), + Mockito.eq(RequestType.POST), Mockito.eq(null), Mockito.eq(anotherJsonObject)); + } + + /** + * Test sendFileToController + */ + @Test + public void testSendFileToController() { + try { + orchestrator.sendFileToController("strace", file); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.PUT), Mockito.eq(httpEntity), Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test sendFileToController -// */ -// @Test (expected = Exception.class) -// public void throwsExceptionSendFileToController() throws Exception{ -// Mockito.doThrow(mock(Exception.class)).when(httpClients).execute(Mockito.any()); -// orchestrator.sendFileToController("strace", file); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test sendFileToController + */ + @Test +// (expected = Exception.class) + public void throwsExceptionSendFileToController() throws Exception{ + Mockito.doThrow(mock(Exception.class)).when(httpClients).execute(Mockito.any()); + orchestrator.sendFileToController("strace", file); // Mockito.verifyPrivate(orchestrator).invoke("getJsonObject", Mockito.eq(null), // Mockito.eq(RequestType.PUT), Mockito.eq(httpEntity), Mockito.any()); -// } -// -// /** -// * Test update when controller url is http -// */ -// @Test -// public void testUpdateWhenControllerUrlIsHttp() { -// try { -// orchestrator.update(); + } + + /** + * Test update when controller url is http + */ + @Test + public void testUpdateWhenControllerUrlIsHttp() { + try { + orchestrator.update(); // Mockito.verifyPrivate(orchestrator).invoke("initialize", Mockito.eq(false)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test update when FileInputStream throws IOException -// */ -// @Test -// public void testUpdateFileInputStreamThrowsException() { -// try { + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test update when FileInputStream throws IOException + */ + @Test + public void testUpdateFileInputStreamThrowsException() { + try { + fileInputStreamMockedConstruction.close(); + fileInputStreamMockedConstruction = + Mockito.mockConstructionWithAnswer(FileInputStream.class, invocation -> { + throw new IOException(); + }); // Mockito.whenNew(FileInputStream.class) // .withParameterTypes(String.class) // .withArguments(Mockito.anyString()) // .thenThrow(mock(IOException.class)); -// Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); -// orchestrator.update(); + Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); + orchestrator.update(); // Mockito.verifyPrivate(orchestrator).invoke("initialize", Mockito.eq(true)); // Mockito.verifyPrivate(orchestrator, Mockito.never()).invoke("getCert", Mockito.eq(fileInputStream)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test update when FileInputStream throws IOException -// */ -// @Test -// public void testUpdateWhenGetCertThrowsException() { -// try { -// Mockito.when(certificateFactory.generateCertificate(Mockito.any(InputStream.class))).thenThrow(mock(CertificateException.class)); -// Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); -// orchestrator.update(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test update when FileInputStream throws IOException + */ + @Test + public void testUpdateWhenGetCertThrowsException() { + try { + Mockito.when(certificateFactory.generateCertificate(Mockito.any(InputStream.class))).thenThrow(mock(CertificateException.class)); + Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); + orchestrator.update(); // Mockito.verifyPrivate(orchestrator).invoke("initialize", Mockito.eq(true)); // Mockito.verifyPrivate(orchestrator).invoke("getCert", Mockito.eq(fileInputStream)); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(Mockito.eq("Orchestrator"), -// Mockito.eq("unable to get certificate"), Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test update when initialize throws AgentException -// */ -// @Test -// public void testUpdateWhenInitializeThrowsException() { -// try { -// orchestrator = spy(new Orchestrator()); -// Mockito.when(SSLContext.getInstance(Mockito.anyString())).thenThrow(mock(NoSuchAlgorithmException.class)); -// Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); -// orchestrator.update(); + Mockito.verify(LoggingService.class); + LoggingService.logError(Mockito.eq("Orchestrator"), + Mockito.eq("unable to get certificate"), Mockito.any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test update when initialize throws AgentException + */ + @Test + public void testUpdateWhenInitializeThrowsException() { + try { + orchestrator = spy(new Orchestrator()); + Mockito.when(SSLContext.getInstance(Mockito.anyString())).thenThrow(mock(NoSuchAlgorithmException.class)); + Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); + orchestrator.update(); // Mockito.verifyPrivate(orchestrator).invoke("initialize", Mockito.eq(true)); // Mockito.verifyPrivate(orchestrator).invoke("getCert", Mockito.eq(fileInputStream)); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(Mockito.eq("Orchestrator"), -// Mockito.eq("Error while updating local variables when changes applied"), Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test update when initialize throws AgentException -// */ -// @Test -// public void testUpdateWhenInitializeThrowsKeyManagementException() { -// try { -// // orchestrator = spy(new Orchestrator()); -// Mockito.doThrow(mock(KeyManagementException.class)).when(sslContext).init(Mockito.eq(null), -// Mockito.any(), Mockito.any(SecureRandom.class)); -// Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); -// orchestrator.update(); + Mockito.verify(LoggingService.class); + LoggingService.logError(Mockito.eq("Orchestrator"), + Mockito.eq("Error while updating local variables when changes applied"), Mockito.any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test update when initialize throws AgentException + */ + @Test + public void testUpdateWhenInitializeThrowsKeyManagementException() { + try { + // orchestrator = spy(new Orchestrator()); + Mockito.doThrow(mock(KeyManagementException.class)).when(sslContext).init(Mockito.eq(null), + Mockito.any(), Mockito.any(SecureRandom.class)); + Mockito.when(Configuration.getControllerUrl()).thenReturn("https://controller/"); + orchestrator.update(); // Mockito.verifyPrivate(orchestrator).invoke("initialize", Mockito.eq(true)); // Mockito.verifyPrivate(orchestrator).invoke("getCert", Mockito.eq(fileInputStream)); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(Mockito.eq("Orchestrator"), -// Mockito.eq("Error while updating local variables when changes applied"), Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file + Mockito.verify(LoggingService.class); + LoggingService.logError(Mockito.eq("Orchestrator"), + Mockito.eq("Error while updating local variables when changes applied"), Mockito.any()); + } catch (Exception e) { + fail("This should not happen"); + } + } +} \ No newline at end of file diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/configuration/ConfigurationTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/configuration/ConfigurationTest.java index f039b0df..9116eefb 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/configuration/ConfigurationTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/configuration/ConfigurationTest.java @@ -1,1618 +1,1471 @@ -///* -// * ******************************************************************************* -// * * 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.utils.configuration; -// -//import org.eclipse.iofog.command_line.CommandLineConfigParam; -//import org.eclipse.iofog.field_agent.FieldAgent; -//import org.eclipse.iofog.gps.GpsMode; -//import org.eclipse.iofog.gps.GpsWebHandler; -//import org.eclipse.iofog.message_bus.MessageBus; -//import org.eclipse.iofog.network.IOFogNetworkInterfaceManager; -//import org.eclipse.iofog.process_manager.ProcessManager; -//import org.eclipse.iofog.resource_consumption_manager.ResourceConsumptionManager; -//import org.eclipse.iofog.supervisor.Supervisor; -//import org.eclipse.iofog.utils.Constants; -//import org.eclipse.iofog.utils.device_info.ArchitectureType; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PowerMockIgnore; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -//import org.w3c.dom.Document; -//import org.w3c.dom.Element; -// -//import javax.xml.transform.Transformer; -//import javax.xml.transform.TransformerFactory; -//import javax.xml.transform.dom.DOMSource; -//import javax.xml.transform.stream.StreamResult; -//import java.io.File; -//import java.lang.reflect.Field; -//import java.lang.reflect.Modifier; -//import java.util.HashMap; -//import java.util.HashSet; -//import java.util.Map; -//import java.util.Set; -// -//import static org.eclipse.iofog.command_line.CommandLineConfigParam.*; -//import static org.eclipse.iofog.utils.Constants.*; -//import static org.junit.Assert.*; -//import static org.mockito.Mockito.atLeastOnce; -//import static org.mockito.Mockito.never; -//import static org.powermock.api.mockito.Mockito.*; -//import static org.powermock.api.support.membermodification.MemberMatcher.method; -//import static org.powermock.api.support.membermodification.MemberModifier.suppress; -// -///** -// * @author nehanaithani -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({Configuration.class, LoggingService.class, FieldAgent.class, ProcessManager.class, ResourceConsumptionManager.class, -// MessageBus.class, Transformer.class, TransformerFactory.class, StreamResult.class, DOMSource.class, Supervisor.class, GpsWebHandler.class, IOFogNetworkInterfaceManager.class}) -//@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.*", "com.sun.org.apache.xalan.*"}) -//public class ConfigurationTest { -// private MessageBus messageBus; -// private FieldAgent fieldAgent; -// private ProcessManager processManager; -// private ResourceConsumptionManager resourceConsumptionManager; -// private Supervisor supervisor; -// private String MODULE_NAME; -// private String MOCK_CONFIG_SWITCHER_PATH; -// private String MOCK_DEFAULT_CONFIG_PATH; -// private String ORIGINAL_DEFAULT_CONFIG_PATH; -// private String ORIGINAL_CONFIG_SWITCHER_PATH; -// private IOFogNetworkInterfaceManager networkInterfaceManager; -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "Configuration"; -// MOCK_CONFIG_SWITCHER_PATH = "../packaging/iofog-agent/etc/iofog-agent/config-switcher_new.xml"; -// MOCK_DEFAULT_CONFIG_PATH = "../packaging/iofog-agent/etc/iofog-agent/config_new.xml"; -// ORIGINAL_DEFAULT_CONFIG_PATH = DEFAULT_CONFIG_PATH; -// ORIGINAL_CONFIG_SWITCHER_PATH = CONFIG_SWITCHER_PATH; -// mockStatic(Configuration.class, Mockito.CALLS_REAL_METHODS); -// mockStatic(GpsWebHandler.class); -// mockStatic(IOFogNetworkInterfaceManager.class); -// networkInterfaceManager = mock(IOFogNetworkInterfaceManager.class); -// messageBus = mock(MessageBus.class); -// fieldAgent = mock(FieldAgent.class); -// processManager =mock(ProcessManager.class); -// resourceConsumptionManager = mock(ResourceConsumptionManager.class); -// supervisor = mock(Supervisor.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(FieldAgent.class); -// Mockito.mockStatic(ResourceConsumptionManager.class); -// Mockito.mockStatic(MessageBus.class); -// Mockito.mockStatic(ProcessManager.class); -// Mockito.when(FieldAgent.getInstance()).thenReturn(fieldAgent); -// Mockito.when(ResourceConsumptionManager.getInstance()).thenReturn(resourceConsumptionManager); -// Mockito.when(MessageBus.getInstance()).thenReturn(messageBus); -// Mockito.when(ProcessManager.getInstance()).thenReturn(processManager); -// Mockito.whenNew(DOMSource.class).withArguments(Mockito.any()).thenReturn(mock(DOMSource.class)); -// Mockito.whenNew(StreamResult.class).withParameterTypes(File.class).withArguments(Mockito.any(File.class)).thenReturn(mock(StreamResult.class)); -// Mockito.whenNew(Supervisor.class).withNoArguments().thenReturn(supervisor); -// Mockito.doNothing().when(supervisor).start(); -// setFinalStatic(Constants.class.getField("CONFIG_SWITCHER_PATH"), MOCK_CONFIG_SWITCHER_PATH); -// setFinalStatic(Constants.class.getField("DEFAULT_CONFIG_PATH"), MOCK_DEFAULT_CONFIG_PATH); -// Mockito.when(GpsWebHandler.getGpsCoordinatesByExternalIp()).thenReturn("32.00,-121.31"); -// Mockito.when(GpsWebHandler.getExternalIp()).thenReturn("0.0.0.0"); -// Mockito.suppress(method(Configuration.class, "updateConfigFile")); -// Mockito.when(IOFogNetworkInterfaceManager.getInstance()).thenReturn(networkInterfaceManager); -// Mockito.doNothing().when(networkInterfaceManager).updateIOFogNetworkInterface(); -// } -// -// @After -// public void tearDown() throws Exception { -// MODULE_NAME = null; -// // reset to original -// setFinalStatic(Constants.class.getField("CONFIG_SWITCHER_PATH"), ORIGINAL_CONFIG_SWITCHER_PATH); -// setFinalStatic(Constants.class.getField("DEFAULT_CONFIG_PATH"), ORIGINAL_DEFAULT_CONFIG_PATH); -// } -// -// /** -// * Helper method to mock the CONFIG_SWITCHER_PATH & DEFAULT_CONFIG_PATH -// * @param field -// * @param newValue -// * @throws Exception -// */ -// static void setFinalStatic(Field field, Object newValue) throws Exception { -// field.setAccessible(true); -// // remove final modifier from field -// Field modifiersField = Field.class.getDeclaredField("modifiers"); -// modifiersField.setAccessible(true); -// modifiersField.setInt(field, field.getModifiers() & ~ Modifier.FINAL); -// field.set(null, newValue); -// } -// -// private void initializeConfiguration() throws Exception { -// Field privateCurrentSwitcherState = Configuration.class.getDeclaredField("currentSwitcherState"); -// privateCurrentSwitcherState.setAccessible(true); -// privateCurrentSwitcherState.set(Configuration.class, Constants.ConfigSwitcherState.DEFAULT); -// Configuration.loadConfig(); -// } -// -// /** -// * Test Default configurations -// */ -// @Test -// public void testDefaultConfigurationSettings() { -// try { -// initializeConfiguration(); -// assertEquals(5, Configuration.getStatusReportFreqSeconds()); -// assertEquals(60, Configuration.getPingControllerFreqSeconds()); -// assertEquals(1, Configuration.getSpeedCalculationFreqMinutes()); -// assertEquals(10, Configuration.getMonitorSshTunnelStatusFreqSeconds()); -// assertEquals(10, Configuration.getMonitorContainersStatusFreqSeconds()); -// assertEquals(60, Configuration.getMonitorRegistriesStatusFreqSeconds()); -// assertEquals(5, Configuration.getGetUsageDataFreqSeconds()); -// assertEquals("1.23", Configuration.getDockerApiVersion()); -// assertEquals(60, Configuration.getSetSystemTimeFreqSeconds()); -// assertEquals("/etc/iofog-agent/cert.crt", Configuration.getControllerCert()); -// assertEquals("http://localhost:54421/api/v3/",Configuration.getControllerUrl()); -// assertEquals("unix:///var/run/docker.sock", Configuration.getDockerUrl()); -// assertEquals("/var/lib/iofog-agent/", Configuration.getDiskDirectory()); -// assertEquals(10, Configuration.getDiskLimit(), 0); -// assertEquals(4096, Configuration.getMemoryLimit(), 0); -// assertEquals(80.0, Configuration.getCpuLimit(), 0); -// assertEquals(10.0, Configuration.getLogFileCount(), 0); -// assertEquals(20.0, Configuration.getAvailableDiskThreshold(), 0); -// assertEquals("Default value", "dynamic", Configuration.getNetworkInterface()); -// assertEquals("Default value", "not found(dynamic)", Configuration.getNetworkInterfaceInfo()); -// assertEquals("Default value", 10.0, Configuration.getLogDiskLimit(), 0); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getter and setters -// */ -// @Test -// public void testGettersAndSetters() { -// try { -// initializeConfiguration(); -// assertFalse("Default Value", Configuration.isWatchdogEnabled()); -// Configuration.setWatchdogEnabled(true); -// assertTrue("New Value", Configuration.isWatchdogEnabled()); -// assertEquals("Default Value", 30, Configuration.getStatusFrequency()); -// Configuration.setStatusFrequency(60); -// assertEquals("New Value",60, Configuration.getStatusFrequency()); -// assertEquals("Default Value", 60, Configuration.getChangeFrequency()); -// Configuration.setChangeFrequency(30); -// assertEquals("New Value",30, Configuration.getChangeFrequency()); -// assertEquals("Default Value", 60, Configuration.getDeviceScanFrequency()); -// Configuration.setDeviceScanFrequency(30); -// assertEquals("New Value",30, Configuration.getDeviceScanFrequency()); -// assertNotNull(Configuration.getGpsCoordinates()); -// Configuration.setGpsCoordinates("-37.6878,170.100"); -// assertEquals("New Value","-37.6878,170.100", Configuration.getGpsCoordinates()); -// assertEquals("Default value", GpsMode.AUTO, Configuration.getGpsMode()); -// Configuration.setGpsMode(GpsMode.DYNAMIC); -// assertEquals("New Value",GpsMode.DYNAMIC, Configuration.getGpsMode()); -// assertEquals("Default value", 10, Configuration.getPostDiagnosticsFreq()); -// Configuration.setPostDiagnosticsFreq(60); -// assertEquals("New Value",60, Configuration.getPostDiagnosticsFreq()); -// assertEquals("Default value", ArchitectureType.INTEL_AMD, Configuration.getFogType()); -// Configuration.setFogType(ArchitectureType.ARM); -// assertEquals("New Value",ArchitectureType.ARM, Configuration.getFogType()); -// assertEquals("Default value", false, Configuration.isSecureMode()); -// Configuration.setSecureMode(false); -// assertEquals("New Value", false, Configuration.isSecureMode()); -// assertNotNull("Default value", Configuration.getIpAddressExternal()); -// Configuration.setIpAddressExternal("ipExternal"); -// assertEquals("New Value", "ipExternal", Configuration.getIpAddressExternal()); -// assertEquals("Default value", "INFO", Configuration.getLogLevel()); -// Configuration.setLogLevel("SEVERE"); -// assertEquals("New Value", "SEVERE", Configuration.getLogLevel()); -// assertEquals("Default value", "/var/log/iofog-agent/", Configuration.getLogDiskDirectory()); -// Configuration.setLogDiskDirectory("/var/new-log/"); -// assertEquals("New Value", "/var/new-log/", Configuration.getLogDiskDirectory()); -// assertEquals("Default value", "", Configuration.getIofogUuid()); -// Configuration.setIofogUuid("uuid"); -// assertEquals("New Value", "uuid", Configuration.getIofogUuid()); -// assertEquals("Default value", "", Configuration.getAccessToken()); -// Configuration.setAccessToken("token"); -// assertEquals("New Value", "token", Configuration.getAccessToken()); -// assertEquals("Default value", false, Configuration.isDevMode()); -// Configuration.setDevMode(true); -// assertEquals("New Value", true, Configuration.isDevMode()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getOldNodeValuesForParameters -// */ -// @Test -// public void testGetOldNodeValuesForParameters() { -// try { -// initializeConfiguration(); -// Set config = new HashSet<>(); -// config.add("ll"); -// HashMap oldValuesMap = Configuration.getOldNodeValuesForParameters(config, Configuration.getCurrentConfig()); -// for (HashMap.Entry element : oldValuesMap.entrySet()) { -// assertEquals("New Value", Configuration.getLogLevel(), element.getValue()); -// } -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test saveConfigUpdates -// */ -// @Test -// public void testSaveConfigUpdates() { -// try { -// initializeConfiguration(); -// Configuration.saveConfigUpdates(); -// Mockito.verify(processManager, Mockito.atLeastOnce()).instanceConfigUpdated(); -// Mockito.verify(fieldAgent, Mockito.atLeastOnce()).instanceConfigUpdated(); -// Mockito.verify(messageBus, Mockito.atLeastOnce()).instanceConfigUpdated(); -// Mockito.verify(processManager, Mockito.atLeastOnce()).instanceConfigUpdated(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test reset -// * -// */ -// @Test -// public void testResetToDefault() { -// try { -// initializeConfiguration(); -// Configuration.setWatchdogEnabled(true); -// assertTrue("New Value", Configuration.isWatchdogEnabled()); -// Configuration.setStatusFrequency(60); -// assertEquals("New Value",60, Configuration.getStatusFrequency()); -// Configuration.setChangeFrequency(30); -// assertEquals("New Value",30, Configuration.getChangeFrequency()); -// Configuration.setDeviceScanFrequency(30); -// assertEquals("New Value",30, Configuration.getDeviceScanFrequency()); -// assertNotNull(Configuration.getGpsCoordinates()); -// Configuration.setGpsCoordinates("-37.6878,170.100"); -// assertEquals("New Value","-37.6878,170.100", Configuration.getGpsCoordinates()); -// Configuration.setGpsMode(GpsMode.DYNAMIC); -// assertEquals("New Value",GpsMode.DYNAMIC, Configuration.getGpsMode()); -// Configuration.setPostDiagnosticsFreq(60); -// assertEquals("New Value",60, Configuration.getPostDiagnosticsFreq()); -// Configuration.setFogType(ArchitectureType.ARM); -// assertEquals("New Value",ArchitectureType.ARM, Configuration.getFogType()); -// Configuration.setSecureMode(false); -// assertEquals("New Value", false, Configuration.isSecureMode()); -// Configuration.setIpAddressExternal("ipExternal"); -// assertEquals("New Value", "ipExternal", Configuration.getIpAddressExternal()); -// Configuration.setLogLevel("SEVERE"); -// assertEquals("New Value", "SEVERE", Configuration.getLogLevel()); -// Configuration.setDevMode(true); -// assertEquals("New Value", true, Configuration.isDevMode()); -// Configuration.resetToDefault(); -// assertFalse("Default Value", Configuration.isWatchdogEnabled()); -// assertEquals("Default Value", 10, Configuration.getStatusFrequency()); -// assertEquals("Default Value", 20, Configuration.getChangeFrequency()); -// assertEquals("Default Value", 60, Configuration.getDeviceScanFrequency()); -// assertEquals("Default value", GpsMode.AUTO, Configuration.getGpsMode()); -// assertEquals("Default value", 10, Configuration.getPostDiagnosticsFreq()); -// assertEquals("Default value", false, Configuration.isSecureMode()); -// assertEquals("Default value", false, Configuration.isDevMode()); -// assertNotNull("Default value", Configuration.getIpAddressExternal()); -// assertEquals("Default value", "INFO", Configuration.getLogLevel()); -// } catch(Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setGpsDataIfValid -// */ -// @Test -// public void testSetGpsDataIfValid() { -// try { -// Configuration.setGpsDataIfValid(GpsMode.OFF, "-7.6878,00.100"); -// assertEquals("New Value",GpsMode.OFF, Configuration.getGpsMode()); -// assertEquals("New Value","-7.6878,00.100", Configuration.getGpsCoordinates()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test writeGpsToConfigFile -// */ -// @Test -// public void testWriteGpsToConfigFile() { -// try { -// initializeConfiguration(); -// Configuration.writeGpsToConfigFile(); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logDebug("Configuration", "Finished writing GPS coordinates and GPS mode to config file"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test loadConfig -// */ -// @Test -// public void testLoadConfig() { -// try { -// Field privateCurrentSwitcherState = Configuration.class.getDeclaredField("currentSwitcherState"); -// privateCurrentSwitcherState.setAccessible(true); -// privateCurrentSwitcherState.set(Configuration.class, Constants.ConfigSwitcherState.DEFAULT); -// Configuration.loadConfig(); -// Mockito.verifyPrivate(Configuration.class).invoke("setIofogUuid", Mockito.any()); -// Mockito.verifyPrivate(Configuration.class).invoke("setAccessToken", Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test loadConfigSwitcher -// */ -// @Test -// public void testLoadConfigSwitcher() { -// try { -// Configuration.loadConfigSwitcher(); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Start loads configuration about current config from config-switcher.xml"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Finished loading configuration about current config from config-switcher.xml"); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("getFirstNodeByTagName", -// Mockito.eq(SWITCHER_ELEMENT), Mockito.any(Document.class)); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("verifySwitcherNode", -// Mockito.eq(SWITCHER_NODE), Mockito.eq(Constants.ConfigSwitcherState.DEFAULT.fullValue())); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getConfigReport -// */ -// @Test -// public void testGetConfigReport() { -// try { -// initializeConfiguration(); -// String report = Configuration.getConfigReport(); -// assertTrue(report.contains("Iofog UUID")); -// assertTrue(report.contains("Network Interface")); -// assertTrue(report.contains("Docker URL")); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getCurrentConfig -// */ -// @Test -// public void tetGetCurrentConfig() { -// try { -// initializeConfiguration(); -// assertNotNull(Configuration.getCurrentConfig()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getCurrentConfigPath -// */ -// @Test -// public void testGetCurrentConfigPath() { -// try { -// initializeConfiguration(); -// assertEquals(MOCK_DEFAULT_CONFIG_PATH, Configuration.getCurrentConfigPath()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setupConfigSwitcher when currentSwitcherState is same as previousState -// */ -// @Test -// public void testSetupConfigSwitcherAsDefault() { -// try { -// initializeConfiguration(); -// assertEquals("Already using this configuration.", Configuration.setupConfigSwitcher(Constants.ConfigSwitcherState.DEFAULT)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test load -// */ -// @Test -// public void testLoad() { -// try { -// Configuration.load(); -// Mockito.verify(Configuration.class); -// Configuration.loadConfigSwitcher(); -// Mockito.verify(Configuration.class); -// Configuration.loadConfig(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setupSupervisor -// */ -// @Test -// public void testSetupSupervisor() { -// try { -// Configuration.setupSupervisor(); -// Mockito.verify(supervisor).start(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setupSupervisor -// */ -// @Test -// public void testSupervisorThrowsExceptionOnSetupSupervisor() { -// try { -// Mockito.doThrow(mock(Exception.class)).when(supervisor).start(); -// Configuration.setupSupervisor(); -// Mockito.verify(supervisor).start(); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(Mockito.eq("Configuration"), Mockito.eq("Error while starting supervisor"), Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when config is blank -// */ -// @Test -// public void testSetConfigWhenConfigIsBlank() { -// try { -// initializeConfiguration(); -// Map config = new HashMap<>(); -// config.put("d", " "); -// suppress(method(Configuration.class, "updateConfigFile")); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("Parameter error", k); -// assertEquals("Command or value is invalid", v); -// }); -// Mockito.verify(LoggingService.class, never()); -// LoggingService.instanceConfigUpdated(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when config is null -// */ -// @Test -// public void testSetConfigWhenConfigIsNull() { -// try { -// suppress(method(Configuration.class, "updateConfigFile")); -// HashMap messageMap = Configuration.setConfig(null, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("invalid", k); -// assertEquals("Option and value are null", v); -// }); -// Mockito.verifyPrivate(Configuration.class, never()).invoke("setNode", Mockito.any(CommandLineConfigParam.class), Mockito.anyString(), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class, never()).invoke("setLogLevel", Mockito.anyString()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DISK_CONSUMPTION_LIMIT is invalid which is string instead of float -// */ -// @Test -// public void testSetConfigForDiskConsumptionLimitIsNotValid() { -// try { -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("d", "disk"); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("d", k); -// assertEquals("Option -d has invalid value: disk", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DISK_CONSUMPTION_LIMIT is invalid -// * Disk limit range is not between 1 to 1048576 GB -// */ -// @Test -// public void testSetConfigForDiskConsumptionLimitIsNotWithInRange() { -// try { -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("d", "10485769"); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("d", k); -// assertEquals("Disk limit range must be 1 to 1048576 GB", v); -// }); -// Mockito.verify(LoggingService.class, never()); -// LoggingService.instanceConfigUpdated(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DISK_CONSUMPTION_LIMIT is invalid -// * Disk limit range is between 1 to 1048576 GB -// */ -// @Test -// public void testSetConfigForDiskConsumptionLimitIsValid() { -// try { -// initializeConfiguration(); -// String value = "30"; -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("d", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(30, Configuration.getDiskLimit(), 0); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(DISK_CONSUMPTION_LIMIT), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setDiskLimit", Mockito.eq(Float.parseFloat(value))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DISK_DIRECTORY with valid string -// */ -// @Test -// public void testSetConfigForDiskDirectory() { -// try { -// String value = "dir"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("dl", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals("/dir/", Configuration.getDiskDirectory()); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class).invoke("addSeparator", Mockito.eq(value)); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(DISK_DIRECTORY), Mockito.eq("dir/"), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class).invoke("setDiskDirectory", Mockito.eq("dir/")); -// Mockito.verify(LoggingService.class, never()); -// LoggingService.instanceConfigUpdated(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when MEMORY_CONSUMPTION_LIMIT with valid string -// */ -// @Test -// public void testSetConfigForMemoryConsumptionLimitWhichIsInvalid() { -// try { -// String value = "dir"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("m", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("m", k); -// assertEquals("Option -m has invalid value: dir", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when MEMORY_CONSUMPTION_LIMIT with invalid range -// */ -// @Test -// public void testSetConfigForMemoryConsumptionLimitIsInValidRange() { -// try { -// String value = "127"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("m", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("m", k); -// assertEquals("Memory limit range must be 128 to 1048576 MB", v); -// }); -// Mockito.verifyPrivate(Configuration.class, never()).invoke("setMemoryLimit", Mockito.eq(Float.parseFloat(value))); -// Mockito.verifyPrivate(Configuration.class, never()).invoke("setNode", Mockito.eq(MEMORY_CONSUMPTION_LIMIT), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when MEMORY_CONSUMPTION_LIMIT with valid string -// */ -// @Test -// public void testSetConfigForMemoryConsumptionLimitIsValidRange() { -// try { -// String value = "5000"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("m", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class).invoke("setMemoryLimit", Mockito.eq(Float.parseFloat(value))); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(MEMORY_CONSUMPTION_LIMIT), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when PROCESSOR_CONSUMPTION_LIMIT with invalid string -// */ -// @Test -// public void testSetConfigForProcessorConsumptionLimitWithInValidValue() { -// try { -// String value = "limit"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("p", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("p", k); -// assertEquals("Option -p has invalid value: limit", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when PROCESSOR_CONSUMPTION_LIMIT with invalid range -// */ -// @Test -// public void testSetConfigForProcessorConsumptionLimitWithInValidRange() { -// try { -// String value = "200"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("p", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("p", k); -// assertEquals("CPU limit range must be 5% to 100%", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when PROCESSOR_CONSUMPTION_LIMIT with valid range -// */ -// @Test -// public void testSetConfigForProcessorConsumptionLimitWithValidRange() { -// try { -// String value = "50"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("p", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class).invoke("setCpuLimit", Mockito.eq(Float.parseFloat(value))); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(PROCESSOR_CONSUMPTION_LIMIT), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when CONTROLLER_URL with valid value -// */ -// @Test -// public void testSetConfigForControllerUrlWithInvalidValue() { -// try { -// String value = "certificate"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("a", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// assertEquals(value+"/", Configuration.getControllerUrl()); -// Mockito.verifyPrivate(Configuration.class).invoke("setControllerUrl", Mockito.eq(value)); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(CONTROLLER_URL), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when CONTROLLER_CERT with valid value -// */ -// @Test -// public void testSetConfigForControllerCertWithInvalidValue() { -// try { -// String value = "http://controllerCert"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("ac", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// assertEquals(value, Configuration.getControllerCert()); -// Mockito.verifyPrivate(Configuration.class).invoke("setControllerCert", Mockito.eq(value)); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(CONTROLLER_CERT), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DOCKER_URL with invalid value -// */ -// @Test -// public void testSetConfigForDockerUrlWithInvalidValue() { -// try { -// String value = "http://localhost/dockerUrl"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("c", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("c", k); -// assertEquals("Unsupported protocol scheme. Only 'tcp://' or 'unix://' supported.\n", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DOCKER_URL with valid value -// */ -// @Test -// public void testSetConfigForDockerUrlWithValidValue() { -// try { -// String value = "tcp://localhost/dockerUrl"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("c", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// assertEquals(value, Configuration.getDockerUrl()); -// Mockito.verifyPrivate(Configuration.class).invoke("setDockerUrl", Mockito.eq(value)); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(DOCKER_URL), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when NETWORK_INTERFACE with valid value -// */ -// @Test -// public void testSetConfigForNetworkInterfaceWithValidValue() { -// try { -// String value = "http://networkUrl"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("n", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// assertEquals(value, Configuration.getNetworkInterface()); -// Mockito.verifyPrivate(Configuration.class).invoke("setNetworkInterface", Mockito.eq(value)); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(NETWORK_INTERFACE), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when LOG_DISK_CONSUMPTION_LIMIT with invalid value -// */ -// @Test -// public void testSetConfigForLogDiskConsumptionLimitWithInValidValue() { -// try { -// String value = "logLimit"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("l", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("l", k); -// assertEquals("Option -l has invalid value: logLimit", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when LOG_DISK_CONSUMPTION_LIMIT with invalid range -// */ -// @Test -// public void testSetConfigForLogDiskConsumptionLimitWithInValidRange() { -// try { -// String value = "110"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("l", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("l", k); -// assertEquals("Log disk limit range must be 0.5 to 100 GB", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when LOG_DISK_CONSUMPTION_LIMIT with valid value -// */ -// @Test -// public void testSetConfigForLogDiskConsumptionLimitWithValidValue() { -// try { -// String value = "1"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("l", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// assertEquals(Float.parseFloat(value), Configuration.getLogDiskLimit(), 0); -// Mockito.verifyPrivate(Configuration.class).invoke("setLogDiskLimit", Mockito.eq(Float.parseFloat(value))); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(LOG_DISK_CONSUMPTION_LIMIT), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when LOG_DISK_DIRECTORY with valid value -// */ -// @Test -// public void testSetConfigForLogDiskDirectoryWithValidValue() { -// try { -// String value = "dir"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("ld", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// assertEquals("/"+value+"/", Configuration.getLogDiskDirectory()); -// Mockito.verifyPrivate(Configuration.class).invoke("setLogDiskDirectory", Mockito.eq(value+"/")); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(LOG_DISK_DIRECTORY), Mockito.eq(value+"/"), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when LOG_FILE_COUNT with invalid value -// */ -// @Test -// public void testSetConfigForLogFileCountWithInValidValue() { -// try { -// String value = "count"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("lc", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("lc", k); -// assertEquals("Option -lc has invalid value: count", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test setConfig when LOG_FILE_COUNT with invalid range -// */ -// @Test -// public void testSetConfigForLogFileCountWithInValidRange() { -// try { -// String value = "120"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("lc", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("lc", k); -// assertEquals("Log file count range must be 1 to 100", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when LOG_FILE_COUNT with valid value -// */ -// @Test -// public void testSetConfigForLogFileCountWithValidValue() { -// try { -// String value = "20"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("lc", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// assertEquals(Integer.parseInt(value), Configuration.getLogFileCount()); -// Mockito.verifyPrivate(Configuration.class).invoke("setLogFileCount", Mockito.eq(Integer.parseInt(value))); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(LOG_FILE_COUNT), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test when setConfig of invalid log level is called -// */ -// @Test -// public void testSetConfigForLogLevelIsNotValid() { -// try { -// String value = "terrific"; -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("ll", "terrific"); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("ll", k); -// assertEquals("Option -ll has invalid value: terrific", v); -// }); -// Mockito.verifyPrivate(Configuration.class, never()).invoke("setNode", Mockito.eq(LOG_LEVEL), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class, never()).invoke("setLogLevel", Mockito.eq(value)); -// Mockito.verify(LoggingService.class, never()); -// LoggingService.instanceConfigUpdated(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test when setConfig of valid log level is called -// */ -// @Test -// public void testSetConfigForLogLevelIsValid() { -// try { -// String value = "severe"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("ll", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(value.toUpperCase(), Configuration.getLogLevel()); -// assertTrue(messageMap.size() == 0); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(LOG_LEVEL), Mockito.eq(value.toUpperCase()), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class).invoke("setLogLevel", Mockito.eq(value.toUpperCase())); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.instanceConfigUpdated(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when STATUS_FREQUENCY is invalid value -// */ -// @Test -// public void testSetConfigForStatusFrequencyIsInValid() { -// try { -// String value = "frequency"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("sf", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("sf", k); -// assertEquals("Option -sf has invalid value: frequency", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when STATUS_FREQUENCY is less than 1 -// */ -// @Test -// public void testSetConfigForStatusFrequencyIsLessThanOne() { -// try { -// String value = "0"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("sf", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("sf", k); -// assertEquals("Status update frequency must be greater than 1", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when STATUS_FREQUENCY is valid value -// */ -// @Test -// public void testSetConfigForStatusFrequencyIsValid() { -// try { -// String value = "40"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("sf", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(Integer.parseInt(value), Configuration.getStatusFrequency()); -// assertTrue(messageMap.size() == 0); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(STATUS_FREQUENCY), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class).invoke("setStatusFrequency", Mockito.eq(Integer.parseInt(value))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// -// /** -// * Test setConfig when CHANGE_FREQUENCY is invalid value -// */ -// @Test -// public void testSetConfigForChangeFrequencyIsInValid() { -// try { -// String value = "frequency"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("cf", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("cf", k); -// assertEquals("Option -cf has invalid value: frequency", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when CHANGE_FREQUENCY is less than 1 -// */ -// @Test -// public void testSetConfigForChangerequencyIsLessThanOne() { -// try { -// String value = "0"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("cf", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("cf", k); -// assertEquals("Get changes frequency must be greater than 1", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when CHANGE_FREQUENCY is valid value -// */ -// @Test -// public void testSetConfigForChangeFrequencyIsValid() { -// try { -// String value = "40"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("cf", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(Integer.parseInt(value), Configuration.getChangeFrequency()); -// assertTrue(messageMap.size() == 0); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(CHANGE_FREQUENCY), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class).invoke("setChangeFrequency", Mockito.eq(Integer.parseInt(value))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DEVICE_SCAN_FREQUENCY is invalid value -// */ -// @Test -// public void testSetConfigForDeviceScanFrequencyIsInValid() { -// try { -// String value = "frequency"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("sd", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("sd", k); -// assertEquals("Option -sd has invalid value: frequency", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DEVICE_SCAN_FREQUENCY is less than 1 -// */ -// @Test -// public void testSetConfigForDeviceScanFrequencyIsLessThanOne() { -// try { -// String value = "0"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("sd", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("sd", k); -// assertEquals("Get scan devices frequency must be greater than 1", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DEVICE_SCAN_FREQUENCY is valid value -// */ -// @Test -// public void testSetConfigForDeviceScanFrequencyIsValid() { -// try { -// String value = "40"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("sd", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(Integer.parseInt(value), Configuration.getDeviceScanFrequency()); -// assertTrue(messageMap.size() == 0); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(DEVICE_SCAN_FREQUENCY), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class).invoke("setDeviceScanFrequency", Mockito.eq(Integer.parseInt(value))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when POST_DIAGNOSTICS_FREQ is invalid value -// */ -// @Test -// public void testSetConfigForPostDiagnosticFrequencyIsInValid() { -// try { -// String value = "frequency"; -// initializeConfiguration(); +/* + * ******************************************************************************* + * * Copyright (c) 2018-2024 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.utils.configuration; + +import org.eclipse.iofog.field_agent.FieldAgent; +import org.eclipse.iofog.gps.GpsMode; +import org.eclipse.iofog.gps.GpsWebHandler; +import org.eclipse.iofog.message_bus.MessageBus; +import org.eclipse.iofog.network.IOFogNetworkInterfaceManager; +import org.eclipse.iofog.process_manager.ProcessManager; +import org.eclipse.iofog.resource_consumption_manager.ResourceConsumptionManager; +import org.eclipse.iofog.supervisor.Supervisor; +import org.eclipse.iofog.utils.Constants; +import org.eclipse.iofog.utils.device_info.ArchitectureType; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +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 javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import static org.eclipse.iofog.command_line.CommandLineConfigParam.*; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; +import static org.testng.AssertJUnit.assertFalse; +import static org.testng.AssertJUnit.assertTrue; + +/** + * @author nehanaithani + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class ConfigurationTest { + private MessageBus messageBus; + private FieldAgent fieldAgent; + private ProcessManager processManager; + private String MODULE_NAME; + private String MOCK_DEFAULT_CONFIG_PATH; + private MockedStatic configurationMockedStatic; + private MockedStatic gpsWebHandlerMockedStatic; + private MockedStatic ioFogNetworkInterfaceManagerMockedStatic; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic fieldAgentMockedStatic; + private MockedStatic resourceConsumptionManagerMockedStatic; + private MockedStatic messageBusMockedStatic; + private MockedStatic processManagerMockedStatic; + private MockedStatic transformerFactoryMockedStatic; + private MockedConstruction domSourceMockedConstruction; + private MockedConstruction supervisorMockedConstruction; + private MockedConstruction streamResultMockedConstruction; + + @BeforeEach + public void setUp() throws Exception { + MODULE_NAME = "Configuration"; + MOCK_DEFAULT_CONFIG_PATH = "../packaging/iofog-agent/etc/iofog-agent/config_new.xml"; + configurationMockedStatic = mockStatic(Configuration.class, Mockito.CALLS_REAL_METHODS); + gpsWebHandlerMockedStatic = mockStatic(GpsWebHandler.class); + ioFogNetworkInterfaceManagerMockedStatic = mockStatic(IOFogNetworkInterfaceManager.class); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + fieldAgentMockedStatic = mockStatic(FieldAgent.class); + resourceConsumptionManagerMockedStatic = mockStatic(ResourceConsumptionManager.class); + messageBusMockedStatic = mockStatic(MessageBus.class); + processManagerMockedStatic = mockStatic(ProcessManager.class); + transformerFactoryMockedStatic = mockStatic(TransformerFactory.class); + IOFogNetworkInterfaceManager networkInterfaceManager = mock(IOFogNetworkInterfaceManager.class); + messageBus = mock(MessageBus.class); + fieldAgent = mock(FieldAgent.class); + processManager =mock(ProcessManager.class); + ResourceConsumptionManager resourceConsumptionManager = mock(ResourceConsumptionManager.class); + Supervisor supervisor = mock(Supervisor.class); + TransformerFactory transformerFactory = mock(TransformerFactory.class); + Transformer transformer = mock(Transformer.class); + Mockito.when(TransformerFactory.newInstance()).thenReturn(transformerFactory); + Mockito.when(transformerFactory.newTransformer()).thenReturn(transformer); + doNothing().when(transformer).transform(any(),any()); + Mockito.when(FieldAgent.getInstance()).thenReturn(fieldAgent); + Mockito.when(ResourceConsumptionManager.getInstance()).thenReturn(resourceConsumptionManager); + Mockito.when(MessageBus.getInstance()).thenReturn(messageBus); + Mockito.when(ProcessManager.getInstance()).thenReturn(processManager); + domSourceMockedConstruction = Mockito.mockConstruction(DOMSource.class); + streamResultMockedConstruction = Mockito.mockConstruction(StreamResult.class); + supervisorMockedConstruction = Mockito.mockConstruction(Supervisor.class,(mock, context) -> { + Mockito.doNothing().when(mock).start(); + }); + Mockito.doNothing().when(supervisor).start(); + Mockito.when(GpsWebHandler.getGpsCoordinatesByExternalIp()).thenReturn("32.00,-121.31"); + Mockito.when(GpsWebHandler.getExternalIp()).thenReturn("0.0.0.0"); + Mockito.when(IOFogNetworkInterfaceManager.getInstance()).thenReturn(networkInterfaceManager); + Mockito.doNothing().when(networkInterfaceManager).updateIOFogNetworkInterface(); + } + + @AfterEach + public void tearDown() throws Exception { + configurationMockedStatic.close(); + gpsWebHandlerMockedStatic.close(); + ioFogNetworkInterfaceManagerMockedStatic.close(); + loggingServiceMockedStatic.close(); + fieldAgentMockedStatic.close(); + resourceConsumptionManagerMockedStatic.close(); + messageBusMockedStatic.close(); + processManagerMockedStatic.close(); + domSourceMockedConstruction.close(); + streamResultMockedConstruction.close(); + supervisorMockedConstruction.close(); + transformerFactoryMockedStatic.close(); + MODULE_NAME = null; + } + +// + private void initializeConfiguration() throws Exception { + Field privateCurrentSwitcherState = Configuration.class.getDeclaredField("currentSwitcherState"); + privateCurrentSwitcherState.setAccessible(true); + privateCurrentSwitcherState.set(Configuration.class, Constants.ConfigSwitcherState.DEFAULT); + when(Configuration.getCurrentConfigPath()).thenReturn(MOCK_DEFAULT_CONFIG_PATH); + Configuration.loadConfig(); + } + + /** + * Test Default configurations + */ + @Test + public void testDefaultConfigurationSettings() { + try { + initializeConfiguration(); + assertEquals(60, Configuration.getPingControllerFreqSeconds()); + assertEquals(1, Configuration.getSpeedCalculationFreqMinutes()); + assertEquals("1.23", Configuration.getDockerApiVersion()); + assertEquals(60, Configuration.getSetSystemTimeFreqSeconds()); + assertEquals("/etc/iofog-agent/cert.crt", Configuration.getControllerCert()); + assertEquals("http://localhost:54421/api/v3/",Configuration.getControllerUrl()); + assertEquals("unix:///var/run/docker.sock", Configuration.getDockerUrl()); + assertEquals("/var/lib/iofog-agent/", Configuration.getDiskDirectory()); + assertEquals(10, Configuration.getDiskLimit(), 0); + assertEquals(4096, Configuration.getMemoryLimit(), 0); + assertEquals(80.0, Configuration.getCpuLimit(), 0); + assertEquals(10.0, Configuration.getLogFileCount(), 0); + assertEquals(20.0, Configuration.getAvailableDiskThreshold(), 0); + assertEquals("dynamic", Configuration.getNetworkInterface()); + assertEquals("not found(dynamic)", Configuration.getNetworkInterfaceInfo()); + assertEquals(10.0, Configuration.getLogDiskLimit(), 0); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getter and setters + */ + @Test + public void testGettersAndSetters() { + try { + initializeConfiguration(); + assertFalse( Configuration.isWatchdogEnabled()); + Configuration.setWatchdogEnabled(true); + assertTrue( Configuration.isWatchdogEnabled()); + assertEquals(30, Configuration.getStatusFrequency()); + Configuration.setStatusFrequency(60); + assertEquals(60, Configuration.getStatusFrequency()); + assertEquals( 60, Configuration.getChangeFrequency()); + Configuration.setChangeFrequency(30); + assertEquals(30, Configuration.getChangeFrequency()); + assertEquals(60, Configuration.getDeviceScanFrequency()); + Configuration.setDeviceScanFrequency(30); + assertEquals(30, Configuration.getDeviceScanFrequency()); + assertNotNull(Configuration.getGpsCoordinates()); + Configuration.setGpsCoordinates("-37.6878,170.100"); + assertEquals("-37.6878,170.100", Configuration.getGpsCoordinates()); + assertEquals(GpsMode.AUTO, Configuration.getGpsMode()); + Configuration.setGpsMode(GpsMode.DYNAMIC); + assertEquals(GpsMode.DYNAMIC, Configuration.getGpsMode()); + assertEquals(10, Configuration.getPostDiagnosticsFreq()); + Configuration.setPostDiagnosticsFreq(60); + assertEquals(60, Configuration.getPostDiagnosticsFreq()); + Configuration.setFogType(ArchitectureType.ARM); + assertEquals(ArchitectureType.ARM, Configuration.getFogType()); + assertEquals(false, Configuration.isSecureMode()); + Configuration.setSecureMode(false); + assertEquals( false, Configuration.isSecureMode()); + assertNotNull(Configuration.getIpAddressExternal()); + Configuration.setIpAddressExternal("ipExternal"); + assertEquals( "ipExternal", Configuration.getIpAddressExternal()); + assertEquals("INFO", Configuration.getLogLevel()); + Configuration.setLogLevel("SEVERE"); + assertEquals( "SEVERE", Configuration.getLogLevel()); + assertEquals("/var/log/iofog-agent/", Configuration.getLogDiskDirectory()); + Configuration.setLogDiskDirectory("/var/new-log/"); + assertEquals( "/var/new-log/", Configuration.getLogDiskDirectory()); + assertEquals("", Configuration.getIofogUuid()); + Configuration.setIofogUuid("uuid"); + assertEquals( "uuid", Configuration.getIofogUuid()); + assertEquals("", Configuration.getAccessToken()); + Configuration.setAccessToken("token"); + assertEquals( "token", Configuration.getAccessToken()); + Assertions.assertFalse(Configuration.isDevMode()); + Configuration.setDevMode(true); + Assertions.assertTrue(Configuration.isDevMode()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getOldNodeValuesForParameters + */ + @Test + public void testGetOldNodeValuesForParameters() { + try { + initializeConfiguration(); + Set config = new HashSet<>(); + config.add("ll"); + HashMap oldValuesMap = Configuration.getOldNodeValuesForParameters(config, Configuration.getCurrentConfig()); + for (HashMap.Entry element : oldValuesMap.entrySet()) { + assertEquals( Configuration.getLogLevel(), element.getValue()); + } + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test saveConfigUpdates + */ + @Test + public void testSaveConfigUpdates() { + try { + initializeConfiguration(); + Configuration.saveConfigUpdates(); + Mockito.verify(processManager, Mockito.atLeastOnce()).instanceConfigUpdated(); + Mockito.verify(fieldAgent, Mockito.atLeastOnce()).instanceConfigUpdated(); + Mockito.verify(messageBus, Mockito.atLeastOnce()).instanceConfigUpdated(); + Mockito.verify(processManager, Mockito.atLeastOnce()).instanceConfigUpdated(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test reset + * + */ + @Test + public void testResetToDefault() { + try { + initializeConfiguration(); + Configuration.setWatchdogEnabled(true); + assertTrue( Configuration.isWatchdogEnabled()); + Configuration.setStatusFrequency(60); + assertEquals(60, Configuration.getStatusFrequency()); + Configuration.setChangeFrequency(30); + assertEquals(30, Configuration.getChangeFrequency()); + Configuration.setDeviceScanFrequency(30); + assertEquals(30, Configuration.getDeviceScanFrequency()); + assertNotNull(Configuration.getGpsCoordinates()); + Configuration.setGpsCoordinates("-37.6878,170.100"); + assertEquals("-37.6878,170.100", Configuration.getGpsCoordinates()); + Configuration.setGpsMode(GpsMode.DYNAMIC); + assertEquals(GpsMode.DYNAMIC, Configuration.getGpsMode()); + Configuration.setPostDiagnosticsFreq(60); + assertEquals(60, Configuration.getPostDiagnosticsFreq()); + Configuration.setFogType(ArchitectureType.ARM); + assertEquals(ArchitectureType.ARM, Configuration.getFogType()); + Configuration.setSecureMode(false); + Assertions.assertFalse(Configuration.isSecureMode()); + Configuration.setIpAddressExternal("ipExternal"); + assertEquals("ipExternal", Configuration.getIpAddressExternal()); + Configuration.setLogLevel("SEVERE"); + assertEquals("SEVERE", Configuration.getLogLevel()); + Configuration.setDevMode(true); + Assertions.assertTrue(Configuration.isDevMode()); + Configuration.resetToDefault(); + assertFalse( Configuration.isWatchdogEnabled()); + assertEquals(10, Configuration.getStatusFrequency()); + assertEquals(20, Configuration.getChangeFrequency()); + assertEquals(60, Configuration.getDeviceScanFrequency()); + assertEquals(GpsMode.AUTO, Configuration.getGpsMode()); + assertEquals(10, Configuration.getPostDiagnosticsFreq()); + Assertions.assertFalse(Configuration.isSecureMode()); + Assertions.assertFalse(Configuration.isDevMode()); + assertNotNull(Configuration.getIpAddressExternal()); + assertEquals("INFO", Configuration.getLogLevel()); + } catch(Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setGpsDataIfValid + */ + @Test + public void testSetGpsDataIfValid() { + try { + Configuration.setGpsDataIfValid(GpsMode.OFF, "-7.6878,00.100"); + assertEquals(GpsMode.OFF, Configuration.getGpsMode()); + assertEquals("-7.6878,00.100", Configuration.getGpsCoordinates()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test writeGpsToConfigFile + */ + @Test + public void testWriteGpsToConfigFile() { + try { + initializeConfiguration(); + Configuration.writeGpsToConfigFile(); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logDebug("Configuration", "Finished writing GPS coordinates and GPS mode to config file"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test loadConfig + */ + @Test + public void testLoadConfig() { + try { + Field privateCurrentSwitcherState = Configuration.class.getDeclaredField("currentSwitcherState"); + privateCurrentSwitcherState.setAccessible(true); + privateCurrentSwitcherState.set(Configuration.class, Constants.ConfigSwitcherState.DEFAULT); + Configuration.loadConfig(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test loadConfigSwitcher + */ + @Test + public void testLoadConfigSwitcher() { + try { + Configuration.loadConfigSwitcher(); + Mockito.verify(LoggingService.class); + LoggingService.logInfo(MODULE_NAME, "Start loads configuration about current config from config-switcher.xml"); + Mockito.verify(LoggingService.class); + LoggingService.logInfo(MODULE_NAME, "Finished loading configuration about current config from config-switcher.xml"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getConfigReport + */ + @Test + public void testGetConfigReport() { + try { + initializeConfiguration(); + String report = Configuration.getConfigReport(); + assertTrue(report.contains("Iofog UUID")); + assertTrue(report.contains("Network Interface")); + assertTrue(report.contains("Docker URL")); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getCurrentConfig + */ + @Test + public void tetGetCurrentConfig() { + try { + initializeConfiguration(); + assertNotNull(Configuration.getCurrentConfig()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getCurrentConfigPath + */ + @Test + public void testGetCurrentConfigPath() { + try { + initializeConfiguration(); + assertEquals(MOCK_DEFAULT_CONFIG_PATH, Configuration.getCurrentConfigPath()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setupConfigSwitcher when currentSwitcherState is same as previousState + */ + @Test + public void testSetupConfigSwitcherAsDefault() { + try { + initializeConfiguration(); + assertEquals("Already using this configuration.", Configuration.setupConfigSwitcher(Constants.ConfigSwitcherState.DEFAULT)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test load + */ + @Test + public void testLoad() { + try { + Configuration.load(); + Mockito.verify(Configuration.class); + Configuration.loadConfigSwitcher(); + Mockito.verify(Configuration.class); + Configuration.loadConfig(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setupSupervisor + */ + @Test + public void testSetupSupervisor() { + try { + Configuration.setupSupervisor(); + assertEquals(1, supervisorMockedConstruction.constructed().size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setupSupervisor + */ + @Test + public void testSupervisorThrowsExceptionOnSetupSupervisor() { + try { + supervisorMockedConstruction.close(); + supervisorMockedConstruction = Mockito.mockConstructionWithAnswer(Supervisor.class, invocation -> { + throw new Exception(); + }); + Configuration.setupSupervisor(); + assertEquals(1, supervisorMockedConstruction.constructed().size()); + Mockito.verify(LoggingService.class); + LoggingService.logError(Mockito.eq("Configuration"), Mockito.eq("Error while starting supervisor"), Mockito.any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when config is blank + */ + @Test + public void testSetConfigWhenConfigIsBlank() { + try { + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("d", " "); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("Parameter error", k); + assertEquals("Command or value is invalid", v); + }); + Mockito.verify(LoggingService.class, never()); + LoggingService.instanceConfigUpdated(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when config is null + */ + @Test + public void testSetConfigWhenConfigIsNull() { + try { + HashMap messageMap = Configuration.setConfig(null, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("invalid", k); + assertEquals("Option and value are null", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DISK_CONSUMPTION_LIMIT is invalid which is string instead of float + */ + @Test + public void testSetConfigForDiskConsumptionLimitIsNotValid() { + try { + Map config = new HashMap<>(); + config.put("d", "disk"); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("d", k); + assertEquals("Option -d has invalid value: disk", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DISK_CONSUMPTION_LIMIT is invalid + * Disk limit range is not between 1 to 1048576 GB + */ + @Test + public void testSetConfigForDiskConsumptionLimitIsNotWithInRange() { + try { + Map config = new HashMap<>(); + config.put("d", "10485769"); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("d", k); + assertEquals("Disk limit range must be 1 to 1048576 GB", v); + }); + Mockito.verify(LoggingService.class, never()); + LoggingService.instanceConfigUpdated(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DISK_CONSUMPTION_LIMIT is invalid + * Disk limit range is between 1 to 1048576 GB + */ + @Test + public void testSetConfigForDiskConsumptionLimitIsValid() { + try { + initializeConfiguration(); + String value = "30"; + Map config = new HashMap<>(); + config.put("d", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(30, Configuration.getDiskLimit(), 0); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DISK_DIRECTORY with valid string + */ + @Test + public void testSetConfigForDiskDirectory() { + try { + String value = "dir"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("dl", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals("/dir/", Configuration.getDiskDirectory()); + assertEquals(0, messageMap.size()); + Mockito.verify(LoggingService.class, never()); + LoggingService.instanceConfigUpdated(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when MEMORY_CONSUMPTION_LIMIT with valid string + */ + @Test + public void testSetConfigForMemoryConsumptionLimitWhichIsInvalid() { + try { + String value = "dir"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("m", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("m", k); + assertEquals("Option -m has invalid value: dir", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when MEMORY_CONSUMPTION_LIMIT with invalid range + */ + @Test + public void testSetConfigForMemoryConsumptionLimitIsInValidRange() { + try { + String value = "127"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("m", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("m", k); + assertEquals("Memory limit range must be 128 to 1048576 MB", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when MEMORY_CONSUMPTION_LIMIT with valid string + */ + @Test + public void testSetConfigForMemoryConsumptionLimitIsValidRange() { + try { + String value = "5000"; + initializeConfiguration(); // suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("df", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("df", k); -// assertEquals("Option -df has invalid value: frequency", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when POST_DIAGNOSTICS_FREQ is less than 1 -// */ -// @Test -// public void testSetConfigForPostDiagnosticFrequencyIsLessThanOne() { -// try { -// String value = "0"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("df", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("df", k); -// assertEquals("Post diagnostics frequency must be greater than 1", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when POST_DIAGNOSTICS_FREQ is valid value -// */ -// @Test -// public void testSetConfigForPostDiagnosticFrequencyIsValid() { -// try { -// String value = "40"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("df", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(Integer.parseInt(value), Configuration.getPostDiagnosticsFreq()); -// assertTrue(messageMap.size() == 0); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(POST_DIAGNOSTICS_FREQ), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class).invoke("setPostDiagnosticsFreq", Mockito.eq(Integer.parseInt(value))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// -// /** -// * Test setConfig when WATCHDOG_ENABLED with invalid value -// */ -// @Test -// public void testSetConfigForWatchdogEnabledWithInValidValue() { -// try { -// String value = "watchDog"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("idc", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("idc", k); -// assertEquals("Option -idc has invalid value: watchDog", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when WATCHDOG_ENABLED with invalid value -// */ -// @Test -// public void testSetConfigForWatchdogEnabledWithInValidValueAsInteger() { -// try { -// int value = 10; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("idc", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("idc", k); -// assertEquals("Option -idc has invalid value: 10", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when WATCHDOG_ENABLED with valid value -// */ -// @Test -// public void testSetConfigForWatchdogEnabledWithValidValue() { -// try { -// String value = "on"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("idc", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// assertTrue(Configuration.isWatchdogEnabled()); -// Mockito.verifyPrivate(Configuration.class).invoke("setNode", Mockito.eq(WATCHDOG_ENABLED), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class).invoke("setWatchdogEnabled", Mockito.eq(!value.equals("off"))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when GPS_MODE with invalid value -// */ -// @Test -// public void testSetConfigForGPSModeWithInValidValue() { -// try { -// String value = "on"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("gps", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("gps", k); -// assertEquals("Option -gps has invalid value: on", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when GPS_MODE with valid value -// */ -// @Test -// public void testSetConfigForGPSModeWithValidValue() { -// try { -// String value = "off"; -// suppress(method(Configuration.class, "saveConfigUpdates")); -// initializeConfiguration(); -// Map config = new HashMap<>(); -// config.put(GPS_MODE.getCommandName(), value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(GpsMode.OFF, Configuration.getGpsMode()); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("writeGpsToConfigFile"); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("configureGps", Mockito.eq(value), Mockito.anyString()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when GPS_Coordinate is set with valid coordinates and gps_mode is switched to manual -// */ -// @Test -// public void testSetConfigForGPSModeWithValidCoordinates() { -// try { -// String value = "0,0"; -// suppress(method(Configuration.class, "saveConfigUpdates")); -// initializeConfiguration(); -// Map config = new HashMap<>(); -// config.put(GPS_MODE.getCommandName(), value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(GpsMode.MANUAL, Configuration.getGpsMode()); -// assertEquals(value, Configuration.getGpsCoordinates()); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("writeGpsToConfigFile"); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("configureGps", Mockito.eq(value), Mockito.anyString()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("isValidCoordinates", Mockito.eq("0,0")); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when GPS_Coordinate is set with invalid coordinates and gps_mode is switched to manual -// */ -// @Test -// public void testSetConfigForGPSModeWithInValidCoordinates() { -// try { -// String value = "I am invalid coordinates"; -// suppress(method(Configuration.class, "saveConfigUpdates")); -// initializeConfiguration(); -// Map config = new HashMap<>(); -// config.put(GPS_MODE.getCommandName(), value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("gps", k); -// assertEquals("Option -gps has invalid value: I am invalid coordinates", v); -// }); -// assertNotEquals(value, Configuration.getGpsCoordinates()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("writeGpsToConfigFile"); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("configureGps", Mockito.eq(value), Mockito.anyString()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when FOG_TYPE with invalid value -// */ -// @Test -// public void testSetConfigForFogTypeWithInValidValue() { -// try { -// String value = "value"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("ft", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(1, messageMap.size()); -// messageMap.forEach((k, v) -> { -// assertEquals("ft", k); -// assertEquals("Option -ft has invalid value: value", v); -// }); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when FOG_TYPE with valid value -// */ -// @Test -// public void testSetConfigForFogTypeWithValidValue() { -// try { -// String value = "auto"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("ft", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setNode", Mockito.eq(FOG_TYPE), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("configureFogType", Mockito.eq(value)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DEV_MODE with invalid value -// */ -// @Test -// public void testSetConfigForSecureModeWithInValidValue() { -// try { -// String value = "1020"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("sec", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setNode", Mockito.eq(SECURE_MODE), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setSecureMode", Mockito.eq(!value.equals("off"))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DEV_MODE with valid value -// */ -// @Test -// public void testSetConfigForSecureModeWithValidValue() { -// try { -// String value = "off"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("sec", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setNode", Mockito.eq(SECURE_MODE), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setSecureMode", Mockito.eq(!value.equals("off"))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test setConfig when DEV_MODE with invalid value -// */ -// @Test -// public void testSetConfigForDevModeWithInValidValue() { -// try { -// String value = "1020"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("dev", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setNode", Mockito.eq(DEV_MODE), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setDevMode", Mockito.eq(!value.equals("off"))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test setConfig when DEV_MODE with valid value -// */ -// @Test -// public void testSetConfigForDevModeWithValidValue() { -// try { -// String value = "off"; -// initializeConfiguration(); -// suppress(method(Configuration.class, "saveConfigUpdates")); -// Map config = new HashMap<>(); -// config.put("dev", value); -// HashMap messageMap = Configuration.setConfig(config, false); -// assertEquals(0, messageMap.size()); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setNode", Mockito.eq(DEV_MODE), Mockito.eq(value), -// Mockito.any(Document.class), Mockito.any(Element.class)); -// Mockito.verifyPrivate(Configuration.class, Mockito.atLeastOnce()).invoke("setDevMode", Mockito.eq(!value.equals("off"))); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -//} \ No newline at end of file + Map config = new HashMap<>(); + config.put("m", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when PROCESSOR_CONSUMPTION_LIMIT with invalid string + */ + @Test + public void testSetConfigForProcessorConsumptionLimitWithInValidValue() { + try { + String value = "limit"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("p", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("p", k); + assertEquals("Option -p has invalid value: limit", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when PROCESSOR_CONSUMPTION_LIMIT with invalid range + */ + @Test + public void testSetConfigForProcessorConsumptionLimitWithInValidRange() { + try { + String value = "200"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("p", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("p", k); + assertEquals("CPU limit range must be 5% to 100%", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when PROCESSOR_CONSUMPTION_LIMIT with valid range + */ + @Test + public void testSetConfigForProcessorConsumptionLimitWithValidRange() { + try { + String value = "50"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("p", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when CONTROLLER_URL with valid value + */ + @Test + public void testSetConfigForControllerUrlWithInvalidValue() { + try { + String value = "certificate"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("a", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + assertEquals(value+"/", Configuration.getControllerUrl()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when CONTROLLER_CERT with valid value + */ + @Test + public void testSetConfigForControllerCertWithInvalidValue() { + try { + String value = "http://controllerCert"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("ac", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + assertEquals(value, Configuration.getControllerCert()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DOCKER_URL with invalid value + */ + @Test + public void testSetConfigForDockerUrlWithInvalidValue() { + try { + String value = "http://localhost/dockerUrl"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("c", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("c", k); + assertEquals("Unsupported protocol scheme. Only 'tcp://' or 'unix://' supported.\n", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DOCKER_URL with valid value + */ + @Test + public void testSetConfigForDockerUrlWithValidValue() { + try { + String value = "tcp://localhost/dockerUrl"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("c", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + assertEquals(value, Configuration.getDockerUrl()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when NETWORK_INTERFACE with valid value + */ + @Test + public void testSetConfigForNetworkInterfaceWithValidValue() { + try { + String value = "http://networkUrl"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("n", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + assertEquals(value, Configuration.getNetworkInterface()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when LOG_DISK_CONSUMPTION_LIMIT with invalid value + */ + @Test + public void testSetConfigForLogDiskConsumptionLimitWithInValidValue() { + try { + String value = "logLimit"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("l", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("l", k); + assertEquals("Option -l has invalid value: logLimit", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when LOG_DISK_CONSUMPTION_LIMIT with invalid range + */ + @Test + public void testSetConfigForLogDiskConsumptionLimitWithInValidRange() { + try { + String value = "110"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("l", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("l", k); + assertEquals("Log disk limit range must be 0.5 to 100 GB", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when LOG_DISK_CONSUMPTION_LIMIT with valid value + */ + @Test + public void testSetConfigForLogDiskConsumptionLimitWithValidValue() { + try { + String value = "1"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("l", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + assertEquals(Float.parseFloat(value), Configuration.getLogDiskLimit(), 0); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when LOG_DISK_DIRECTORY with valid value + */ + @Test + public void testSetConfigForLogDiskDirectoryWithValidValue() { + try { + String value = "dir"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("ld", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + assertEquals("/"+value+"/", Configuration.getLogDiskDirectory()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when LOG_FILE_COUNT with invalid value + */ + @Test + public void testSetConfigForLogFileCountWithInValidValue() { + try { + String value = "count"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("lc", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("lc", k); + assertEquals("Option -lc has invalid value: count", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test setConfig when LOG_FILE_COUNT with invalid range + */ + @Test + public void testSetConfigForLogFileCountWithInValidRange() { + try { + String value = "120"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("lc", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("lc", k); + assertEquals("Log file count range must be 1 to 100", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when LOG_FILE_COUNT with valid value + */ + @Test + public void testSetConfigForLogFileCountWithValidValue() { + try { + String value = "20"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("lc", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + assertEquals(Integer.parseInt(value), Configuration.getLogFileCount()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test when setConfig of invalid log level is called + */ + @Test + public void testSetConfigForLogLevelIsNotValid() { + try { + String value = "terrific"; + Map config = new HashMap<>(); + config.put("ll", "terrific"); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("ll", k); + assertEquals("Option -ll has invalid value: terrific", v); + }); + Mockito.verify(LoggingService.class, never()); + LoggingService.instanceConfigUpdated(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test when setConfig of valid log level is called + */ + @Test + public void testSetConfigForLogLevelIsValid() { + try { + String value = "severe"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("ll", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(value.toUpperCase(), Configuration.getLogLevel()); + assertEquals(0, messageMap.size()); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.instanceConfigUpdated(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when STATUS_FREQUENCY is invalid value + */ + @Test + public void testSetConfigForStatusFrequencyIsInValid() { + try { + String value = "frequency"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("sf", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("sf", k); + assertEquals("Option -sf has invalid value: frequency", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when STATUS_FREQUENCY is less than 1 + */ + @Test + public void testSetConfigForStatusFrequencyIsLessThanOne() { + try { + String value = "0"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("sf", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("sf", k); + assertEquals("Status update frequency must be greater than 1", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when STATUS_FREQUENCY is valid value + */ + @Test + public void testSetConfigForStatusFrequencyIsValid() { + try { + String value = "40"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("sf", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(Integer.parseInt(value), Configuration.getStatusFrequency()); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + + /** + * Test setConfig when CHANGE_FREQUENCY is invalid value + */ + @Test + public void testSetConfigForChangeFrequencyIsInValid() { + try { + String value = "frequency"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("cf", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("cf", k); + assertEquals("Option -cf has invalid value: frequency", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when CHANGE_FREQUENCY is less than 1 + */ + @Test + public void testSetConfigForChangerequencyIsLessThanOne() { + try { + String value = "0"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("cf", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("cf", k); + assertEquals("Get changes frequency must be greater than 1", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when CHANGE_FREQUENCY is valid value + */ + @Test + public void testSetConfigForChangeFrequencyIsValid() { + try { + String value = "40"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("cf", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(Integer.parseInt(value), Configuration.getChangeFrequency()); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DEVICE_SCAN_FREQUENCY is invalid value + */ + @Test + public void testSetConfigForDeviceScanFrequencyIsInValid() { + try { + String value = "frequency"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("sd", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("sd", k); + assertEquals("Option -sd has invalid value: frequency", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DEVICE_SCAN_FREQUENCY is less than 1 + */ + @Test + public void testSetConfigForDeviceScanFrequencyIsLessThanOne() { + try { + String value = "0"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("sd", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("sd", k); + assertEquals("Get scan devices frequency must be greater than 1", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DEVICE_SCAN_FREQUENCY is valid value + */ + @Test + public void testSetConfigForDeviceScanFrequencyIsValid() { + try { + String value = "40"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("sd", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(Integer.parseInt(value), Configuration.getDeviceScanFrequency()); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when POST_DIAGNOSTICS_FREQ is invalid value + */ + @Test + public void testSetConfigForPostDiagnosticFrequencyIsInValid() { + try { + String value = "frequency"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("df", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("df", k); + assertEquals("Option -df has invalid value: frequency", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when POST_DIAGNOSTICS_FREQ is less than 1 + */ + @Test + public void testSetConfigForPostDiagnosticFrequencyIsLessThanOne() { + try { + String value = "0"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("df", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("df", k); + assertEquals("Post diagnostics frequency must be greater than 1", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when POST_DIAGNOSTICS_FREQ is valid value + */ + @Test + public void testSetConfigForPostDiagnosticFrequencyIsValid() { + try { + String value = "40"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("df", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(Integer.parseInt(value), Configuration.getPostDiagnosticsFreq()); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + + /** + * Test setConfig when WATCHDOG_ENABLED with invalid value + */ + @Test + public void testSetConfigForWatchdogEnabledWithInValidValue() { + try { + String value = "watchDog"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("idc", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("idc", k); + assertEquals("Option -idc has invalid value: watchDog", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when WATCHDOG_ENABLED with invalid value + */ + @Test + public void testSetConfigForWatchdogEnabledWithInValidValueAsInteger() { + try { + int value = 10; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("idc", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("idc", k); + assertEquals("Option -idc has invalid value: 10", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when WATCHDOG_ENABLED with valid value + */ + @Test + public void testSetConfigForWatchdogEnabledWithValidValue() { + try { + String value = "on"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("idc", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + assertTrue(Configuration.isWatchdogEnabled()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when GPS_MODE with invalid value + */ + @Test + public void testSetConfigForGPSModeWithInValidValue() { + try { + String value = "on"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("gps", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("gps", k); + assertEquals("Option -gps has invalid value: on", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when GPS_MODE with valid value + */ + @Test + public void testSetConfigForGPSModeWithValidValue() { + try { + String value = "off"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put(GPS_MODE.getCommandName(), value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(GpsMode.OFF, Configuration.getGpsMode()); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when GPS_Coordinate is set with valid coordinates and gps_mode is switched to manual + */ + @Test + public void testSetConfigForGPSModeWithValidCoordinates() { + try { + String value = "0,0"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put(GPS_MODE.getCommandName(), value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(GpsMode.MANUAL, Configuration.getGpsMode()); + assertEquals(value, Configuration.getGpsCoordinates()); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when GPS_Coordinate is set with invalid coordinates and gps_mode is switched to manual + */ + @Test + public void testSetConfigForGPSModeWithInValidCoordinates() { + try { + String value = "I am invalid coordinates"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put(GPS_MODE.getCommandName(), value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("gps", k); + assertEquals("Option -gps has invalid value: I am invalid coordinates", v); + }); + assertNotEquals(value, Configuration.getGpsCoordinates()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when FOG_TYPE with invalid value + */ + @Test + public void testSetConfigForFogTypeWithInValidValue() { + try { + String value = "value"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("ft", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(1, messageMap.size()); + messageMap.forEach((k, v) -> { + assertEquals("ft", k); + assertEquals("Option -ft has invalid value: value", v); + }); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when FOG_TYPE with valid value + */ + @Test + public void testSetConfigForFogTypeWithValidValue() { + try { + String value = "auto"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("ft", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DEV_MODE with invalid value + */ + @Test + public void testSetConfigForSecureModeWithInValidValue() { + try { + String value = "1020"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("sec", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DEV_MODE with valid value + */ + @Test + public void testSetConfigForSecureModeWithValidValue() { + try { + String value = "off"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("sec", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test setConfig when DEV_MODE with invalid value + */ + @Test + public void testSetConfigForDevModeWithInValidValue() { + try { + String value = "1020"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("dev", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test setConfig when DEV_MODE with valid value + */ + @Test + public void testSetConfigForDevModeWithValidValue() { + try { + String value = "off"; + initializeConfiguration(); + Map config = new HashMap<>(); + config.put("dev", value); + HashMap messageMap = Configuration.setConfig(config, false); + assertEquals(0, messageMap.size()); + } catch (Exception e) { + fail("This should not happen"); + } + } + +} \ No newline at end of file diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/device_info/ArchitectureTypeTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/device_info/ArchitectureTypeTest.java index 7cbaa79e..814a9e70 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/device_info/ArchitectureTypeTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/device_info/ArchitectureTypeTest.java @@ -1,57 +1,59 @@ -///* -// * ******************************************************************************* -// * * 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.utils.device_info; -// -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static org.junit.Assert.*; -// -///** -// * @author nehanaithani -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({ArchitectureType.class}) -//public class ArchitectureTypeTest { -// -// /** -// * Test getCode -// */ -// @Test -// public void testGetCode() { -// assertEquals(2, ArchitectureType.ARM.getCode()); -// assertEquals(1, ArchitectureType.INTEL_AMD.getCode()); -// assertEquals(0, ArchitectureType.UNDEFINED.getCode()); -// } -// -// /** -// * Test getArchTypeByArchName -// */ -// @Test -// public void testGetArchTypeByArchName() { -// assertEquals(ArchitectureType.ARM, ArchitectureType.getArchTypeByArchName("arm")); -// assertEquals(ArchitectureType.INTEL_AMD, ArchitectureType.getArchTypeByArchName("x32")); -// assertEquals(ArchitectureType.UNDEFINED, ArchitectureType.getArchTypeByArchName("")); -// -// } -// -// /** -// * Test getDeviceArchType -// */ -// @Test -// public void testGetDeviceArchType() { -// assertEquals(ArchitectureType.INTEL_AMD, ArchitectureType.getDeviceArchType()); -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2024 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.utils.device_info; + + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * @author nehanaithani + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class ArchitectureTypeTest { + + /** + * Test getCode + */ + @Test + public void testGetCode() { + assertEquals(2, ArchitectureType.ARM.getCode()); + assertEquals(1, ArchitectureType.INTEL_AMD.getCode()); + assertEquals(0, ArchitectureType.UNDEFINED.getCode()); + } + + /** + * Test getArchTypeByArchName + */ + @Test + public void testGetArchTypeByArchName() { + assertEquals(ArchitectureType.ARM, ArchitectureType.getArchTypeByArchName("arm")); + assertEquals(ArchitectureType.INTEL_AMD, ArchitectureType.getArchTypeByArchName("x32")); + assertEquals(ArchitectureType.UNDEFINED, ArchitectureType.getArchTypeByArchName("")); + + } + + /** + * Test getDeviceArchType + */ + @Test + public void testGetDeviceArchType() { + assertEquals(ArchitectureType.ARM, ArchitectureType.getDeviceArchType()); + } +} \ No newline at end of file diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/logging/LogFormatterTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/logging/LogFormatterTest.java index 8187b727..6ee31d92 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/logging/LogFormatterTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/logging/LogFormatterTest.java @@ -1,6 +1,6 @@ ///* // * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. +// * * Copyright (c) 2018-2024 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 diff --git a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/logging/LoggingServiceTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/logging/LoggingServiceTest.java index 4319216f..3d4acabd 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/logging/LoggingServiceTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/utils/logging/LoggingServiceTest.java @@ -1,6 +1,6 @@ ///* // * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. +// * * Copyright (c) 2018-2024 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