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 b4170a39..1bbf6ffb 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,180 +1,199 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.field_agent; -// -//import org.eclipse.iofog.command_line.util.CommandShellExecutor; -//import org.eclipse.iofog.command_line.util.CommandShellResultSet; -//import org.eclipse.iofog.edge_resources.EdgeResourceManager; -//import org.eclipse.iofog.exception.AgentSystemException; -//import org.eclipse.iofog.exception.AgentUserException; -//import org.eclipse.iofog.field_agent.enums.RequestType; -//import org.eclipse.iofog.local_api.LocalApi; -//import org.eclipse.iofog.message_bus.MessageBus; -//import org.eclipse.iofog.message_bus.MessageBusStatus; -//import org.eclipse.iofog.microservice.MicroserviceManager; -//import org.eclipse.iofog.network.IOFogNetworkInterfaceManager; -//import org.eclipse.iofog.process_manager.ProcessManager; -//import org.eclipse.iofog.process_manager.ProcessManagerStatus; -//import org.eclipse.iofog.proxy.SshConnection; -//import org.eclipse.iofog.proxy.SshProxyManager; -//import org.eclipse.iofog.proxy.SshProxyManagerStatus; -//import org.eclipse.iofog.resource_consumption_manager.ResourceConsumptionManagerStatus; -//import org.eclipse.iofog.resource_manager.ResourceManagerStatus; -//import org.eclipse.iofog.status_reporter.StatusReporter; -//import org.eclipse.iofog.status_reporter.StatusReporterStatus; -//import org.eclipse.iofog.supervisor.SupervisorStatus; -//import org.eclipse.iofog.utils.Constants; -//import org.eclipse.iofog.utils.Orchestrator; -//import org.eclipse.iofog.utils.configuration.Configuration; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.jupiter.api.AfterEach; -//import org.junit.jupiter.api.BeforeEach; -//import org.junit.jupiter.api.Test; -//import org.junit.jupiter.api.extension.ExtendWith; -//import org.mockito.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.JsonArray; -//import javax.json.JsonObject; -//import javax.json.JsonObjectBuilder; -//import javax.net.ssl.SSLHandshakeException; -//import java.io.BufferedReader; -//import java.io.InputStream; -//import java.io.InputStreamReader; -//import java.lang.reflect.Field; -//import java.lang.reflect.Method; -//import java.net.HttpURLConnection; -//import java.net.URL; -//import java.nio.charset.Charset; -//import java.security.cert.CertificateException; -//import java.util.ArrayList; -//import java.util.List; -//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 -// */ -//@ExtendWith(MockitoExtension.class) -//@MockitoSettings(strictness = Strictness.LENIENT) -//public class FieldAgentTest { -// private FieldAgent fieldAgent; -// private String MODULE_NAME; -// private Orchestrator orchestrator = null; -// private JsonObject jsonObject; -// private JsonObject provisionJsonObject; -// private JsonObjectBuilder jsonObjectBuilder = null; -// 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; -// private MockedStatic processManagerMockedStatic; -// private MockedStatic orchestratorMockedStatic; -// private MockedStatic messageBusMockedStatic; -// private MockedStatic localApiMockedStatic; -// private MockedStatic versionHandlerMockedStatic; -// private MockedStatic commandShellExecutorMockedStatic; -// private MockedStatic ioFogNetworkInterfaceManagerMockedStatic; -// private MockedStatic bufferedReaderMockedStatic; -// private MockedStatic inputStreamReaderMockedStatic; -// private MockedStatic edgeResourceManagerMockedStatic; -// -// @BeforeEach -// public void setUp() throws Exception { -// loggingServiceMockedStatic = mockStatic(LoggingService.class); -// statusReporterMockedStatic = mockStatic(StatusReporter.class); -// configurationMockedStatic = mockStatic(Configuration.class); -// processManagerMockedStatic = mockStatic(ProcessManager.class); -// orchestratorMockedStatic = mockStatic(Orchestrator.class); -// messageBusMockedStatic = mockStatic(MessageBus.class); -// localApiMockedStatic = mockStatic(LocalApi.class); -// versionHandlerMockedStatic = mockStatic(VersionHandler.class); -// commandShellExecutorMockedStatic = mockStatic(CommandShellExecutor.class); -// ioFogNetworkInterfaceManagerMockedStatic = mockStatic(IOFogNetworkInterfaceManager.class); -// 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); -// mockConfiguration(); -// mockOthers(); -// fieldAgent = Mockito.spy(FieldAgent.getInstance()); -// fieldAgentStatus = Mockito.mock(FieldAgentStatus.class); -// ioFogNetworkInterfaceManager = Mockito.mock(IOFogNetworkInterfaceManager.class); -// setMock(fieldAgent); -// 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); -// mockStatic(MicroserviceManager.class); -//// Mockito.whenNew(Orchestrator.class).withNoArguments().thenReturn(orchestrator); -//// Mockito.whenNew(SshProxyManager.class).withArguments(Mockito.any(SshConnection.class)).thenReturn(sshProxyManager); -// 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(); -// when(orchestrator.request(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Mockito.mock(JsonObject.class)); +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.field_agent; + +import org.eclipse.iofog.command_line.util.CommandShellExecutor; +import org.eclipse.iofog.command_line.util.CommandShellResultSet; +import org.eclipse.iofog.edge_resources.EdgeResourceManager; +import org.eclipse.iofog.exception.AgentSystemException; +import org.eclipse.iofog.exception.AgentUserException; +import org.eclipse.iofog.field_agent.enums.RequestType; +import org.eclipse.iofog.local_api.LocalApi; +import org.eclipse.iofog.message_bus.MessageBus; +import org.eclipse.iofog.message_bus.MessageBusStatus; +import org.eclipse.iofog.microservice.MicroserviceManager; +import org.eclipse.iofog.network.IOFogNetworkInterfaceManager; +import org.eclipse.iofog.process_manager.ProcessManager; +import org.eclipse.iofog.process_manager.ProcessManagerStatus; +import org.eclipse.iofog.proxy.SshConnection; +import org.eclipse.iofog.proxy.SshProxyManager; +import org.eclipse.iofog.proxy.SshProxyManagerStatus; +import org.eclipse.iofog.resource_consumption_manager.ResourceConsumptionManagerStatus; +import org.eclipse.iofog.resource_manager.ResourceManagerStatus; +import org.eclipse.iofog.status_reporter.StatusReporter; +import org.eclipse.iofog.status_reporter.StatusReporterStatus; +import org.eclipse.iofog.supervisor.SupervisorStatus; +import org.eclipse.iofog.utils.Constants; +import org.eclipse.iofog.utils.Orchestrator; +import org.eclipse.iofog.utils.configuration.Configuration; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; +import javax.net.ssl.SSLHandshakeException; +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.Charset; +import java.security.cert.CertificateException; +import java.util.ArrayList; +import java.util.List; +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 + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@Disabled +public class FieldAgentTest { + private FieldAgent fieldAgent; + private String MODULE_NAME; + private Orchestrator orchestrator = null; + private JsonObject jsonObject; + private JsonObject provisionJsonObject; + private JsonObjectBuilder jsonObjectBuilder = null; + 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; + private MockedStatic processManagerMockedStatic; + private MockedStatic orchestratorMockedStatic; + private MockedStatic messageBusMockedStatic; + private MockedStatic localApiMockedStatic; + private MockedStatic versionHandlerMockedStatic; + private MockedStatic commandShellExecutorMockedStatic; + private MockedStatic ioFogNetworkInterfaceManagerMockedStatic; + private MockedStatic bufferedReaderMockedStatic; + private MockedStatic inputStreamReaderMockedStatic; + private MockedStatic edgeResourceManagerMockedStatic; + private MockedStatic microserviceManagerMockedStatic; + private MockedConstruction orchestratorMockedConstruction; + private MockedConstruction sshProxyManagerMockedConstruction; + private MockedConstruction urlMockedConstruction; + private MockedConstruction inputStreamReaderMockedConstruction; + private MockedConstruction bufferedReaderMockedConstruction; + + @BeforeEach + public void setUp() throws Exception { + loggingServiceMockedStatic = mockStatic(LoggingService.class); + statusReporterMockedStatic = mockStatic(StatusReporter.class); + configurationMockedStatic = mockStatic(Configuration.class); + processManagerMockedStatic = mockStatic(ProcessManager.class); + orchestratorMockedStatic = mockStatic(Orchestrator.class); + messageBusMockedStatic = mockStatic(MessageBus.class); + localApiMockedStatic = mockStatic(LocalApi.class); + versionHandlerMockedStatic = mockStatic(VersionHandler.class); + commandShellExecutorMockedStatic = mockStatic(CommandShellExecutor.class); + ioFogNetworkInterfaceManagerMockedStatic = mockStatic(IOFogNetworkInterfaceManager.class); + 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); + 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); + microserviceManagerMockedStatic = mockStatic(MicroserviceManager.class); + orchestratorMockedConstruction = mockConstruction(Orchestrator.class, (mock, context) -> { + when(mock.request(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(Mockito.mock(JsonObject.class)); + }); + sshProxyManagerMockedConstruction = mockConstruction(SshProxyManager.class); + urlMockedConstruction = mockConstruction(URL.class, (mock, context) -> { + httpURLConnection = Mockito.mock(HttpURLConnection.class); + when(mock.openConnection()).thenReturn(httpURLConnection ); + when(httpURLConnection.getResponseCode()).thenReturn(200); + Mockito.doNothing().when(httpURLConnection).disconnect(); + }); + inputStreamReaderMockedConstruction = mockConstruction(InputStreamReader.class); + bufferedReaderMockedConstruction = mockConstruction(BufferedReader.class, (mock, context) -> { + 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); -// httpURLConnection = Mockito.mock(HttpURLConnection.class); -//// whenNew(URL.class).withArguments(Mockito.any()).thenReturn(url); -// when(url.openConnection()).thenReturn(httpURLConnection ); -// when(httpURLConnection.getResponseCode()).thenReturn(200); -// Mockito.doNothing().when(httpURLConnection).disconnect(); + // bufferedReader = Mockito.mock(BufferedReader.class); // inputStreamReader = Mockito.mock(InputStreamReader.class); -//// 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(bufferedReader.readLine()).thenReturn("Response from HAL").thenReturn(null); -// when(VersionHandler.isReadyToUpgrade()).thenReturn(false); -// when(VersionHandler.isReadyToRollback()).thenReturn(false); + when(VersionHandler.isReadyToUpgrade()).thenReturn(false); + when(VersionHandler.isReadyToRollback()).thenReturn(false); // jsonObjectBuilder = Json.createObjectBuilder(); // jsonObject = jsonObjectBuilder // .add("uuid", "uuid") @@ -184,1542 +203,1563 @@ // .add("uuid", "uuid") // .add("token", "token") // .add("message", "success").build(); -// Mockito.doNothing().when(processManager).updateMicroserviceStatus(); -// -// } -// -// @AfterEach -// public void tearDown() throws Exception { -// loggingServiceMockedStatic.close(); -// statusReporterMockedStatic.close(); -// configurationMockedStatic.close(); -// processManagerMockedStatic.close(); -// orchestratorMockedStatic.close(); -// messageBusMockedStatic.close(); -// localApiMockedStatic.close(); -// versionHandlerMockedStatic.close(); -// commandShellExecutorMockedStatic.close(); -// ioFogNetworkInterfaceManagerMockedStatic.close(); -// bufferedReaderMockedStatic.close(); -// inputStreamReaderMockedStatic.close(); -// edgeResourceManagerMockedStatic.close(); -// Field instance = FieldAgent.class.getDeclaredField("instance"); -// instance.setAccessible(true); -// instance.set(null, null); -// MODULE_NAME = null; -// fieldAgent = null; -// Mockito.reset(fieldAgentStatus, orchestrator, bufferedReader, inputStreamReader); -// 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) { + Mockito.doNothing().when(processManager).updateMicroserviceStatus(); +// setMock(fieldAgent,microserviceManager,orchestrator, sshProxyManager, edgeResourceManager); + + + } + + @AfterEach + public void tearDown() throws Exception { + loggingServiceMockedStatic.close(); + microserviceManagerMockedStatic.close(); + statusReporterMockedStatic.close(); + configurationMockedStatic.close(); + processManagerMockedStatic.close(); + orchestratorMockedStatic.close(); + messageBusMockedStatic.close(); + localApiMockedStatic.close(); + versionHandlerMockedStatic.close(); + commandShellExecutorMockedStatic.close(); + ioFogNetworkInterfaceManagerMockedStatic.close(); + bufferedReaderMockedStatic.close(); + inputStreamReaderMockedStatic.close(); + edgeResourceManagerMockedStatic.close(); + orchestratorMockedConstruction.close(); + inputStreamReaderMockedConstruction.close(); + urlMockedConstruction.close(); + bufferedReaderMockedConstruction.close(); + sshProxyManagerMockedConstruction.close(); + Field instance = FieldAgent.class.getDeclaredField("instance"); + instance.setAccessible(true); + instance.set(null, null); + MODULE_NAME = null; + fieldAgent = null; + Mockito.reset(fieldAgentStatus, orchestrator, inputStreamReader); + 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); -// } catch (Exception e) { -// throw new RuntimeException(e); -// } -// } -// -// public void initiateMockStart() { -// 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) { -// fail("this should not happen"); -// } -// -// } -// -// /** -// * Test module index of FieldAgent -// */ -// @Test -// public void testGetModuleIndex() { -// assertEquals(5, fieldAgent.getModuleIndex()); -// } -// -// /** -// * Test Module Name of FieldAgent -// */ -// @Test -// public void getModuleName() { -// assertEquals(MODULE_NAME, fieldAgent.getModuleName()); -// -// } -// -// /** -// * Test getInstance is same as mock -// */ -// @Test -// public void testGetInstanceIsSameAsMock() { -// assertSame(fieldAgent, FieldAgent.getInstance()); -// } -// -// /** -// * Test postTracking with valid jsonObject -// */ -// @Test -//// ( timeout = 5000L ) -// public void testPostTrackingWithValidJsonObject() { -// try { -// initiateMockStart(); -// fieldAgent.postTracking(jsonObject); -// Mockito.verify(orchestrator).request(eq("tracking"), eq(RequestType.POST), eq(null), eq(jsonObject)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test postTracking with null jsonObject -// */ -// @Test -//// ( timeout = 5000L ) -// public void postTrackingLogsErrorWhenRequestFails() { -// try { -// initiateMockStart(); -// when(orchestrator.request(any(), any(), any(), any())).thenThrow(Mockito.mock(Exception.class)); -// fieldAgent.postTracking(null); -// Mockito.verify(orchestrator).request(eq("tracking"), eq(RequestType.POST), eq(null), eq(null)); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable send tracking logs"), any()); -// } catch (Exception e) { -// fail("this should never happen"); -// } -// } -// -// /** -// * Test provision when controller status is not provisioned -// */ -// @Test -// public void testProvisionWhenControllerStatusIsNotProvisioned() { -// try { -// initiateMockStart(); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// 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) { -// fail("this should never happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates is null -// */ -// @Test -// public void testProvisionWhenWhenPostFogConfigGPSCoordinatesNull() { -// try { -// when(Configuration.getGpsCoordinates()).thenReturn(null); -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// assertTrue(response.containsKey("message")); -// 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()); -// Configuration.getGpsCoordinates(); -// } catch (Exception e) { -// fail("this should never happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates are invalid -// */ -// @Test -// public void testProvisionWhenPostFogConfigGPSCoordinatesAreInvalid() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(Configuration.getGpsCoordinates()).thenReturn(""); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// assertTrue(response.containsKey("message")); -// 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()); -// Configuration.getGpsCoordinates(); -// } catch (Exception e) { -// fail("this should never happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates are valid -// * but orchestrator.request for config command returns certificate exception -// */ -// @Test -// public void throwsCertificationExceptionWhenOrchestratorRequestWithConfigIsCalledInsideProvision() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("config"), any(), any(), any())). -// thenThrow(new CertificateException("Invalid certificate")); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// assertTrue(response.containsKey("message")); -// 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()); -// Configuration.getGpsCoordinates(); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable to post ioFog config due to broken certificate "), any()); -// } catch (AgentSystemException e) { -// fail("this should never happen"); -// } catch (Exception e) { -// fail("this should never happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null and valid -// */ -// @Test -// public void testProvisionWhenPostFogConfigGPSCoordinatesAreValid() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// assertTrue(response.containsKey("message")); -// 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()); -// Configuration.getGpsCoordinates(); -// } catch (Exception e) { -// fail("this should never happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & IoFogController returns valid registries -// * And has no microservices -// */ -// @Test -// public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturnsValidRegistries() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// JsonObject registryObject = jsonObjectBuilder -// .add("id", 1) -// .add("url", "http://url") -// .add("username", "username") -// .add("password", "password") -// .add("userEmail", "userEmail") -// .build(); -// JsonArray jsonArray = Json.createArrayBuilder().add(registryObject).build(); -// jsonObject = jsonObjectBuilder -// .add("registries", jsonArray) -// .add("uuid", "uuid") -// .add("token", "token").build(); -// when(orchestrator.request(eq("registries"), any(), any(), any())).thenReturn(jsonObject); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// assertTrue(response.containsKey("message")); -// 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()); -// Configuration.getGpsCoordinates(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & -// * IoFogController returns Invalid registries -// * And has no microservices -// */ -// @Test -// public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturnsInValidRegistries() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// JsonObject registryObject = jsonObjectBuilder -// .add("id", 1) -// .build(); -// JsonArray jsonArray = Json.createArrayBuilder().add(registryObject).build(); -// jsonObject = jsonObjectBuilder -// .add("registries", jsonArray) -// .add("uuid", "uuid") -// .add("token", "token").build(); -// when(orchestrator.request(eq("registries"), any(), any(), any())).thenReturn(jsonObject); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// assertTrue(response.containsKey("message")); -// 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()); -// Configuration.getGpsCoordinates(); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable to get registries"), any()); -// } catch (AgentSystemException e) { -// fail("This should not happen"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & IoFogController returns valid registries -// * And invalid microservices -// */ -// @Test -// public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturnsValidRegistriesAndInvalidMicroservices() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// JsonObject registryObject = jsonObjectBuilder -// .add("id", 1) -// .add("url", "http://url") -// .add("username", "username") -// .add("password", "password") -// .add("userEmail", "userEmail") -// .build(); -// JsonArray jsonRegisteryArray = Json.createArrayBuilder().add(registryObject).build(); -// JsonArray jsonMicorserviceArray = Json.createArrayBuilder().add(registryObject).build(); -// jsonObject = jsonObjectBuilder -// .add("registries", jsonRegisteryArray) -// .add("microservices", jsonMicorserviceArray) -// .add("uuid", "uuid") -// .add("token", "token").build(); -// when(orchestrator.request(any(), any(), any(), any())).thenReturn(jsonObject); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// assertTrue(response.containsKey("message")); -// 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()); -// Configuration.getGpsCoordinates(); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable to parse microservices"),any()); -// } catch (AgentSystemException e) { -// fail("This should not happen"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & IoFogController returns valid registries -// * And valid microservices -// */ -// @Test -// public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturnsValidRegistriesAndValidMicroservices() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// JsonObject registryObject = jsonObjectBuilder -// .add("id", 1) -// .add("url", "http://url") -// .add("username", "username") -// .add("password", "password") -// .add("userEmail", "userEmail") -// .build(); -// JsonObject portMappingsObject = jsonObjectBuilder -// .add("portExternal", 9090) -// .add("portInternal", 8002) -// .build(); -// JsonObject volumeMappingsObject = jsonObjectBuilder -// .add("hostDestination", "hostDestination") -// .add("containerDestination", "containerDestination") -// .add("accessMode", "accessMode") -// .build(); -// JsonObject envObject = jsonObjectBuilder -// .add("key", "key") -// .add("value", "value") -// .build(); -// JsonArray jsonRegisteryArray = Json.createArrayBuilder().add(registryObject).build(); -// JsonArray routesJson = Json.createArrayBuilder().add("route").build(); -// JsonArray portMappingsJson = Json.createArrayBuilder().add(portMappingsObject).build(); -// JsonArray volumeMappingsJson = Json.createArrayBuilder().add(volumeMappingsObject).build(); -// JsonArray cmdJson = Json.createArrayBuilder().add("cmd").add("sh").build(); -// JsonArray envJson = Json.createArrayBuilder().add(envObject).build(); -// JsonObject microserviceObject = jsonObjectBuilder -// .add("uuid", "uuid") -// .add("imageId", "imageId") -// .add("config", "config") -// .add("rebuild", false) -// .add("delete", false) -// .add("rootHostAccess", false) -// .add("deleteWithCleanup", false) -// .add("registryId", 1) -// .add("logSize", 2123l) -// .add("routes", routesJson) -// .add("portMappings", portMappingsJson) -// .add("volumeMappings", volumeMappingsJson) -// .add("env", envJson) -// .add("cmd", cmdJson) -// .build(); -// JsonArray jsonMicorserviceArray = Json.createArrayBuilder().add(microserviceObject).build(); -// jsonObject = jsonObjectBuilder -// .add("registries", jsonRegisteryArray) -// .add("microservices", jsonMicorserviceArray) -// .add("uuid", "uuid") -// .add("token", "token").build(); -// when(orchestrator.request(any(), any(), any(), any())).thenReturn(jsonObject); -// when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); -// JsonObject response = fieldAgent.provision("provisonKey"); -// 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()); -// Configuration.getGpsCoordinates(); -// } catch (AgentSystemException e) { -// fail("This should not happen"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & -// * Orchestrator.provision throws AgentSystemException -// */ -// @Test -// public void throwsExceptionWhenOrchestratorProvisionIsCalled() { -// try { -// initiateMockStart(); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// when(orchestrator.provision(any())).thenThrow(new AgentSystemException("IofogController provisioning failed")); -// JsonObject provisioningResult = fieldAgent.provision("provisonKey"); -// assertTrue(provisioningResult.containsKey("status")); -// assertTrue(provisioningResult.containsKey("errorMessage")); -// assertEquals("failed", provisioningResult.getString("status")); -// assertEquals("IofogController provisioning failed", provisioningResult.getString("errorMessage")); -// Mockito.verify(orchestrator).provision(eq("provisonKey")); -// Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); -// } catch (AgentSystemException e) { -// fail("This should not happen"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & -// * Orchestrator.provision returns success response & -// * loadMicroservices : Orchestrator.request with command microservice throws CertificateException -// */ -// @Test -// public void throwsExceptionWhenOrchestratorRequestIsCalled() { -// try { -// initiateMockStart(); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.provision(any())).thenReturn(jsonObject); -// 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); -// LoggingService.logWarning(MODULE_NAME,"controller verification failed: BROKEN_CERTIFICATE"); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable to get microservices due to broken certificate"), any()); -// Mockito.verify(LoggingService.class, Mockito.never()); -// LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); -// } catch (AgentSystemException e) { -// fail("This should not happen"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & -// * Orchestrator.provision returns success response & -// * loadRegistries : Orchestrator.request with command registries throws AgentUserException -// */ -// @Test -// public void throwsAgentUserExceptionWhenLoadRegistriestIsCalledInProvision() { -// try { -// initiateMockStart(); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// when(StatusReporter.getFieldAgentStatus()).thenReturn(fieldAgentStatus); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.provision(any())).thenReturn(jsonObject); -// 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()); -// LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); -// } catch (AgentSystemException e) { -// fail("This should not happen"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & -// * Orchestrator.provision returns success response & -// * sendHWInfoFromHalToController method throws exception -// */ -// @Test -// public void throwsExceptionWhenSendHWInfoFromHalToControllerIsCalledInProvision() { -// try { -// initiateMockStart(); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// when(StatusReporter.getFieldAgentStatus()).thenReturn(fieldAgentStatus); -// 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) { -// fail("This should not happen"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test deprovision with isTokenExpired true and Controller status is not provisioned -// */ -// @Test -// public void testDeProvisionFailureWithExpiredToken() { -// try { -// 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"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test deprovision with isTokenExpired true and Controller status is provisioned -// */ -// @Test -// public void testDeProvisionSuccessWithExpiredToken() { -// try { -// initiateMockStart(); -// 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"); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Finished Deprovisioning : Success - tokens, identifiers and keys removed"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test deprovision with isTokenExpired false and Controller status is provisioned -// */ -// @Test -// public void testDeProvisionSuccessWithNotExpiredToken() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test deprovision with isTokenExpired false and Controller status is provisioned -// * Orchestrator.request throws Exception -// */ -// @Test -// public void throwsExceptionWhenOrchestratorRequestIsCalledForDeProvisioning() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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()); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test deprovision with isTokenExpired false and Controller status is provisioned -// * Error saving config updates -// */ -// @Test -// public void throwsExceptionWhenUpdatingConfigForDeProvisioning() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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()); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test deprovision with isTokenExpired false and Controller status is provisioned -// * Orchestrator.request throws SSLHandshakeException -// */ -// @Test -// public void throwsSSLHandshakeExceptionWhenOrchestratorRequestIsCalledForDeProvisioning() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("deprovision"), any(), any(), any())).thenReturn(mock(JsonObject.class)); -// Mockito.doThrow(new Exception("Error Updating config")).when(Configuration.class); -// 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()); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test instanceConfigUpdated when controller status is not provisioned -// */ -// @Test -// public void testInstanceConfigUpdatedWhenControllerStatusIsNotProvisioned() { -// try { -// initiateMockStart(); -// 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()); -// LoggingService.logInfo(MODULE_NAME, "Finished Post ioFog config"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test instanceConfigUpdated when controller status is provisioned -// */ -// @Test -// public void testInstanceConfigUpdatedWhenControllerStatusIsProvisioned() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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()); -// LoggingService.logInfo(MODULE_NAME, "Finished Post ioFog config"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test instanceConfigUpdated when controller status is provisioned -// * Orchestrator.request throws SSLHandshakeException -// */ -// @Test -// public void throwsSSLHandshakeExceptionWhenOrchestratorIsCalledToUpdateConfiguration() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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()); -// LoggingService.logDebug(MODULE_NAME, "Finished IOFog configuration update"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test instanceConfigUpdated when controller status is provisioned -// * Orchestrator.request for config throws Exception -// */ -// @Test -// public void throwsExceptionWhenOrchestratorIsCalledToUpdateConfiguration() { -// try { -// initiateMockStart(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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()); -// LoggingService.logDebug(MODULE_NAME, "Finished IOFog configuration update"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Controller status is not provisioned -// */ -// @Test -//// (timeout = 10000l) -// 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()); -// LoggingService.logDebug(MODULE_NAME, "Field Agent started"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test start getFogStatus throws Exception -// * Controller status is provisioned -// * Controller ping is false -// * Controller is verified -// * Controller connection is broken -// */ -// @Test -// public void testStartWhenControllerConnectionIsBroken() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK, Constants.ControllerStatus.OK, -// Constants.ControllerStatus.NOT_PROVISIONED, Constants.ControllerStatus.OK); -// 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()); -// LoggingService.logWarning(MODULE_NAME, "Connection to controller has broken"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Finished handling Bad Controller Status"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME,"Started checking provisioned"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test start getFogStatus throws Exception -// * Controller status is provisioned -// * Controller ping is false -// * Controller is not verified -// * Controller connection is broken -// */ -// @Test -// public void testStartWhenControllerConnectionIsBrokenAndNotVerified() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK, Constants.ControllerStatus.OK, -// Constants.ControllerStatus.NOT_PROVISIONED, Constants.ControllerStatus.OK); -// 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); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logWarning(MODULE_NAME, "controller verification failed: NOT_CONNECTED"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test start getFogStatus throws Exception -// * Controller status is provisioned -// * Controller ping is true -// * Controller is not verified -// * Controller connection is good -// */ -// @Test -// public void testStartWhenControllerIsConnectedAndStatusIsProvisioned() { -// try { -// 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 "); -// Mockito.verify(LoggingService.class, never()); -// LoggingService.logDebug(MODULE_NAME, "Finished handling Bad Controller Status"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Field Agent started"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test start getFogStatus throws Exception -// * Controller status is provisioned -// * Controller ping is true -// * Controller is not verified -// * Controller connection is good -// * initialization is false -// */ -// @Test -// public void testStartWhenControllerIsConnectedAndStatusIsProvisionedInitializationIsFalse() { -// try { -// Field instance = FieldAgent.class.getDeclaredField("initialization"); +// Field microserviceManager = FieldAgent.class.getDeclaredField("microserviceManager"); // instance.setAccessible(true); -// instance.set(fieldAgent, false); -// JsonObject configObject = jsonObjectBuilder -// .add("networkInterface", "interface") -// .add("dockerUrl", "http://url") -// .add("diskLimit", 40) -// .build(); -// when(orchestrator.request(eq("config"), any(), any(), any())).thenReturn(configObject); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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()); -// LoggingService.logDebug(MODULE_NAME, "checked is Controller Connected : true "); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Field Agent started"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test getFogStatus -// */ -// @Test -// public void testGetFogStatus() { -// try { -// method = FieldAgent.class.getDeclaredMethod("getFogStatus"); -// method.setAccessible(true); -// 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){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test deleteNode when controller status is not provisioned -// * Orchestrator returns success -// */ -// @Test -// public void testDeleteNodeSuccessWhenControllerStatusIsNotProvisioned() { -// try { -// initiateMockStart(); -// method = FieldAgent.class.getDeclaredMethod("deleteNode"); -// method.setAccessible(true); -// 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()); -// LoggingService.logInfo(MODULE_NAME, "Finished Deprovisioning : Failure - not provisioned"); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test deleteNode when controller status is provisioned -// * Orchestrator returns success -// */ -// @Test -// public void testDeleteNodeSuccessWhenControllerStatusIsProvisioned() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// initiateMockStart(); -// method = FieldAgent.class.getDeclaredMethod("deleteNode"); -// method.setAccessible(true); -// 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()); -// LoggingService.logDebug(MODULE_NAME, "Finish deleting current fog node from controller and make it deprovision"); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test deleteNode when controller status is provisioned -// * Orchestrator delete request throws exception -// * Orchestrator deprovision request returns success -// */ -// @Test -// public void throwsExceptionWhenDeleteNode() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("delete-node"), any(), any(), any())).thenThrow(mock(Exception.class)); -// initiateMockStart(); -// method = FieldAgent.class.getDeclaredMethod("deleteNode"); -// method.setAccessible(true); -// 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()); -// Mockito.verify(Configuration.class, atLeastOnce()); -// Configuration.setIofogUuid(anyString()); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test reboot success -// */ -// @Test -// public void testRebootSuccess() { -// try { -// List error = new ArrayList<>(); -// List value = new ArrayList<>(); -// value.add("success"); -// CommandShellResultSet, List> resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// initiateMockStart(); -// 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()); -// LoggingService.logInfo(MODULE_NAME, "start Remote reboot of Linux machine from IOFog controller"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Finished Remote reboot of Linux machine from IOFog controller"); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test reboot Failure When CommandShellExecutor returns errors -// */ -// @Test -// public void testRebootFailureWhenCommandShellExecutorReturnsError() { -// try { -// List error = new ArrayList<>(); -// List value = new ArrayList<>(); -// error.add("Error Rebooting"); -// CommandShellResultSet, List> resultSetWithPath = new CommandShellResultSet<>(value, error); -// when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// initiateMockStart(); -// 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()); -// LoggingService.logWarning(eq(MODULE_NAME),eq(resultSetWithPath.toString())); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test reboot Failure When CommandShellExecutor returns null -// */ -// @Test -// public void testRebootFailureWhenCommandShellExecutorReturnsNull() { -// try { -// when(CommandShellExecutor.executeCommand(any())).thenReturn(null); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// initiateMockStart(); -// 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()); -// LoggingService.logError(eq(MODULE_NAME), eq("Error in Remote reboot of Linux machine from IOFog controller"), any()); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test changeVersion success -// */ -// @Test -// public void testChangeVersionSuccess() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// initiateMockStart(); -// 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()); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Starting change version action"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Finished change version operation, received from ioFog controller"); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test changeVersion -// * Orchestrator request throws CertificateException -// */ -// @Test -// public void throwsCertificateExceptionWhenCalledForChangeVersion() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("version"), any(), any(), any())).thenThrow(mock(CertificateException.class)); -// initiateMockStart(); -// 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()); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable to get version command due to broken certificate"), any()); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test changeVersion -// * Orchestrator request throws Exception -// */ -// @Test -// public void throwsExceptionWhenCalledForChangeVersion() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("version"), any(), any(), any())).thenThrow(mock(Exception.class)); -// initiateMockStart(); -// 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){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test updateDiagnostics success -// */ -// @Test -// public void testUpdateDiagnostics() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// initiateMockStart(); -// 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"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logInfo(MODULE_NAME, "Finished update diagnostics"); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test updateDiagnostics -// * Orchestrator request throws CertificateException -// */ -// @Test -// public void throwsCertificateExceptionWhenUpdateDiagnostics() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("strace"), any(), any(), any())).thenThrow(mock(CertificateException.class)); -// initiateMockStart(); -// 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()); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable to get diagnostics update due to broken certificate"), any()); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test updateDiagnostics -// * Orchestrator request throws Exception -// */ -// @Test -// public void throwsExceptionWhenUpdateDiagnostics() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("strace"), any(), any(), any())).thenThrow(mock(Exception.class)); -// initiateMockStart(); -// 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){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test getProxyConfig -// * Orchestrator request throws Exception -// */ -// @Test -// public void throwsExceptionWhenGetProxyConfigIsCalled() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("tunnel"), any(), any(), any())).thenThrow(mock(Exception.class)); -// initiateMockStart(); -// 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()); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test getProxyConfig -// * Orchestrator request returns success -// */ -// @Test -// public void testGetProxyConfigsuccess() { -// try { -// JsonObject dummyObject =jsonObjectBuilder -// .add("uuid", "response proxy") -// .build(); -// JsonObject proxyObject = jsonObjectBuilder -// .add("tunnel", dummyObject) -// .build(); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.request(eq("tunnel"), any(), any(), any())).thenReturn(proxyObject); -// initiateMockStart(); -// method = FieldAgent.class.getDeclaredMethod("getProxyConfig"); -// method.setAccessible(true); -// 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()); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test sendUSBInfoFromHalToController -// * Orchestrator request returns success -// */ -// @Test -// public void testSendUSBInfoFromHalToController() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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()); -// LoggingService.logDebug(MODULE_NAME, "Finished send USB Info from hal To Controller"); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Test sendUSBInfoFromHalToController -// * Orchestrator request throws Exception -// */ -// @Test -// public void throwsExceptionWhenSendUSBInfoFromHalToController() { -// try { -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// 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(); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Error while sending USBInfo from hal to controller"), any()); -// } catch (Exception e){ -// fail("This should never happen"); -// } -// } -// -// /** -// * Helper method for mocking Configuration -// */ -// public void mockConfiguration() { -// when(Configuration.getIofogUuid()).thenReturn("uuid"); -// when(Configuration.getAccessToken()).thenReturn("token"); -// when(Configuration.getControllerUrl()).thenReturn("http://controllerurl"); -// when(Configuration.getNetworkInterface()).thenReturn("dynamic"); -// when(Configuration.getDockerUrl()).thenReturn("getDockerUrl"); -// when(Configuration.getDiskLimit()).thenReturn(10f); -// when(Configuration.getDiskDirectory()).thenReturn("uuid"); -// when(Configuration.getMemoryLimit()).thenReturn(4096f); -// when(Configuration.getCpuLimit()).thenReturn(80f); -// when(Configuration.getLogDiskLimit()).thenReturn(10f); -// when(Configuration.getLogDiskDirectory()).thenReturn("/var/log/iofog-agent/"); -// when(Configuration.getLogLevel()).thenReturn("info"); -// when(Configuration.getLogFileCount()).thenReturn(10); -// when(Configuration.getStatusFrequency()).thenReturn(10); -// when(Configuration.getChangeFrequency()).thenReturn(20); -// when(Configuration.getDeviceScanFrequency()).thenReturn(60); -// when(Configuration.isWatchdogEnabled()).thenReturn(false); -// when(Configuration.getReadyToUpgradeScanFrequency()).thenReturn(24); -// when(Configuration.getGpsCoordinates()).thenReturn("4000.0, 2000.3"); -// when(Configuration.getGetUsageDataFreqSeconds()).thenReturn(1l); -// } -// -// /** -// * Helper method for mocking Status classes -// */ -// public void mockOthers() { -// SupervisorStatus supervisorStatus = mock(SupervisorStatus.class); -// ProcessManagerStatus processManagerStatus = mock(ProcessManagerStatus.class); -// StatusReporterStatus statusReporterStatus = mock(StatusReporterStatus.class); -// MessageBusStatus messageBusStatus = mock(MessageBusStatus.class); -// SshProxyManagerStatus sshProxyManagerStatus = mock(SshProxyManagerStatus.class); -// IOFogNetworkInterfaceManager ioFogNetworkInterfaceManager = mock(IOFogNetworkInterfaceManager.class); -// ResourceConsumptionManagerStatus resourceConsumptionManagerStatus = mock(ResourceConsumptionManagerStatus.class); -// when(StatusReporter.getSupervisorStatus()).thenReturn(supervisorStatus); -// when(StatusReporter.getProcessManagerStatus()).thenReturn(processManagerStatus); -// when(processManagerStatus.getRunningMicroservicesCount()).thenReturn(2); -// when(StatusReporter.getStatusReporterStatus()).thenReturn(statusReporterStatus); -// when(StatusReporter.getMessageBusStatus()).thenReturn(messageBusStatus); -// when(StatusReporter.getSshManagerStatus()).thenReturn(sshProxyManagerStatus); -// when(StatusReporter.getResourceConsumptionManagerStatus()).thenReturn(resourceConsumptionManagerStatus); -// when(IOFogNetworkInterfaceManager.getInstance()).thenReturn(ioFogNetworkInterfaceManager); -// when(ioFogNetworkInterfaceManager.getCurrentIpAddress()).thenReturn("ip"); -// when(supervisorStatus.getDaemonStatus()).thenReturn(Constants.ModulesStatus.RUNNING); -// ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class); -// ScheduledFuture future = mock(ScheduledFuture.class); -// Mockito.doReturn(future).when(scheduler).scheduleAtFixedRate(any(Runnable.class), Mockito.anyLong(), Mockito.anyLong(), any(TimeUnit.class)); -// mock(Runnable.class); -// -// } +// 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); // -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & -// * Orchestrator.provision returns success response & -// * loadEdgeResources : Orchestrator.request with command microservice throws CertificateException -// */ -// @Test -// public void throwsExceptionWhenOrchestratorEdgeRequestIsCalled() { -// try { -// initiateMockStart(); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.provision(any())).thenReturn(jsonObject); -// 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); -// LoggingService.logWarning(MODULE_NAME,"controller verification failed: BROKEN_CERTIFICATE"); -// Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable to get edgeResources due to broken certificate"), any()); -// Mockito.verify(LoggingService.class, Mockito.never()); -// LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); -// } catch (AgentSystemException e) { -// fail("This should not happen"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test provision when controller status is provisioned & Gps coordinates not null & -// * Orchestrator.provision returns success response & -// * loadEdgeResources : returns list of edgeResources -// */ -// @Test -// public void testProvisionWhenLoadEdgeResourcesReturnList() { -// try { -// initiateMockStart(); -// JsonObject edgeObject = jsonObjectBuilder -// .add("id", 1) -// .add("name", "com.orange.smart-door") -// .add("description", "Orange Smart Door") -// .add("version", "0.0.1") -// .add("interfaceProtocol", "https") -// .add("interface", "") -// .build(); -// JsonArray jsonArray = Json.createArrayBuilder().add(edgeObject).build(); -// JsonObject edgeResources = jsonObjectBuilder -// .add("edgeResources", jsonArray).build(); -// when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); -// when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); -// when(orchestrator.provision(any())).thenReturn(jsonObject); -// 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...")); -// } catch (AgentSystemException e) { -// fail("This should not happen"); // } catch (Exception e) { -// fail("This should not happen"); +// throw new RuntimeException(e); // } // } -// -//} \ No newline at end of file + + public void initiateMockStart() { + 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) { + fail("this should not happen"); + } + + } + + /** + * Test module index of FieldAgent + */ + @Test + public void testGetModuleIndex() { + assertEquals(5, fieldAgent.getModuleIndex()); + } + + /** + * Test Module Name of FieldAgent + */ + @Test + public void getModuleName() { + assertEquals(MODULE_NAME, fieldAgent.getModuleName()); + + } + + /** + * Test getInstance is same as mock + */ + @Test + public void testGetInstanceIsSameAsMock() { + assertSame(fieldAgent, FieldAgent.getInstance()); + } + + /** + * Test postTracking with valid jsonObject + */ + @Test +// ( timeout = 5000L ) + public void testPostTrackingWithValidJsonObject() { + try { + initiateMockStart(); + fieldAgent.postTracking(jsonObject); + Mockito.verify(orchestrator).request(eq("tracking"), eq(RequestType.POST), eq(null), eq(jsonObject)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test postTracking with null jsonObject + */ + @Test +// ( timeout = 5000L ) + public void postTrackingLogsErrorWhenRequestFails() { + try { + initiateMockStart(); + when(orchestrator.request(any(), any(), any(), any())).thenThrow(Mockito.mock(Exception.class)); + fieldAgent.postTracking(null); + Mockito.verify(orchestrator).request(eq("tracking"), eq(RequestType.POST), eq(null), eq(null)); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Unable send tracking logs"), any()); + } catch (Exception e) { + fail("this should never happen"); + } + } + + /** + * Test provision when controller status is not provisioned + */ + @Test + public void testProvisionWhenControllerStatusIsNotProvisioned() { + try { + initiateMockStart(); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + 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) { + fail("this should never happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates is null + */ + @Test + public void testProvisionWhenWhenPostFogConfigGPSCoordinatesNull() { + try { + when(Configuration.getGpsCoordinates()).thenReturn(null); + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + assertTrue(response.containsKey("message")); + 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()); + Configuration.getGpsCoordinates(); + } catch (Exception e) { + fail("this should never happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates are invalid + */ + @Test + public void testProvisionWhenPostFogConfigGPSCoordinatesAreInvalid() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(Configuration.getGpsCoordinates()).thenReturn(""); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + assertTrue(response.containsKey("message")); + 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()); + Configuration.getGpsCoordinates(); + } catch (Exception e) { + fail("this should never happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates are valid + * but orchestrator.request for config command returns certificate exception + */ + @Test + public void throwsCertificationExceptionWhenOrchestratorRequestWithConfigIsCalledInsideProvision() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("config"), any(), any(), any())). + thenThrow(new CertificateException("Invalid certificate")); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + assertTrue(response.containsKey("message")); + 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()); + Configuration.getGpsCoordinates(); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Unable to post ioFog config due to broken certificate "), any()); + } catch (AgentSystemException e) { + fail("this should never happen"); + } catch (Exception e) { + fail("this should never happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null and valid + */ + @Test + public void testProvisionWhenPostFogConfigGPSCoordinatesAreValid() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + assertTrue(response.containsKey("message")); + 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()); + Configuration.getGpsCoordinates(); + } catch (Exception e) { + fail("this should never happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & IoFogController returns valid registries + * And has no microservices + */ + @Test + public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturnsValidRegistries() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + JsonObject registryObject = jsonObjectBuilder + .add("id", 1) + .add("url", "http://url") + .add("username", "username") + .add("password", "password") + .add("userEmail", "userEmail") + .build(); + JsonArray jsonArray = Json.createArrayBuilder().add(registryObject).build(); + jsonObject = jsonObjectBuilder + .add("registries", jsonArray) + .add("uuid", "uuid") + .add("token", "token").build(); + when(orchestrator.request(eq("registries"), any(), any(), any())).thenReturn(jsonObject); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + assertTrue(response.containsKey("message")); + 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()); + Configuration.getGpsCoordinates(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & + * IoFogController returns Invalid registries + * And has no microservices + */ + @Test + public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturnsInValidRegistries() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + JsonObject registryObject = jsonObjectBuilder + .add("id", 1) + .build(); + JsonArray jsonArray = Json.createArrayBuilder().add(registryObject).build(); + jsonObject = jsonObjectBuilder + .add("registries", jsonArray) + .add("uuid", "uuid") + .add("token", "token").build(); + when(orchestrator.request(eq("registries"), any(), any(), any())).thenReturn(jsonObject); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + assertTrue(response.containsKey("message")); + 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()); + Configuration.getGpsCoordinates(); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Unable to get registries"), any()); + } catch (AgentSystemException e) { + fail("This should not happen"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & IoFogController returns valid registries + * And invalid microservices + */ + @Test + public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturnsValidRegistriesAndInvalidMicroservices() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + JsonObject registryObject = jsonObjectBuilder + .add("id", 1) + .add("url", "http://url") + .add("username", "username") + .add("password", "password") + .add("userEmail", "userEmail") + .build(); + JsonArray jsonRegisteryArray = Json.createArrayBuilder().add(registryObject).build(); + JsonArray jsonMicorserviceArray = Json.createArrayBuilder().add(registryObject).build(); + jsonObject = jsonObjectBuilder + .add("registries", jsonRegisteryArray) + .add("microservices", jsonMicorserviceArray) + .add("uuid", "uuid") + .add("token", "token").build(); + when(orchestrator.request(any(), any(), any(), any())).thenReturn(jsonObject); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + assertTrue(response.containsKey("message")); + 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()); + Configuration.getGpsCoordinates(); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Unable to parse microservices"),any()); + } catch (AgentSystemException e) { + fail("This should not happen"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & IoFogController returns valid registries + * And valid microservices + */ + @Test + public void testProvisionWhenControllerStatusIsProvisionedAndOrchestratorReturnsValidRegistriesAndValidMicroservices() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + JsonObject registryObject = jsonObjectBuilder + .add("id", 1) + .add("url", "http://url") + .add("username", "username") + .add("password", "password") + .add("userEmail", "userEmail") + .build(); + JsonObject portMappingsObject = jsonObjectBuilder + .add("portExternal", 9090) + .add("portInternal", 8002) + .build(); + JsonObject volumeMappingsObject = jsonObjectBuilder + .add("hostDestination", "hostDestination") + .add("containerDestination", "containerDestination") + .add("accessMode", "accessMode") + .build(); + JsonObject envObject = jsonObjectBuilder + .add("key", "key") + .add("value", "value") + .build(); + JsonArray jsonRegisteryArray = Json.createArrayBuilder().add(registryObject).build(); + JsonArray routesJson = Json.createArrayBuilder().add("route").build(); + JsonArray portMappingsJson = Json.createArrayBuilder().add(portMappingsObject).build(); + JsonArray volumeMappingsJson = Json.createArrayBuilder().add(volumeMappingsObject).build(); + JsonArray cmdJson = Json.createArrayBuilder().add("cmd").add("sh").build(); + JsonArray envJson = Json.createArrayBuilder().add(envObject).build(); + JsonObject microserviceObject = jsonObjectBuilder + .add("uuid", "uuid") + .add("imageId", "imageId") + .add("config", "config") + .add("rebuild", false) + .add("delete", false) + .add("rootHostAccess", false) + .add("deleteWithCleanup", false) + .add("registryId", 1) + .add("logSize", 2123l) + .add("routes", routesJson) + .add("portMappings", portMappingsJson) + .add("volumeMappings", volumeMappingsJson) + .add("env", envJson) + .add("cmd", cmdJson) + .build(); + JsonArray jsonMicorserviceArray = Json.createArrayBuilder().add(microserviceObject).build(); + jsonObject = jsonObjectBuilder + .add("registries", jsonRegisteryArray) + .add("microservices", jsonMicorserviceArray) + .add("uuid", "uuid") + .add("token", "token").build(); + when(orchestrator.request(any(), any(), any(), any())).thenReturn(jsonObject); + when(orchestrator.provision(anyString())).thenReturn(provisionJsonObject); + JsonObject response = fieldAgent.provision("provisonKey"); + 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()); + Configuration.getGpsCoordinates(); + } catch (AgentSystemException e) { + fail("This should not happen"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & + * Orchestrator.provision throws AgentSystemException + */ + @Test + public void throwsExceptionWhenOrchestratorProvisionIsCalled() { + try { + initiateMockStart(); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + when(orchestrator.provision(any())).thenThrow(new AgentSystemException("IofogController provisioning failed")); + JsonObject provisioningResult = fieldAgent.provision("provisonKey"); + assertTrue(provisioningResult.containsKey("status")); + assertTrue(provisioningResult.containsKey("errorMessage")); + assertEquals("failed", provisioningResult.getString("status")); + assertEquals("IofogController provisioning failed", provisioningResult.getString("errorMessage")); + Mockito.verify(orchestrator).provision(eq("provisonKey")); + Mockito.verify(fieldAgentStatus, atLeastOnce()).getControllerStatus(); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); + } catch (AgentSystemException e) { + fail("This should not happen"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & + * Orchestrator.provision returns success response & + * loadMicroservices : Orchestrator.request with command microservice throws CertificateException + */ + @Test + public void throwsExceptionWhenOrchestratorRequestIsCalled() { + try { + initiateMockStart(); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.provision(any())).thenReturn(jsonObject); + 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); + LoggingService.logWarning(MODULE_NAME,"controller verification failed: BROKEN_CERTIFICATE"); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Unable to get microservices due to broken certificate"), any()); + Mockito.verify(LoggingService.class, Mockito.never()); + LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); + } catch (AgentSystemException e) { + fail("This should not happen"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & + * Orchestrator.provision returns success response & + * loadRegistries : Orchestrator.request with command registries throws AgentUserException + */ + @Test + public void throwsAgentUserExceptionWhenLoadRegistriestIsCalledInProvision() { + try { + initiateMockStart(); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + when(StatusReporter.getFieldAgentStatus()).thenReturn(fieldAgentStatus); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.provision(any())).thenReturn(jsonObject); + 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()); + LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); + } catch (AgentSystemException e) { + fail("This should not happen"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & + * Orchestrator.provision returns success response & + * sendHWInfoFromHalToController method throws exception + */ + @Test + public void throwsExceptionWhenSendHWInfoFromHalToControllerIsCalledInProvision() { + try { + initiateMockStart(); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + when(StatusReporter.getFieldAgentStatus()).thenReturn(fieldAgentStatus); + 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) { + fail("This should not happen"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test deprovision with isTokenExpired true and Controller status is not provisioned + */ + @Test + public void testDeProvisionFailureWithExpiredToken() { + try { + 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"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test deprovision with isTokenExpired true and Controller status is provisioned + */ + @Test + public void testDeProvisionSuccessWithExpiredToken() { + try { + initiateMockStart(); + 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"); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Finished Deprovisioning : Success - tokens, identifiers and keys removed"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test deprovision with isTokenExpired false and Controller status is provisioned + */ + @Test + public void testDeProvisionSuccessWithNotExpiredToken() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test deprovision with isTokenExpired false and Controller status is provisioned + * Orchestrator.request throws Exception + */ + @Test + public void throwsExceptionWhenOrchestratorRequestIsCalledForDeProvisioning() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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()); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test deprovision with isTokenExpired false and Controller status is provisioned + * Error saving config updates + */ + @Test + public void throwsExceptionWhenUpdatingConfigForDeProvisioning() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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()); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test deprovision with isTokenExpired false and Controller status is provisioned + * Orchestrator.request throws SSLHandshakeException + */ + @Test + public void throwsSSLHandshakeExceptionWhenOrchestratorRequestIsCalledForDeProvisioning() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("deprovision"), any(), any(), any())).thenReturn(mock(JsonObject.class)); + Mockito.doThrow(new Exception("Error Updating config")).when(Configuration.class); + 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()); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test instanceConfigUpdated when controller status is not provisioned + */ + @Test + public void testInstanceConfigUpdatedWhenControllerStatusIsNotProvisioned() { + try { + initiateMockStart(); + 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()); + LoggingService.logInfo(MODULE_NAME, "Finished Post ioFog config"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test instanceConfigUpdated when controller status is provisioned + */ + @Test + public void testInstanceConfigUpdatedWhenControllerStatusIsProvisioned() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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()); + LoggingService.logInfo(MODULE_NAME, "Finished Post ioFog config"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test instanceConfigUpdated when controller status is provisioned + * Orchestrator.request throws SSLHandshakeException + */ + @Test + public void throwsSSLHandshakeExceptionWhenOrchestratorIsCalledToUpdateConfiguration() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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()); + LoggingService.logDebug(MODULE_NAME, "Finished IOFog configuration update"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test instanceConfigUpdated when controller status is provisioned + * Orchestrator.request for config throws Exception + */ + @Test + public void throwsExceptionWhenOrchestratorIsCalledToUpdateConfiguration() { + try { + initiateMockStart(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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()); + LoggingService.logDebug(MODULE_NAME, "Finished IOFog configuration update"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Controller status is not provisioned + */ + @Test +// (timeout = 10000l) + 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()); + LoggingService.logDebug(MODULE_NAME, "Field Agent started"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test start getFogStatus throws Exception + * Controller status is provisioned + * Controller ping is false + * Controller is verified + * Controller connection is broken + */ + @Test + public void testStartWhenControllerConnectionIsBroken() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK, Constants.ControllerStatus.OK, + Constants.ControllerStatus.NOT_PROVISIONED, Constants.ControllerStatus.OK); + 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()); + LoggingService.logWarning(MODULE_NAME, "Connection to controller has broken"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Finished handling Bad Controller Status"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME,"Started checking provisioned"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test start getFogStatus throws Exception + * Controller status is provisioned + * Controller ping is false + * Controller is not verified + * Controller connection is broken + */ + @Test + public void testStartWhenControllerConnectionIsBrokenAndNotVerified() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK, Constants.ControllerStatus.OK, + Constants.ControllerStatus.NOT_PROVISIONED, Constants.ControllerStatus.OK); + 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); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logWarning(MODULE_NAME, "controller verification failed: NOT_CONNECTED"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test start getFogStatus throws Exception + * Controller status is provisioned + * Controller ping is true + * Controller is not verified + * Controller connection is good + */ + @Test + public void testStartWhenControllerIsConnectedAndStatusIsProvisioned() { + try { + 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 "); + Mockito.verify(LoggingService.class, never()); + LoggingService.logDebug(MODULE_NAME, "Finished handling Bad Controller Status"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Field Agent started"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test start getFogStatus throws Exception + * Controller status is provisioned + * Controller ping is true + * Controller is not verified + * Controller connection is good + * initialization is false + */ + @Test + public void testStartWhenControllerIsConnectedAndStatusIsProvisionedInitializationIsFalse() { + try { + Field instance = FieldAgent.class.getDeclaredField("initialization"); + instance.setAccessible(true); + instance.set(fieldAgent, false); + JsonObject configObject = jsonObjectBuilder + .add("networkInterface", "interface") + .add("dockerUrl", "http://url") + .add("diskLimit", 40) + .build(); + when(orchestrator.request(eq("config"), any(), any(), any())).thenReturn(configObject); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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()); + LoggingService.logDebug(MODULE_NAME, "checked is Controller Connected : true "); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Field Agent started"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test getFogStatus + */ + @Test + public void testGetFogStatus() { + try { + method = FieldAgent.class.getDeclaredMethod("getFogStatus"); + method.setAccessible(true); + 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){ + fail("This should never happen"); + } + } + + /** + * Test deleteNode when controller status is not provisioned + * Orchestrator returns success + */ + @Test + public void testDeleteNodeSuccessWhenControllerStatusIsNotProvisioned() { + try { + initiateMockStart(); + method = FieldAgent.class.getDeclaredMethod("deleteNode"); + method.setAccessible(true); + 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()); + LoggingService.logInfo(MODULE_NAME, "Finished Deprovisioning : Failure - not provisioned"); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test deleteNode when controller status is provisioned + * Orchestrator returns success + */ + @Test + public void testDeleteNodeSuccessWhenControllerStatusIsProvisioned() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + initiateMockStart(); + method = FieldAgent.class.getDeclaredMethod("deleteNode"); + method.setAccessible(true); + 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()); + LoggingService.logDebug(MODULE_NAME, "Finish deleting current fog node from controller and make it deprovision"); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test deleteNode when controller status is provisioned + * Orchestrator delete request throws exception + * Orchestrator deprovision request returns success + */ + @Test + public void throwsExceptionWhenDeleteNode() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("delete-node"), any(), any(), any())).thenThrow(mock(Exception.class)); + initiateMockStart(); + method = FieldAgent.class.getDeclaredMethod("deleteNode"); + method.setAccessible(true); + 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()); + Mockito.verify(Configuration.class, atLeastOnce()); + Configuration.setIofogUuid(anyString()); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test reboot success + */ + @Test + public void testRebootSuccess() { + try { + List error = new ArrayList<>(); + List value = new ArrayList<>(); + value.add("success"); + CommandShellResultSet, List> resultSetWithPath = new CommandShellResultSet<>(value, error); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + initiateMockStart(); + 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()); + LoggingService.logInfo(MODULE_NAME, "start Remote reboot of Linux machine from IOFog controller"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Finished Remote reboot of Linux machine from IOFog controller"); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test reboot Failure When CommandShellExecutor returns errors + */ + @Test + public void testRebootFailureWhenCommandShellExecutorReturnsError() { + try { + List error = new ArrayList<>(); + List value = new ArrayList<>(); + error.add("Error Rebooting"); + CommandShellResultSet, List> resultSetWithPath = new CommandShellResultSet<>(value, error); + when(CommandShellExecutor.executeCommand(any())).thenReturn(resultSetWithPath); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + initiateMockStart(); + 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()); + LoggingService.logWarning(eq(MODULE_NAME),eq(resultSetWithPath.toString())); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test reboot Failure When CommandShellExecutor returns null + */ + @Test + public void testRebootFailureWhenCommandShellExecutorReturnsNull() { + try { + when(CommandShellExecutor.executeCommand(any())).thenReturn(null); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + initiateMockStart(); + 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()); + LoggingService.logError(eq(MODULE_NAME), eq("Error in Remote reboot of Linux machine from IOFog controller"), any()); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test changeVersion success + */ + @Test + public void testChangeVersionSuccess() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + initiateMockStart(); + 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()); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Starting change version action"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Finished change version operation, received from ioFog controller"); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test changeVersion + * Orchestrator request throws CertificateException + */ + @Test + public void throwsCertificateExceptionWhenCalledForChangeVersion() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("version"), any(), any(), any())).thenThrow(mock(CertificateException.class)); + initiateMockStart(); + 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()); + LoggingService.logError(eq(MODULE_NAME), eq("Unable to get version command due to broken certificate"), any()); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test changeVersion + * Orchestrator request throws Exception + */ + @Test + public void throwsExceptionWhenCalledForChangeVersion() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("version"), any(), any(), any())).thenThrow(mock(Exception.class)); + initiateMockStart(); + 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){ + fail("This should never happen"); + } + } + + /** + * Test updateDiagnostics success + */ + @Test + public void testUpdateDiagnostics() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + initiateMockStart(); + 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"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logInfo(MODULE_NAME, "Finished update diagnostics"); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test updateDiagnostics + * Orchestrator request throws CertificateException + */ + @Test + public void throwsCertificateExceptionWhenUpdateDiagnostics() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("strace"), any(), any(), any())).thenThrow(mock(CertificateException.class)); + initiateMockStart(); + 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()); + LoggingService.logError(eq(MODULE_NAME), eq("Unable to get diagnostics update due to broken certificate"), any()); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test updateDiagnostics + * Orchestrator request throws Exception + */ + @Test + public void throwsExceptionWhenUpdateDiagnostics() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("strace"), any(), any(), any())).thenThrow(mock(Exception.class)); + initiateMockStart(); + 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){ + fail("This should never happen"); + } + } + + /** + * Test getProxyConfig + * Orchestrator request throws Exception + */ + @Test + public void throwsExceptionWhenGetProxyConfigIsCalled() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("tunnel"), any(), any(), any())).thenThrow(mock(Exception.class)); + initiateMockStart(); + 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()); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test getProxyConfig + * Orchestrator request returns success + */ + @Test + public void testGetProxyConfigsuccess() { + try { + JsonObject dummyObject =jsonObjectBuilder + .add("uuid", "response proxy") + .build(); + JsonObject proxyObject = jsonObjectBuilder + .add("tunnel", dummyObject) + .build(); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.request(eq("tunnel"), any(), any(), any())).thenReturn(proxyObject); + initiateMockStart(); + method = FieldAgent.class.getDeclaredMethod("getProxyConfig"); + method.setAccessible(true); + 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()); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test sendUSBInfoFromHalToController + * Orchestrator request returns success + */ + @Test + public void testSendUSBInfoFromHalToController() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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()); + LoggingService.logDebug(MODULE_NAME, "Finished send USB Info from hal To Controller"); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Test sendUSBInfoFromHalToController + * Orchestrator request throws Exception + */ + @Test + public void throwsExceptionWhenSendUSBInfoFromHalToController() { + try { + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + 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(); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Error while sending USBInfo from hal to controller"), any()); + } catch (Exception e){ + fail("This should never happen"); + } + } + + /** + * Helper method for mocking Configuration + */ + public void mockConfiguration() { + when(Configuration.getIofogUuid()).thenReturn("uuid"); + when(Configuration.getAccessToken()).thenReturn("token"); + when(Configuration.getControllerUrl()).thenReturn("http://controllerurl"); + when(Configuration.getNetworkInterface()).thenReturn("dynamic"); + when(Configuration.getDockerUrl()).thenReturn("getDockerUrl"); + when(Configuration.getDiskLimit()).thenReturn(10f); + when(Configuration.getDiskDirectory()).thenReturn("uuid"); + when(Configuration.getMemoryLimit()).thenReturn(4096f); + when(Configuration.getCpuLimit()).thenReturn(80f); + when(Configuration.getLogDiskLimit()).thenReturn(10f); + when(Configuration.getLogDiskDirectory()).thenReturn("/var/log/iofog-agent/"); + when(Configuration.getLogLevel()).thenReturn("info"); + when(Configuration.getLogFileCount()).thenReturn(10); + when(Configuration.getStatusFrequency()).thenReturn(10); + when(Configuration.getChangeFrequency()).thenReturn(20); + when(Configuration.getDeviceScanFrequency()).thenReturn(60); + when(Configuration.isWatchdogEnabled()).thenReturn(false); + when(Configuration.getReadyToUpgradeScanFrequency()).thenReturn(24); + when(Configuration.getGpsCoordinates()).thenReturn("4000.0, 2000.3"); + when(Configuration.getGetUsageDataFreqSeconds()).thenReturn(1l); + } + + /** + * Helper method for mocking Status classes + */ + public void mockOthers() { + SupervisorStatus supervisorStatus = mock(SupervisorStatus.class); + ProcessManagerStatus processManagerStatus = mock(ProcessManagerStatus.class); + StatusReporterStatus statusReporterStatus = mock(StatusReporterStatus.class); + MessageBusStatus messageBusStatus = mock(MessageBusStatus.class); + SshProxyManagerStatus sshProxyManagerStatus = mock(SshProxyManagerStatus.class); + IOFogNetworkInterfaceManager ioFogNetworkInterfaceManager = mock(IOFogNetworkInterfaceManager.class); + ResourceConsumptionManagerStatus resourceConsumptionManagerStatus = mock(ResourceConsumptionManagerStatus.class); + when(StatusReporter.getSupervisorStatus()).thenReturn(supervisorStatus); + when(StatusReporter.getProcessManagerStatus()).thenReturn(processManagerStatus); + when(processManagerStatus.getRunningMicroservicesCount()).thenReturn(2); + when(StatusReporter.getStatusReporterStatus()).thenReturn(statusReporterStatus); + when(StatusReporter.getMessageBusStatus()).thenReturn(messageBusStatus); + when(StatusReporter.getSshManagerStatus()).thenReturn(sshProxyManagerStatus); + when(StatusReporter.getResourceConsumptionManagerStatus()).thenReturn(resourceConsumptionManagerStatus); + when(IOFogNetworkInterfaceManager.getInstance()).thenReturn(ioFogNetworkInterfaceManager); + when(ioFogNetworkInterfaceManager.getCurrentIpAddress()).thenReturn("ip"); + when(supervisorStatus.getDaemonStatus()).thenReturn(Constants.ModulesStatus.RUNNING); + ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class); + ScheduledFuture future = mock(ScheduledFuture.class); + Mockito.doReturn(future).when(scheduler).scheduleAtFixedRate(any(Runnable.class), Mockito.anyLong(), Mockito.anyLong(), any(TimeUnit.class)); + mock(Runnable.class); + + } + + /** + * Test provision when controller status is provisioned & Gps coordinates not null & + * Orchestrator.provision returns success response & + * loadEdgeResources : Orchestrator.request with command microservice throws CertificateException + */ + @Test + public void throwsExceptionWhenOrchestratorEdgeRequestIsCalled() { + try { + initiateMockStart(); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.provision(any())).thenReturn(jsonObject); + 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); + LoggingService.logWarning(MODULE_NAME,"controller verification failed: BROKEN_CERTIFICATE"); + Mockito.verify(LoggingService.class, Mockito.atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Unable to get edgeResources due to broken certificate"), any()); + Mockito.verify(LoggingService.class, Mockito.never()); + LoggingService.logError(eq(MODULE_NAME), eq("Provisioning failed"), any()); + } catch (AgentSystemException e) { + fail("This should not happen"); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test provision when controller status is provisioned & Gps coordinates not null & + * Orchestrator.provision returns success response & + * loadEdgeResources : returns list of edgeResources + */ + @Test + public void testProvisionWhenLoadEdgeResourcesReturnList() { + try { + initiateMockStart(); + JsonObject edgeObject = jsonObjectBuilder + .add("id", 1) + .add("name", "com.orange.smart-door") + .add("description", "Orange Smart Door") + .add("version", "0.0.1") + .add("interfaceProtocol", "https") + .add("interface", "") + .build(); + JsonArray jsonArray = Json.createArrayBuilder().add(edgeObject).build(); + JsonObject edgeResources = jsonObjectBuilder + .add("edgeResources", jsonArray).build(); + when(Configuration.getGpsCoordinates()).thenReturn("40.9006, 174.8860"); + when(fieldAgentStatus.getControllerStatus()).thenReturn(Constants.ControllerStatus.OK); + when(orchestrator.provision(any())).thenReturn(jsonObject); + 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...")); + } catch (AgentSystemException e) { + fail("This should not happen"); + } 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/local_api/ApiHandlerHelpersTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ApiHandlerHelpersTest.java index 06f6471d..45838cd2 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 @@ -52,8 +52,6 @@ public class ApiHandlerHelpersTest { private HttpHeaders httpHeaders; private ByteBuf byteBuf; private DefaultFullHttpResponse defaultResponse; - private BufferedReader bufferedReader; - private FileReader fileReader; private MockedStatic apiHandlerHelpersMockedStatic; private MockedStatic loggingServiceMockedStatic; private MockedConstruction bufferedReaderMockedConstruction; @@ -66,8 +64,6 @@ public void setUp() throws Exception { request = mock(HttpRequest.class); httpHeaders = mock(HttpHeaders.class); byteBuf = mock(ByteBuf.class); - bufferedReader = mock(BufferedReader.class); - fileReader = mock(FileReader.class); expectedMethod = HttpMethod.POST; contentType = "Application/json"; content = "response content"; @@ -78,14 +74,6 @@ public void setUp() throws Exception { bufferedReaderMockedConstruction = mockConstruction(BufferedReader.class, (mock, context) -> { when(mock.readLine()).thenReturn("token"); }); -// Mockito.whenNew(BufferedReader.class) -// .withParameterTypes(Reader.class) -// .withArguments(Mockito.any(Reader.class)) -// .thenReturn(bufferedReader); -// Mockito.whenNew(FileReader.class) -// .withParameterTypes(String.class) -// .withArguments(Mockito.anyString()) -// .thenReturn(fileReader); } @AfterEach @@ -170,7 +158,6 @@ public void testValidateContentTypeAreSame() { public void testValidateAccessTokenFalse() { try { assertFalse(ApiHandlerHelpers.validateAccessToken(request)); -// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); } catch (Exception e) { fail("This should not happen"); } @@ -184,9 +171,7 @@ public void testValidateAccessTokenTrue() { try { Mockito.when(request.headers()).thenReturn(httpHeaders); Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("token"); -// Mockito.when(bufferedReader.readLine()).thenReturn("token"); assertTrue(ApiHandlerHelpers.validateAccessToken(request)); -// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); } catch (Exception e) { fail("This should not happen"); } @@ -205,7 +190,6 @@ public void testValidateAccesswhenFetchTokenThrowsException() { when(mock.readLine()).thenThrow(IOException.class); }); assertFalse(ApiHandlerHelpers.validateAccessToken(request)); -// Mockito.verifyPrivate(ApiHandlerHelpers.class).invoke("fetchAccessToken"); LoggingService.logError(Mockito.eq("Local API"), Mockito.eq("unable to load api token"), Mockito.any()); 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 0f8ce02e..fdaaa300 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,146 +1,132 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.bootstrap.Bootstrap; -//import io.netty.buffer.ByteBuf; -//import io.netty.channel.Channel; -//import io.netty.channel.ChannelFuture; -//import io.netty.channel.ChannelInitializer; -//import io.netty.channel.nio.NioEventLoopGroup; -//import io.netty.handler.codec.http.*; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static org.junit.Assert.*; -//import static org.powermock.api.mockito.Mockito.mockStatic; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({BluetoothApiHandler.class, FullHttpRequest.class, ByteBuf.class, NioEventLoopGroup.class, -// Bootstrap.class, ChannelInitializer.class, LoggingService.class, Channel.class, ChannelFuture.class, -// HttpHeaders.class, DefaultFullHttpRequest.class}) -//@Ignore -//public class BluetoothApiHandlerTest { -// private BluetoothApiHandler bluetoothApiHandler; -// private FullHttpRequest httpRequest; -// private HttpHeaders httpHeaders; -// private ByteBuf byteBuf; -// private String content; -// private byte[] bytes; -// private NioEventLoopGroup nioEventLoopGroup; -// private Bootstrap bootstrap; -// private ChannelInitializer channelInitializer; -// private Channel channel; -// private ChannelFuture channelFuture; -// private DefaultFullHttpResponse defaultResponse; -// private DefaultFullHttpRequest defaultFullHttpRequest; -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// @Before -// public void setUp() throws Exception { -// httpRequest = Mockito.mock(FullHttpRequest.class); -// httpHeaders = Mockito.mock(HttpHeaders.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// nioEventLoopGroup = Mockito.mock(NioEventLoopGroup.class); -// bootstrap = Mockito.mock(Bootstrap.class); -// channelInitializer = Mockito.mock(ChannelInitializer.class); -// channel = Mockito.mock(Channel.class); -// channelFuture = Mockito.mock(ChannelFuture.class); -// defaultFullHttpRequest = Mockito.mock(DefaultFullHttpRequest.class); -// mockStatic(LoggingService.class); -// content = "content"; -// bytes = content.getBytes(); -// bluetoothApiHandler = Mockito.spy(new BluetoothApiHandler(httpRequest, byteBuf, bytes)); -// Mockito.whenNew(NioEventLoopGroup.class) -// .withArguments(Mockito.anyInt()) -// .thenReturn(nioEventLoopGroup); -// Mockito.whenNew(Bootstrap.class) -// .withNoArguments() -// .thenReturn(bootstrap); -// Mockito.whenNew(ChannelInitializer.class) -// .withNoArguments() -// .thenReturn(channelInitializer); -// Mockito.whenNew(DefaultFullHttpRequest.class) -// .withParameterTypes(HttpVersion.class, HttpMethod.class, String.class, ByteBuf.class) -// .withArguments(Mockito.eq(HttpVersion.HTTP_1_1), Mockito.eq(HttpMethod.POST), Mockito.anyString(), Mockito.any(ByteBuf.class)) -// .thenReturn(defaultFullHttpRequest); -// Mockito.when(defaultFullHttpRequest.headers()).thenReturn(httpHeaders); -// Mockito.when(bootstrap.channel(Mockito.any())).thenReturn(bootstrap); -// Mockito.when(bootstrap.option(Mockito.any(), Mockito.anyBoolean())).thenReturn(bootstrap); -// Mockito.when(bootstrap.group(Mockito.any())).thenReturn(bootstrap); -// Mockito.when(bootstrap.handler(Mockito.any())).thenReturn(bootstrap); -// Mockito.when(bootstrap.connect(Mockito.anyString(), Mockito.anyInt())).thenReturn(channelFuture); -// Mockito.when(channelFuture.sync()).thenReturn(channelFuture); -// Mockito.when(channelFuture.channel()).thenReturn(channel); -// Mockito.when(httpRequest.uri()).thenReturn("http://0.0.0.0:5000/"); -// Mockito.when(httpRequest.headers()).thenReturn(httpHeaders); -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.POST); -// } -// -// @After -// public void tearDown() throws Exception { -// Mockito.reset(bluetoothApiHandler, httpRequest, byteBuf); -// -// } -// -// /** -// * Test call when response NOT_FOUND -// */ -// @Test -// public void testCallWhenResponseNotFound() { -// try { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// defaultResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json"); -// assertEquals(defaultResponse, bluetoothApiHandler.call()); -// Mockito.verify(bootstrap).connect(Mockito.eq("localhost"), Mockito.eq(10500)); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(Mockito.eq("Local Api : Bluetooth API"), Mockito.eq("Error unable to reach RESTblue container!"), Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when response NOT_FOUND -// */ -// @Test -// public void testCallWhenResponseNotFoundAndChannelFlush() { -// try { -// Mockito.when(channel.writeAndFlush(Mockito.any())).thenReturn(channelFuture); -// Mockito.when(channelFuture.addListener(Mockito.any())).thenReturn(channelFuture); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// defaultResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json"); -// assertEquals(defaultResponse, bluetoothApiHandler.call()); -// Mockito.verify(bootstrap).connect(Mockito.eq("localhost"), Mockito.eq(10500)); -// Mockito.verify(LoggingService.class, Mockito.never()); -// LoggingService.logError(Mockito.eq("Local Api : Bluetooth API"), Mockito.eq("Error unable to reach RESTblue container!"), Mockito.any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.bootstrap.Bootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.handler.codec.http.*; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.*; + + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class BluetoothApiHandlerTest { + private BluetoothApiHandler bluetoothApiHandler; + private FullHttpRequest httpRequest; + private ByteBuf byteBuf; + private Channel channel; + private ChannelFuture channelFuture; + private DefaultFullHttpResponse defaultResponse; + private MockedStatic loggingServiceMockedStatic; + private MockedConstruction nioEventLoopGroupMockedConstruction; + private MockedConstruction bootstrapMockedConstruction; + private MockedConstruction defaultFullHttpRequestMockedConstruction; + @BeforeEach + public void setUp() throws Exception { + httpRequest = Mockito.mock(FullHttpRequest.class); + HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class); + byteBuf = Mockito.mock(ByteBuf.class); + Bootstrap bootstrap = Mockito.mock(Bootstrap.class); + channel = Mockito.mock(Channel.class); + channelFuture = Mockito.mock(ChannelFuture.class); + DefaultFullHttpRequest defaultFullHttpRequest = Mockito.mock(DefaultFullHttpRequest.class); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + String content = "content"; + byte[] bytes = content.getBytes(); + bluetoothApiHandler = Mockito.spy(new BluetoothApiHandler(httpRequest, byteBuf, bytes)); + nioEventLoopGroupMockedConstruction = mockConstruction(NioEventLoopGroup.class, (mock, context) -> {}); + bootstrapMockedConstruction = mockConstruction(Bootstrap.class, (mock, context) -> {}); + defaultFullHttpRequestMockedConstruction = mockConstruction(DefaultFullHttpRequest.class, (mock, context) -> {}); + Mockito.when(defaultFullHttpRequest.headers()).thenReturn(httpHeaders); + Mockito.when(bootstrap.channel(Mockito.any())).thenReturn(bootstrap); + Mockito.when(bootstrap.option(Mockito.any(), Mockito.anyBoolean())).thenReturn(bootstrap); + Mockito.when(bootstrap.group(Mockito.any())).thenReturn(bootstrap); + Mockito.when(bootstrap.handler(Mockito.any())).thenReturn(bootstrap); + Mockito.when(bootstrap.connect(Mockito.anyString(), Mockito.anyInt())).thenReturn(channelFuture); + Mockito.when(channelFuture.sync()).thenReturn(channelFuture); + Mockito.when(channelFuture.channel()).thenReturn(channel); + Mockito.when(httpRequest.uri()).thenReturn("http://0.0.0.0:5000/"); + Mockito.when(httpRequest.headers()).thenReturn(httpHeaders); + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.POST); + } + + @AfterEach + public void tearDown() throws Exception { + loggingServiceMockedStatic.close(); + nioEventLoopGroupMockedConstruction.close(); + bootstrapMockedConstruction.close(); + defaultFullHttpRequestMockedConstruction.close(); + Mockito.reset(bluetoothApiHandler, httpRequest, byteBuf); + + } + + /** + * Test call when response NOT_FOUND + */ + @Test + public void testCallWhenResponseNotFound() { + try { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + defaultResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json"); + assertEquals(defaultResponse, bluetoothApiHandler.call()); + Mockito.verify(LoggingService.class); + LoggingService.logError(Mockito.eq("Local Api : Bluetooth API"), Mockito.eq("Error unable to reach RESTblue container!"), Mockito.any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when response NOT_FOUND + */ + @Test + public void testCallWhenResponseNotFoundAndChannelFlush() { + try { + Mockito.when(channel.writeAndFlush(Mockito.any())).thenReturn(channelFuture); + Mockito.when(channelFuture.addListener(Mockito.any())).thenReturn(channelFuture); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, NOT_FOUND, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + defaultResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json"); + assertEquals(defaultResponse, bluetoothApiHandler.call()); + Mockito.verify(LoggingService.class); + LoggingService.logError(Mockito.eq("Local Api : Bluetooth API"), Mockito.eq("Error unable to reach RESTblue container!"), 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/local_api/CommandLineApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/CommandLineApiHandlerTest.java index 1e51668f..60f05a4a 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,306 +1,280 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import com.fasterxml.jackson.databind.ObjectMapper; -//import io.netty.buffer.ByteBuf; -//import io.netty.handler.codec.http.*; -//import org.eclipse.iofog.command_line.CommandLineParser; -//import org.eclipse.iofog.exception.AgentSystemException; -//import org.eclipse.iofog.exception.AgentUserException; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import javax.json.Json; -//import javax.json.JsonObject; -//import javax.json.JsonReader; -//import java.io.BufferedReader; -//import java.io.Reader; -//import java.io.StringReader; -//import java.util.HashMap; -//import java.util.Map; -//import java.util.concurrent.ExecutorService; -//import java.util.concurrent.Executors; -// -//import static io.netty.handler.codec.http.HttpMethod.POST; -//import static io.netty.handler.codec.http.HttpResponseStatus.*; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static java.nio.charset.StandardCharsets.UTF_8; -//import static org.junit.Assert.*; -//import static org.powermock.api.mockito.Mockito.*; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({CommandLineApiHandler.class, HttpRequest.class, ByteBuf.class, LoggingService.class, HttpHeaders.class, -// ApiHandlerHelpers.class, Json.class, JsonReader.class, JsonObject.class, CommandLineParser.class, BufferedReader.class}) -//@Ignore -//public class CommandLineApiHandlerTest { -// private CommandLineApiHandler commandLineApiHandler; -// private HttpRequest httpRequest; -// private ByteBuf byteBuf; -// private String content; -// private byte[] bytes; -// private DefaultFullHttpResponse defaultResponse; -// private HttpHeaders httpHeaders; -// private String contentType; -// private BufferedReader bufferedReader; -// private JsonReader jsonReader; -// private JsonObject jsonObject; -// private String commandLineOutput; -// private ObjectMapper objectMapper; -// private ExecutorService executor; -// -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// -// @Before -// public void setUp() throws Exception { -// executor = Executors.newFixedThreadPool(1); -// content = "content"; -// contentType = "text/html"; -// bytes = content.getBytes(); -// objectMapper = new ObjectMapper(); -// httpRequest = Mockito.mock(HttpRequest.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// jsonReader = Mockito.mock(JsonReader.class); -// httpHeaders = Mockito.mock(HttpHeaders.class); -// commandLineApiHandler = Mockito.spy(new CommandLineApiHandler(httpRequest, byteBuf, bytes)); -// bufferedReader = Mockito.mock(BufferedReader.class); -// jsonObject = Mockito.mock(JsonObject.class); -// Mockito.mockStatic(ApiHandlerHelpers.class); -// Mockito.mockStatic(Json.class); -// Mockito.mockStatic(CommandLineParser.class); -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.POST); -// Mockito.whenNew(BufferedReader.class) -// .withParameterTypes(Reader.class) -// .withArguments(Mockito.any(Reader.class)) -// .thenReturn(bufferedReader); -// mockStatic(LoggingService.class); -// Mockito.when(httpRequest.headers()).thenReturn(httpHeaders); -// Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); -// Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); -// Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); -// Mockito.when(byteBuf.writeBytes(Mockito.any(byte[].class))).thenReturn(byteBuf); -// commandLineOutput = "success help"; -// Mockito.when(ApiHandlerHelpers.validateMethod(httpRequest, POST)).thenReturn(true); -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); -// } -// -// @After -// public void tearDown() throws Exception { -// defaultResponse = null; -// objectMapper = null; -// jsonObject = null; -// httpRequest = null; -// byteBuf = null; -// commandLineApiHandler = null; -// defaultResponse = null; -// jsonReader = null; -// bytes = null; -// content = null; -// executor.shutdown(); -// } -// -// /** -// * Test ApiHandlerHelpers.validateMethod returns false -// */ -// @Test -// public void testCallWhenMethodIsNotValid() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); -// Mockito.when(ApiHandlerHelpers.validateMethod(httpRequest, POST)).thenReturn(false); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); -// Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); -// assertEquals(defaultResponse, commandLineApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.methodNotAllowedResponse(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test ApiHandlerHelpers.validateContentType returns text/html -// */ -// @Test -// public void testCallWhenContentTypeIsNotValid() { -// try { -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn("Incorrect content type text/html"); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// assertEquals(defaultResponse, commandLineApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq("Incorrect content type text/html")); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test ApiHandlerHelpers.validateContentType returns null -// */ -// @Test -// public void testCallWhenContentTypeIsNull() { -// try { -// Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(null); -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn("Incorrect content type null"); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// assertEquals(defaultResponse, commandLineApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq("Incorrect content type null")); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test ApiHandlerHelpers.validateAccessToken returns false -// */ -// @Test -// public void testCallWhenAccessTokenIsNull() { -// try { -// String errorMsg = "Incorrect access token"; -// contentType = "application/json"; -// Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); -// assertEquals(defaultResponse, commandLineApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test ApiHandlerHelpers.validateAccessToken returns false -// */ -// @Test -// public void testCallWhenAccessTokenIsNotValid() { -// try { -// String errorMsg = "Incorrect access token"; -// contentType = "application/json"; -// Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); -// Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("access-token"); -// Mockito.when(bufferedReader.readLine()).thenReturn("token"); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); -// Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// assertEquals(defaultResponse, commandLineApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call success -// */ -// @Test -// public void testCallSuccess() { -// try { -// contentType = "application/json"; -// Mockito.when(jsonObject.getString("command")).thenReturn("help"); -// Map resultMap = new HashMap<>(); -// resultMap.put("response", commandLineOutput); -// String jsonResult = objectMapper.writeValueAsString(resultMap); -// Mockito.when(CommandLineParser.parse(Mockito.anyString())).thenReturn(commandLineOutput); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(jsonResult))).thenReturn(defaultResponse); -// commandLineApiHandler.call(); -// verifyStatic(CommandLineParser.class); -// CommandLineParser.parse(Mockito.eq("help")); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(jsonResult)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test call when commandLine.parse method throws exception -// */ -// @Test -// public void testCallFailureResponse() { -// try { -// contentType = "application/json"; -// Mockito.when(jsonObject.getString("command")).thenReturn("help"); -// Mockito.when(CommandLineParser.parse(Mockito.anyString())).thenThrow(mock(AgentUserException.class)); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, byteBuf); -// Map resultMap = new HashMap<>(); -// resultMap.put("response", null); -// resultMap.put("error", "Internal server error"); -// String jsonResult = objectMapper.writeValueAsString(resultMap); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(jsonResult))).thenReturn(defaultResponse); -// commandLineApiHandler.call(); -// verifyStatic(CommandLineParser.class); -// CommandLineParser.parse(Mockito.eq("help")); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.internalServerErrorResponse(Mockito.eq(byteBuf), Mockito.eq(jsonResult)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when jsonReader throws exception -// */ -// @Test -// public void testCallWhenJsonReaderThrowsRuntimeException() { -// try { -// RuntimeException e = new RuntimeException("Error"); -// String errorMsg = " Log message parsing error, " + e.getMessage(); -// contentType = "application/json"; -// Mockito.when(jsonObject.getString("command")).thenReturn("help"); -// Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); -// Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("token"); -// Mockito.when(bufferedReader.readLine()).thenReturn("token"); -// Mockito.when(jsonReader.readObject()).thenThrow(e); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); -// commandLineApiHandler.call(); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.*; +import org.eclipse.iofog.command_line.CommandLineParser; +import org.eclipse.iofog.exception.AgentUserException; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; +import java.io.BufferedReader; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static io.netty.handler.codec.http.HttpMethod.POST; +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class CommandLineApiHandlerTest { + private CommandLineApiHandler commandLineApiHandler; + private HttpRequest httpRequest; + private ByteBuf byteBuf; + private String content; + private byte[] bytes; + private DefaultFullHttpResponse defaultResponse; + private HttpHeaders httpHeaders; + private String contentType; + private BufferedReader bufferedReader; + private JsonReader jsonReader; + private JsonObject jsonObject; + private String commandLineOutput; + private ObjectMapper objectMapper; + private ExecutorService executor; + private MockedConstruction bufferedReaderMockedConstruction; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic apiHandlerHelpersMockedStatic; + private MockedStatic jsonMockedStatic; + private MockedStatic commandLineParserMockedStatic; + + + //global timeout rule + + @BeforeEach + public void setUp() throws Exception { + executor = Executors.newFixedThreadPool(1); + content = "content"; + contentType = "text/html"; + bytes = content.getBytes(); + objectMapper = new ObjectMapper(); + httpRequest = Mockito.mock(HttpRequest.class); + byteBuf = Mockito.mock(ByteBuf.class); + jsonReader = Mockito.mock(JsonReader.class); + httpHeaders = Mockito.mock(HttpHeaders.class); + commandLineApiHandler = Mockito.spy(new CommandLineApiHandler(httpRequest, byteBuf, bytes)); + bufferedReader = Mockito.mock(BufferedReader.class); + jsonObject = Mockito.mock(JsonObject.class); + apiHandlerHelpersMockedStatic = mockStatic(ApiHandlerHelpers.class); + jsonMockedStatic = mockStatic(Json.class); + commandLineParserMockedStatic = mockStatic(CommandLineParser.class); + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.POST); + bufferedReaderMockedConstruction = mockConstruction(BufferedReader.class, (mock, context) -> {}); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + Mockito.when(httpRequest.headers()).thenReturn(httpHeaders); + Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); + Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); + Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); + Mockito.when(byteBuf.writeBytes(Mockito.any(byte[].class))).thenReturn(byteBuf); + commandLineOutput = "success help"; + Mockito.when(ApiHandlerHelpers.validateMethod(httpRequest, POST)).thenReturn(true); + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); + } + + @AfterEach + public void tearDown() throws Exception { + objectMapper = null; + jsonObject = null; + httpRequest = null; + byteBuf = null; + commandLineApiHandler = null; + defaultResponse = null; + jsonReader = null; + bytes = null; + content = null; + bufferedReaderMockedConstruction.close(); + loggingServiceMockedStatic.close(); + apiHandlerHelpersMockedStatic.close(); + jsonMockedStatic.close(); + commandLineParserMockedStatic.close(); + executor.shutdown(); + } + + /** + * Test ApiHandlerHelpers.validateMethod returns false + */ + @Test + public void testCallWhenMethodIsNotValid() { + try { + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); + Mockito.when(ApiHandlerHelpers.validateMethod(httpRequest, POST)).thenReturn(false); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); + Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); + assertEquals(defaultResponse, commandLineApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ApiHandlerHelpers.validateContentType returns text/html + */ + @Test + public void testCallWhenContentTypeIsNotValid() { + try { + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn("Incorrect content type text/html"); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + assertEquals(defaultResponse, commandLineApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ApiHandlerHelpers.validateContentType returns null + */ + @Test + public void testCallWhenContentTypeIsNull() { + try { + Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(null); + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn("Incorrect content type null"); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + assertEquals(defaultResponse, commandLineApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ApiHandlerHelpers.validateAccessToken returns false + */ + @Test + public void testCallWhenAccessTokenIsNull() { + try { + String errorMsg = "Incorrect access token"; + contentType = "application/json"; + Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); + Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); + assertEquals(defaultResponse, commandLineApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ApiHandlerHelpers.validateAccessToken returns false + */ + @Test + public void testCallWhenAccessTokenIsNotValid() { + try { + String errorMsg = "Incorrect access token"; + contentType = "application/json"; + Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); + Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("access-token"); + Mockito.when(bufferedReader.readLine()).thenReturn("token"); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); + Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + assertEquals(defaultResponse, commandLineApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call success + */ + @Test + public void testCallSuccess() { + try { + contentType = "application/json"; + Mockito.when(jsonObject.getString("command")).thenReturn("help"); + Map resultMap = new HashMap<>(); + resultMap.put("response", commandLineOutput); + String jsonResult = objectMapper.writeValueAsString(resultMap); + Mockito.when(CommandLineParser.parse(Mockito.anyString())).thenReturn(commandLineOutput); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(jsonResult))).thenReturn(defaultResponse); + commandLineApiHandler.call(); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test call when commandLine.parse method throws exception + */ + @Test + public void testCallFailureResponse() { + try { + contentType = "application/json"; + Mockito.when(jsonObject.getString("command")).thenReturn("help"); + Mockito.when(CommandLineParser.parse(Mockito.anyString())).thenThrow(mock(AgentUserException.class)); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, byteBuf); + Map resultMap = new HashMap<>(); + resultMap.put("response", null); + resultMap.put("error", "Internal server error"); + String jsonResult = objectMapper.writeValueAsString(resultMap); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(jsonResult))).thenReturn(defaultResponse); + commandLineApiHandler.call(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when jsonReader throws exception + */ + @Test + public void testCallWhenJsonReaderThrowsRuntimeException() { + try { + RuntimeException e = new RuntimeException("Error"); + String errorMsg = " Log message parsing error, " + e.getMessage(); + contentType = "application/json"; + Mockito.when(jsonObject.getString("command")).thenReturn("help"); + Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); + Mockito.when(httpHeaders.get(HttpHeaderNames.AUTHORIZATION, "")).thenReturn("token"); + Mockito.when(bufferedReader.readLine()).thenReturn("token"); + Mockito.when(jsonReader.readObject()).thenThrow(e); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); + commandLineApiHandler.call(); + } 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/local_api/ConfigApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ConfigApiHandlerTest.java index 4fd733e2..9971dc70 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,271 +1,248 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import com.fasterxml.jackson.databind.ObjectMapper; -//import io.netty.buffer.ByteBuf; -//import io.netty.handler.codec.http.*; -//import org.eclipse.iofog.command_line.CommandLineParser; -//import org.eclipse.iofog.utils.configuration.Configuration; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import javax.json.Json; -//import javax.json.JsonObject; -//import javax.json.JsonReader; -//import java.io.StringReader; -//import java.util.HashMap; -// -//import static io.netty.handler.codec.http.HttpMethod.POST; -//import static io.netty.handler.codec.http.HttpResponseStatus.*; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static org.junit.Assert.*; -//import static org.powermock.api.mockito.Mockito.verify; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({ConfigApiHandler.class, HttpRequest.class, ByteBuf.class, LoggingService.class, ApiHandlerHelpers.class, -// HttpHeaders.class, Json.class, JsonReader.class, JsonObject.class, CommandLineParser.class, Configuration.class}) -//@Ignore -//public class ConfigApiHandlerTest { -// private HttpRequest httpRequest; -// private ByteBuf byteBuf; -// private String content; -// private byte[] bytes; -// private DefaultFullHttpResponse defaultResponse; -// private ConfigApiHandler configApiHandler; -// private String contentType; -// private HttpHeaders httpHeaders; -// private JsonReader jsonReader; -// private JsonObject jsonObject; -// private String commandLineOutput; -// private ObjectMapper objectMapper; -// private HashMap responseMap; -// -// @Before -// public void setUp() throws Exception { -// httpRequest = Mockito.mock(HttpRequest.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// httpHeaders = Mockito.mock(HttpHeaders.class); -// jsonReader = Mockito.mock(JsonReader.class); -// jsonObject = Mockito.mock(JsonObject.class); -// objectMapper = new ObjectMapper(); -// responseMap = new HashMap<>(); -// commandLineOutput = "success help"; -// content = "content"; -// contentType = "application/json"; -// bytes = content.getBytes(); -// Mockito.mockStatic(ApiHandlerHelpers.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(Json.class); -// Mockito.mockStatic(CommandLineParser.class); -// Mockito.mockStatic(Configuration.class); -// configApiHandler = Mockito.spy(new ConfigApiHandler(httpRequest, byteBuf, bytes)); -// Mockito.when(ApiHandlerHelpers.validateMethod(httpRequest, POST)).thenReturn(true); -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(httpRequest.headers()).thenReturn(httpHeaders); -// Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); -// Mockito.when(httpRequest.method()).thenReturn(POST); -// Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); -// Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); -// Mockito.when(Configuration.setConfig(Mockito.anyMap(), Mockito.anyBoolean())).thenReturn(responseMap); -// } -// -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// -// @After -// public void tearDown() throws Exception { -// defaultResponse = null; -// Mockito.reset(configApiHandler, httpRequest, byteBuf); -// } -// -// /** -// * Test call when httpMethod is not valid -// */ -// @Test -// public void testCallWhenMethodTypeIsInvalid() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); -// assertEquals(defaultResponse, configApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST)); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.methodNotAllowedResponse(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when contentType is not valid -// */ -// @Test -// public void testCallWhenContentTypeIsInvalid() { -// try { -// String errorMsg = "Incorrect content type text/html"; -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(errorMsg); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, configApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test ApiHandlerHelpers.validateAccessToken returns false -// */ -// @Test -// public void testCallWhenAccessTokenIsNull() { -// try { -// String errorMsg = "Incorrect access token"; -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); -// assertEquals(defaultResponse, configApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when request is empty -// */ -// @Test -// public void testCallWhenRequestForSetConfigIsEmpty() { -// try { -// String errMsg = "Request not valid"; -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errMsg))).thenReturn(defaultResponse); -// assertEquals(defaultResponse,configApiHandler.call()); -// verifyStatic(Configuration.class, Mockito.never()); -// Configuration.setConfig(Mockito.anyMap(), Mockito.eq(false)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call Configuration.setConfig throws exception -// */ -// @Test -// public void testCallWhenRequestForSetConfigIsNotEmptyAndSetConfigThrowsException() { -// try { -// Exception exp = new Exception("Error setting configuration"); -// String errMsg = "Error updating new config " + exp.getMessage(); -// Mockito.when(jsonObject.containsKey("logs-level")).thenReturn(true); -// Mockito.when(jsonObject.getString("logs-level")).thenReturn("SEVERE"); -// Mockito.when(Configuration.setConfig(Mockito.anyMap(), Mockito.eq(false))).thenThrow(exp); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errMsg))).thenReturn(defaultResponse); -// assertEquals(defaultResponse,configApiHandler.call()); -// verifyStatic(Configuration.class); -// Configuration.setConfig(Mockito.anyMap(), Mockito.eq(false)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call Configuration.setConfig returns error -// */ -// @Test -// public void testCallWhenRequestForSetConfigReturnsError() { -// try { -// responseMap.put("ll", "Invalid input"); -// Mockito.when(jsonObject.containsKey("logs-level")).thenReturn(true); -// Mockito.when(jsonObject.getString("logs-level")).thenReturn("SEVERE"); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse,configApiHandler.call()); -// responseMap.clear(); -// responseMap.put("logs-level","Invalid input"); -// String result = objectMapper.writeValueAsString(responseMap); -// verifyStatic(Configuration.class); -// Configuration.setConfig(Mockito.anyMap(), Mockito.eq(false)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call Configuration.setConfig returns empty map -// */ -// @Test -// public void testCallWhenRequestForSetConfigReturnsEmptyMap() { -// try { -// Mockito.when(jsonObject.containsKey("logs-level")).thenReturn(true); -// Mockito.when(jsonObject.getString("logs-level")).thenReturn("SEVERE"); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse,configApiHandler.call()); -// String result = objectMapper.writeValueAsString(responseMap); -// verifyStatic(Configuration.class); -// Configuration.setConfig(Mockito.anyMap(), Mockito.eq(false)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test call when jsonReader throws exception -// */ -// @Test -// public void testCallWhenJsonReaderThrowsRuntimeException() { -// try { -// RuntimeException e = new RuntimeException("Error"); -// String errorMsg = "Log message parsing error, " + e.getMessage(); -// contentType = "application/json"; -// Mockito.when(jsonReader.readObject()).thenThrow(e); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); -// assertEquals(defaultResponse,configApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.*; +import org.eclipse.iofog.command_line.CommandLineParser; +import org.eclipse.iofog.utils.configuration.Configuration; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.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.JsonReader; +import java.io.StringReader; +import java.util.HashMap; + +import static io.netty.handler.codec.http.HttpMethod.POST; +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mockStatic; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class ConfigApiHandlerTest { + private HttpRequest httpRequest; + private ByteBuf byteBuf; + private DefaultFullHttpResponse defaultResponse; + private ConfigApiHandler configApiHandler; + private String contentType; + private JsonReader jsonReader; + private JsonObject jsonObject; + private HashMap responseMap; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic apiHandlerHelpersMockedStatic; + private MockedStatic jsonMockedStatic; + private MockedStatic commandLineParserMockedStatic; + private MockedStatic configurationMockedStatic; + + @BeforeEach + public void setUp() throws Exception { + httpRequest = Mockito.mock(HttpRequest.class); + byteBuf = Mockito.mock(ByteBuf.class); + HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class); + jsonReader = Mockito.mock(JsonReader.class); + jsonObject = Mockito.mock(JsonObject.class); + responseMap = new HashMap<>(); + String content = "content"; + contentType = "application/json"; + byte[] bytes = content.getBytes(); + apiHandlerHelpersMockedStatic = mockStatic(ApiHandlerHelpers.class); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + jsonMockedStatic = mockStatic(Json.class); + commandLineParserMockedStatic = mockStatic(CommandLineParser.class); + configurationMockedStatic = mockStatic(Configuration.class); + configApiHandler = Mockito.spy(new ConfigApiHandler(httpRequest, byteBuf, bytes)); + Mockito.when(ApiHandlerHelpers.validateMethod(httpRequest, POST)).thenReturn(true); + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(httpRequest.headers()).thenReturn(httpHeaders); + Mockito.when(httpHeaders.get(HttpHeaderNames.CONTENT_TYPE, "")).thenReturn(contentType); + Mockito.when(httpRequest.method()).thenReturn(POST); + Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); + Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); + Mockito.when(Configuration.setConfig(Mockito.anyMap(), Mockito.anyBoolean())).thenReturn(responseMap); + } + + @AfterEach + public void tearDown() throws Exception { + defaultResponse = null; + Mockito.reset(configApiHandler, httpRequest, byteBuf); + configurationMockedStatic.close(); + loggingServiceMockedStatic.close(); + apiHandlerHelpersMockedStatic.close(); + jsonMockedStatic.close(); + commandLineParserMockedStatic.close(); + + } + + /** + * Test call when httpMethod is not valid + */ + @Test + public void testCallWhenMethodTypeIsInvalid() { + try { + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(false); + Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); + assertEquals(defaultResponse, configApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST)); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.methodNotAllowedResponse(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when contentType is not valid + */ + @Test + public void testCallWhenContentTypeIsInvalid() { + try { + String errorMsg = "Incorrect content type text/html"; + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(errorMsg); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, configApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ApiHandlerHelpers.validateAccessToken returns false + */ + @Test + public void testCallWhenAccessTokenIsNull() { + try { + String errorMsg = "Incorrect access token"; + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); + Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); + assertEquals(defaultResponse, configApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when request is empty + */ + @Test + public void testCallWhenRequestForSetConfigIsEmpty() { + try { + String errMsg = "Request not valid"; + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errMsg))).thenReturn(defaultResponse); + assertEquals(defaultResponse,configApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call Configuration.setConfig throws exception + */ + @Test + public void testCallWhenRequestForSetConfigIsNotEmptyAndSetConfigThrowsException() { + try { + Exception exp = new Exception("Error setting configuration"); + String errMsg = "Error updating new config " + exp.getMessage(); + Mockito.when(jsonObject.containsKey("logs-level")).thenReturn(true); + Mockito.when(jsonObject.getString("logs-level")).thenReturn("SEVERE"); + Mockito.when(Configuration.setConfig(Mockito.anyMap(), Mockito.eq(false))).thenThrow(exp); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errMsg))).thenReturn(defaultResponse); + assertEquals(defaultResponse,configApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call Configuration.setConfig returns error + */ + @Test + public void testCallWhenRequestForSetConfigReturnsError() { + try { + responseMap.put("ll", "Invalid input"); + Mockito.when(jsonObject.containsKey("logs-level")).thenReturn(true); + Mockito.when(jsonObject.getString("logs-level")).thenReturn("SEVERE"); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse,configApiHandler.call()); + responseMap.clear(); + responseMap.put("logs-level","Invalid input"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call Configuration.setConfig returns empty map + */ + @Test + public void testCallWhenRequestForSetConfigReturnsEmptyMap() { + try { + Mockito.when(jsonObject.containsKey("logs-level")).thenReturn(true); + Mockito.when(jsonObject.getString("logs-level")).thenReturn("SEVERE"); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse,configApiHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test call when jsonReader throws exception + */ + @Test + public void testCallWhenJsonReaderThrowsRuntimeException() { + try { + RuntimeException e = new RuntimeException("Error"); + String errorMsg = "Log message parsing error, " + e.getMessage(); + contentType = "application/json"; + Mockito.when(jsonReader.readObject()).thenThrow(e); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); + assertEquals(defaultResponse,configApiHandler.call()); + } 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/local_api/ControlSignalSentInfoTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/ControlSignalSentInfoTest.java index 516c85d8..cb88f0ff 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,81 +1,84 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({ControlSignalSentInfo.class}) -//public class ControlSignalSentInfoTest { -// private ControlSignalSentInfo controlSignalSentInfo; -// private int sendTryCount = 0; -// private long timeMillis; -// -// @Before -// public void setUp() throws Exception { -// sendTryCount = 5; -// timeMillis = System.currentTimeMillis(); -// controlSignalSentInfo = Mockito.spy(new ControlSignalSentInfo(sendTryCount, timeMillis)); -// } -// -// @After -// public void tearDown() throws Exception { -// } -// -// /** -// * Test getTimeMillis -// */ -// @Test -// public void testGetTimeMillis() { -// assertEquals(timeMillis, controlSignalSentInfo.getTimeMillis()); -// } -// -// /** -// * Test setTimeMillis -// */ -// @Test -// public void testSetTimeMillis() { -// timeMillis = timeMillis + 100; -// controlSignalSentInfo.setTimeMillis(timeMillis); -// assertEquals(timeMillis, controlSignalSentInfo.getTimeMillis()); -// } -// -// /** -// * Test getSendTryCount -// */ -// @Test -// public void testGetSendTryCount() { -// assertEquals(sendTryCount, controlSignalSentInfo.getSendTryCount()); -// } -// -// /** -// * Test setSendTryCount -// */ -// @Test -// public void testSetSendTryCount() { -// sendTryCount = sendTryCount + 15; -// controlSignalSentInfo.setSendTryCount(sendTryCount); -// assertEquals(sendTryCount, controlSignalSentInfo.getSendTryCount()); -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + + +import 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.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; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class ControlSignalSentInfoTest { + private ControlSignalSentInfo controlSignalSentInfo; + private int sendTryCount = 0; + private long timeMillis; + + @BeforeEach + public void setUp() throws Exception { + sendTryCount = 5; + timeMillis = System.currentTimeMillis(); + controlSignalSentInfo = Mockito.spy(new ControlSignalSentInfo(sendTryCount, timeMillis)); + } + + @AfterEach + public void tearDown() throws Exception { + } + + /** + * Test getTimeMillis + */ + @Test + public void testGetTimeMillis() { + assertEquals(timeMillis, controlSignalSentInfo.getTimeMillis()); + } + + /** + * Test setTimeMillis + */ + @Test + public void testSetTimeMillis() { + timeMillis = timeMillis + 100; + controlSignalSentInfo.setTimeMillis(timeMillis); + assertEquals(timeMillis, controlSignalSentInfo.getTimeMillis()); + } + + /** + * Test getSendTryCount + */ + @Test + public void testGetSendTryCount() { + assertEquals(sendTryCount, controlSignalSentInfo.getSendTryCount()); + } + + /** + * Test setSendTryCount + */ + @Test + public void testSetSendTryCount() { + sendTryCount = sendTryCount + 15; + controlSignalSentInfo.setSendTryCount(sendTryCount); + assertEquals(sendTryCount, controlSignalSentInfo.getSendTryCount()); + } +} \ No newline at end of file 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 8c626eb5..dae0e678 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,347 +1,335 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.buffer.ByteBuf; -//import io.netty.buffer.ByteBufAllocator; -//import io.netty.channel.Channel; -//import io.netty.channel.ChannelFuture; -//import io.netty.channel.ChannelHandlerContext; -//import io.netty.handler.codec.http.HttpHeaders; -//import io.netty.handler.codec.http.HttpRequest; -//import io.netty.handler.codec.http.websocketx.*; -//import org.eclipse.iofog.status_reporter.StatusReporter; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import java.util.HashMap; -//import java.util.Map; -// -//import static io.netty.handler.codec.http.HttpHeaders.Names.HOST; -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({ControlWebsocketHandler.class, StatusReporter.class, LoggingService.class, WebSocketServerHandshakerFactory.class, -// WebSocketMap.class, ChannelHandlerContext.class, HttpRequest.class, HttpHeaders.class, Channel.class, WebSocketServerHandshaker00.class, -// ChannelFuture.class, LocalApiStatus.class, WebSocketFrame.class, PingWebSocketFrame.class, ByteBuf.class, -// WebsocketUtil.class, ByteBufAllocator.class, BinaryWebSocketFrame.class, CloseWebSocketFrame.class}) -//@Ignore -//public class ControlWebsocketHandlerTest { -// private ControlWebsocketHandler controlWebsocketHandler; -// private HttpRequest httpRequest; -// private HttpHeaders httpHeaders; -// private ChannelHandlerContext channelHandlerContext; -// private String MODULE_NAME; -// private Channel channel; -// private WebSocketServerHandshakerFactory webSocketServerHandshakerFactory; -// private WebSocketServerHandshaker00 handShaker; -// private ChannelFuture channelFuture; -// private LocalApiStatus localApiStatus; -// private WebSocketFrame webSocketFrame; -// private PingWebSocketFrame pingWebSocketFrame; -// private ByteBuf byteBuf; -// private ByteBufAllocator byteBufAllocator; -// private BinaryWebSocketFrame binaryWebSocketFrame; -// private CloseWebSocketFrame closeWebSocketFrame; -// private Map contextMap; -// -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "Local API"; -// httpRequest = Mockito.mock(HttpRequest.class); -// httpHeaders = Mockito.mock(HttpHeaders.class); -// webSocketServerHandshakerFactory = Mockito.mock(WebSocketServerHandshakerFactory.class); -// channel = Mockito.mock(Channel.class); -// handShaker = Mockito.mock(WebSocketServerHandshaker00.class); -// channelFuture = Mockito.mock(ChannelFuture.class); -// localApiStatus = Mockito.mock(LocalApiStatus.class); -// webSocketFrame = Mockito.mock(WebSocketFrame.class); -// pingWebSocketFrame = Mockito.mock(PingWebSocketFrame.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// byteBufAllocator = Mockito.mock(ByteBufAllocator.class); -// binaryWebSocketFrame = Mockito.mock(BinaryWebSocketFrame.class); -// closeWebSocketFrame = Mockito.mock(CloseWebSocketFrame.class); -// contextMap = new HashMap<>(); -// Mockito.mockStatic(StatusReporter.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(WebsocketUtil.class); -// Mockito.mockStatic(WebSocketServerHandshakerFactory.class); -// channelHandlerContext = Mockito.mock(ChannelHandlerContext.class); -// controlWebsocketHandler = Mockito.spy(new ControlWebsocketHandler()); -// Mockito.when(httpRequest.uri()).thenReturn("http://localhost:54321/token/qwld"); -// Mockito.when(channelHandlerContext.channel()).thenReturn(channel); -// Mockito.when(httpRequest.headers()).thenReturn(httpHeaders); -// Mockito.when(httpHeaders.get(HOST)).thenReturn("host"); +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.http.HttpHeaders; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.handler.codec.http.websocketx.*; +import org.eclipse.iofog.status_reporter.StatusReporter; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.HashMap; +import java.util.Map; +import static io.netty.handler.codec.http.HttpHeaders.Names.HOST; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.never; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class ControlWebsocketHandlerTest { + private ControlWebsocketHandler controlWebsocketHandler; + private HttpRequest httpRequest; + private ChannelHandlerContext channelHandlerContext; + private String MODULE_NAME; + private Channel channel; + private WebSocketServerHandshakerFactory webSocketServerHandshakerFactory; + private WebSocketServerHandshaker00 handShaker; + private LocalApiStatus localApiStatus; + private WebSocketFrame webSocketFrame; + private PingWebSocketFrame pingWebSocketFrame; + private ByteBuf byteBuf; + private BinaryWebSocketFrame binaryWebSocketFrame; + private CloseWebSocketFrame closeWebSocketFrame; + private MockedStatic statusReporterMockedStatic; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic websocketUtilMockedStatic; + private MockedStatic webSocketServerHandshakerFactoryMockedStatic; + private MockedConstruction webSocketServerHandshakerFactoryMockedConstruction; + + //global timeout rule + + @BeforeEach + public void setUp() throws Exception { + MODULE_NAME = "Local API"; + httpRequest = Mockito.mock(HttpRequest.class); + HttpHeaders httpHeaders = Mockito.mock(HttpHeaders.class); + webSocketServerHandshakerFactory = Mockito.mock(WebSocketServerHandshakerFactory.class); + channel = Mockito.mock(Channel.class); + handShaker = Mockito.mock(WebSocketServerHandshaker00.class); + ChannelFuture channelFuture = Mockito.mock(ChannelFuture.class); + localApiStatus = Mockito.mock(LocalApiStatus.class); + webSocketFrame = Mockito.mock(WebSocketFrame.class); + pingWebSocketFrame = Mockito.mock(PingWebSocketFrame.class); + byteBuf = Mockito.mock(ByteBuf.class); + ByteBufAllocator byteBufAllocator = Mockito.mock(ByteBufAllocator.class); + binaryWebSocketFrame = Mockito.mock(BinaryWebSocketFrame.class); + closeWebSocketFrame = Mockito.mock(CloseWebSocketFrame.class); + statusReporterMockedStatic = Mockito.mockStatic(StatusReporter.class); + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + websocketUtilMockedStatic = Mockito.mockStatic(WebsocketUtil.class); + webSocketServerHandshakerFactoryMockedStatic = Mockito.mockStatic(WebSocketServerHandshakerFactory.class); + channelHandlerContext = Mockito.mock(ChannelHandlerContext.class); + controlWebsocketHandler = Mockito.spy(new ControlWebsocketHandler()); + Mockito.when(httpRequest.uri()).thenReturn("http://localhost:54321/token/qwld"); + Mockito.when(channelHandlerContext.channel()).thenReturn(channel); + Mockito.when(httpRequest.headers()).thenReturn(httpHeaders); + Mockito.when(httpHeaders.get(HOST)).thenReturn("host"); + 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); -// Mockito.when(channelHandlerContext.alloc()).thenReturn(byteBufAllocator); -// Mockito.when(byteBufAllocator.buffer()).thenReturn(byteBuf); -// } -// -// @After -// public void tearDown() throws Exception { -// MODULE_NAME = null; -// Mockito.reset(controlWebsocketHandler, httpRequest, byteBuf); -// WebSocketMap.controlWebsocketMap.remove(channelHandlerContext); -// } -// -// /** -// * Test handle when ChannelHandlerContext and httpsRequest is Null -// */ -// @Test -// public void testHandleWhenReqAndContextAreNull() { -// controlWebsocketHandler.handle(null, null); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(Mockito.eq(MODULE_NAME), Mockito.eq("Error in Handler to open the websocket for the real-time control signals"), -// Mockito.any()); -// } -// -// /** -// * Test handle when ChannelHandlerContext and httpsRequest are not Null -// * & token is less than 5 -// */ -// @Test -// public void testHandleWhenReqAndContextAreNotNullAndTokenIsLessThan5() { -// Mockito.when(httpRequest.uri()).thenReturn("http://localhost:54321/qwld"); -// controlWebsocketHandler.handle(channelHandlerContext, httpRequest); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(Mockito.eq(MODULE_NAME), Mockito.eq(" Missing ID or ID value in URL "), -// Mockito.any()); -// } -// -// /** -// * Test handle when ChannelHandlerContext and httpsRequest are not Null -// * & token is greater than 5 & WebSocketServerHandshaker is not null -// */ -// @Test -// public void testHandleWhenReqAndContextAreNotNullAndTokenIsNotLessThan5() { -// try { -// controlWebsocketHandler.handle(channelHandlerContext, httpRequest); -// Mockito.verifyNew(WebSocketServerHandshakerFactory.class) -// .withArguments(Mockito.eq("ws://host/v2/control/socket"), Mockito.eq(null), Mockito.eq(true), Mockito.eq(Integer.MAX_VALUE)); -// Mockito.verify(webSocketServerHandshakerFactory).newHandshaker(Mockito.eq(httpRequest)); -// Mockito.verify(handShaker).handshake(Mockito.eq(channel), Mockito.eq(httpRequest)); -// Mockito.verify(StatusReporter.class); -// StatusReporter.setLocalApiStatus(); -// Mockito.verify(localApiStatus).setOpenConfigSocketsCount(Mockito.eq(WebSocketMap.controlWebsocketMap.size())); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test handle when ChannelHandlerContext and httpsRequest are not Null -// * & token is greater than 5 & WebSocketServerHandshaker is null -// */ -// @Test -// public void testHandleWhenReqAndContextAreNotNullAndWebSocketServerHandShakerIsNull() { -// try { -// Mockito.doReturn(null).when(webSocketServerHandshakerFactory).newHandshaker(Mockito.any(HttpRequest.class)); -// controlWebsocketHandler.handle(channelHandlerContext, httpRequest); -// Mockito.verifyNew(WebSocketServerHandshakerFactory.class) -// .withArguments(Mockito.eq("ws://host/v2/control/socket"), Mockito.eq(null), Mockito.eq(true), Mockito.eq(Integer.MAX_VALUE)); -// Mockito.verify(webSocketServerHandshakerFactory).newHandshaker(Mockito.eq(httpRequest)); -// Mockito.verify(WebSocketServerHandshakerFactory.class); -// WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(channel); -// Mockito.verify(StatusReporter.class); -// StatusReporter.setLocalApiStatus(); -// Mockito.verify(localApiStatus).setOpenConfigSocketsCount(Mockito.eq(WebSocketMap.controlWebsocketMap.size())); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test handleWebSocketFrame when WebSocketFrame is null -// */ -// @Test -// public void testHandleWebSocketFrameWhenWebSocketFrameIsNull() { -// controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, null); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Send control signals to container on configuration change"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Finished handling the websocket frame"); -// } -// -// /** -// * Test handleWebSocketFrame when WebSocketFrame is not null -// */ -// @Test -// public void testHandleWebSocketFrameWhenWebSocketFrameIsNotNull() { -// controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, webSocketFrame); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Send control signals to container on configuration change"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Finished handling the websocket frame"); -// } -// -// /** -// * Test handleWebSocketFrame when WebSocketFrame is pingWebSocketFrame & readableBytes ==1 -// * has open real-time websocket -// */ -// @Test -// public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfPingWebSocketFrame() { -// Mockito.when(pingWebSocketFrame.content()).thenReturn(byteBuf); -// Mockito.when(byteBuf.readableBytes()).thenReturn(1); -// Mockito.when(byteBuf.readByte()).thenReturn((byte)9); -// controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, pingWebSocketFrame); -// Mockito.verify(pingWebSocketFrame).content(); -// Mockito.verify(byteBuf).readableBytes(); -// Mockito.verify(channelHandlerContext).alloc(); -// Mockito.verify(WebsocketUtil.class); -// WebsocketUtil.hasContextInMap(Mockito.eq(channelHandlerContext), Mockito.eq(WebSocketMap.controlWebsocketMap)); -// } -// -// /** -// * Test handleWebSocketFrame when WebSocketFrame is pingWebSocketFrame & readableBytes == 0 -// * has open real-time websocket -// */ -// @Test -// public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfPingWebSocketFrameAndReadableBytesIs0() { -// Mockito.when(pingWebSocketFrame.content()).thenReturn(byteBuf); -// Mockito.when(byteBuf.readableBytes()).thenReturn(0); -// Mockito.when(byteBuf.readByte()).thenReturn((byte)9); -// controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, pingWebSocketFrame); -// Mockito.verify(pingWebSocketFrame).content(); -// Mockito.verify(WebsocketUtil.class, Mockito.never()); -// WebsocketUtil.hasContextInMap(Mockito.eq(channelHandlerContext), Mockito.eq(WebSocketMap.controlWebsocketMap)); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Ping opcode not found"); -// } -// -// /** -// * Test handleWebSocketFrame when binaryWebSocketFrame & -// * readableBytes 9 -// */ -// @Test -// public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfbinaryWebSocketFrame() { -// Mockito.when(binaryWebSocketFrame.content()).thenReturn(byteBuf); -// Mockito.when(byteBuf.readableBytes()).thenReturn(1); -// Mockito.when(byteBuf.readByte()).thenReturn((byte)9); -// controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, binaryWebSocketFrame); -// Mockito.verify(binaryWebSocketFrame).content(); -// Mockito.verify(byteBuf).readableBytes(); -// Mockito.verify(byteBuf).readByte(); -// } -// -// /** -// * Test handleWebSocketFrame when binaryWebSocketFrame & -// * readableBytes 11 -// */ -// @Test -// public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfCloseWebSocketFrame() { -// Mockito.when(binaryWebSocketFrame.content()).thenReturn(byteBuf); -// Mockito.when(byteBuf.readableBytes()).thenReturn(1); -// Mockito.when(byteBuf.readByte()).thenReturn((byte)11); -// controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, binaryWebSocketFrame); -// Mockito.verify(binaryWebSocketFrame).content(); -// Mockito.verify(byteBuf).readableBytes(); -// Mockito.verify(byteBuf).readByte(); -// } -// -// /** -// * Test handleWebSocketFrame when binaryWebSocketFrame & -// * readableBytes 9 -// */ -// @Test -// public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfbinaryWebSocketFrameAndByteIs11() { -// try { -// Mockito.when(closeWebSocketFrame.content()).thenReturn(byteBuf); -// Mockito.when(channelHandlerContext.channel()).thenReturn(channel); -// Mockito.doNothing().when(WebsocketUtil.class, "removeWebsocketContextFromMap", Mockito.any(), Mockito.any()); -// controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, closeWebSocketFrame); -// Mockito.verify(WebsocketUtil.class); -// WebsocketUtil.removeWebsocketContextFromMap(Mockito.eq(channelHandlerContext), Mockito.eq(WebSocketMap.controlWebsocketMap)); -// Mockito.verify(StatusReporter.class); -// StatusReporter.setLocalApiStatus(); -// } catch (Exception e){ -// fail("This should not happen"); -// } -// } -// -// /** -// * Test initiateControlSignal when map is null -// */ -// @Test -// public void testInitiateControlSignalWhenOldAndNewConfigMapIsNull() { -// controlWebsocketHandler.initiateControlSignal(null, null); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Start Helper method to compare the configuration map control signals"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Finished Helper method to compare the configuration map control signals"); -// } -// -// /** -// * Test initiateControlSignal when controlWebsocketMap has different value than changedConfigElmtsList -// */ -// @Test -// public void testInitiateControlSignalWhenControlWebsocketMapHasDifferentValue() { -// Map newConfigMap = new HashMap<>(); -// newConfigMap.put("log-level", "INFO"); -// Map oldConfigMap = new HashMap<>(); -// oldConfigMap.put("log-level", "SEVERE"); -// WebSocketMap.addWebsocket('C', "log-directory", channelHandlerContext); -// controlWebsocketHandler.initiateControlSignal(oldConfigMap, newConfigMap); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Start Helper method to compare the configuration map control signals"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Finished Helper method to compare the configuration map control signals"); -// } -// -// /** -// * Test initiateControlSignal when controlWebsocketMap has different value than changedConfigElmtsList -// */ -// @Test -// public void testInitiateControlSignalWhenOldAndNewConfigMapHasDifferentValue() { -// Map newConfigMap = new HashMap<>(); -// newConfigMap.put("log-level", "INFO"); -// Map oldConfigMap = new HashMap<>(); -// oldConfigMap.put("log-directory", "SEVERE"); -// WebSocketMap.addWebsocket('C', "log-directory", channelHandlerContext); -// controlWebsocketHandler.initiateControlSignal(oldConfigMap, newConfigMap); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Start Helper method to compare the configuration map control signals"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Finished Helper method to compare the configuration map control signals"); -// } -// -// @Test -// public void testInitiateControlSignalWhenControlWebsocketMapHasSameValue() { -// Map newConfigMap = new HashMap<>(); -// newConfigMap.put("log-level", "INFO"); -// Map oldConfigMap = new HashMap<>(); -// newConfigMap.put("log-level", "SEVERE"); -// WebSocketMap.addWebsocket('C', "log-level", channelHandlerContext); -// controlWebsocketHandler.initiateControlSignal(oldConfigMap, newConfigMap); -// Mockito.verify(channelHandlerContext).alloc(); -// Mockito.verify(byteBuf).writeByte(Mockito.eq(0xC)); -// } -//} \ No newline at end of file + 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); + Mockito.when(channelHandlerContext.alloc()).thenReturn(byteBufAllocator); + Mockito.when(byteBufAllocator.buffer()).thenReturn(byteBuf); + } + + @AfterEach + public void tearDown() throws Exception { + MODULE_NAME = null; + WebSocketMap.controlWebsocketMap.remove(channelHandlerContext); + Mockito.reset(controlWebsocketHandler, httpRequest, byteBuf); + statusReporterMockedStatic.close(); + loggingServiceMockedStatic.close(); + websocketUtilMockedStatic.close(); + webSocketServerHandshakerFactoryMockedStatic.close(); + webSocketServerHandshakerFactoryMockedConstruction.close(); + } + + /** + * Test handle when ChannelHandlerContext and httpsRequest is Null + */ + @Test + public void testHandleWhenReqAndContextAreNull() { + controlWebsocketHandler.handle(null, null); + Mockito.verify(LoggingService.class); + LoggingService.logError(Mockito.eq(MODULE_NAME), Mockito.eq("Error in Handler to open the websocket for the real-time control signals"), + Mockito.any()); + } + + /** + * Test handle when ChannelHandlerContext and httpsRequest are not Null + * & token is less than 5 + */ + @Test + public void testHandleWhenReqAndContextAreNotNullAndTokenIsLessThan5() { + Mockito.when(httpRequest.uri()).thenReturn("http://localhost:54321/qwld"); + controlWebsocketHandler.handle(channelHandlerContext, httpRequest); + Mockito.verify(LoggingService.class); + LoggingService.logError(Mockito.eq(MODULE_NAME), Mockito.eq(" Missing ID or ID value in URL "), + Mockito.any()); + } + + /** + * Test handle when ChannelHandlerContext and httpsRequest are not Null + * & token is greater than 5 & WebSocketServerHandshaker is not null + */ + @Test + 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(); + Mockito.verify(localApiStatus).setOpenConfigSocketsCount(Mockito.eq(WebSocketMap.controlWebsocketMap.size())); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test handle when ChannelHandlerContext and httpsRequest are not Null + * & token is greater than 5 & WebSocketServerHandshaker is null + */ + @Test + public void testHandleWhenReqAndContextAreNotNullAndWebSocketServerHandShakerIsNull() { + try { + Mockito.doReturn(null).when(webSocketServerHandshakerFactory).newHandshaker(Mockito.any(HttpRequest.class)); + controlWebsocketHandler.handle(channelHandlerContext, httpRequest); + Mockito.verify(StatusReporter.class); + StatusReporter.setLocalApiStatus(); + Mockito.verify(localApiStatus).setOpenConfigSocketsCount(Mockito.eq(WebSocketMap.controlWebsocketMap.size())); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test handleWebSocketFrame when WebSocketFrame is null + */ + @Test + public void testHandleWebSocketFrameWhenWebSocketFrameIsNull() { + controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, null); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Send control signals to container on configuration change"); + } + + /** + * Test handleWebSocketFrame when WebSocketFrame is not null + */ + @Test + public void testHandleWebSocketFrameWhenWebSocketFrameIsNotNull() { + controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, webSocketFrame); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Send control signals to container on configuration change"); + } + + /** + * Test handleWebSocketFrame when WebSocketFrame is pingWebSocketFrame & readableBytes ==1 + * has open real-time websocket + */ + @Test + public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfPingWebSocketFrame() { + Mockito.when(pingWebSocketFrame.content()).thenReturn(byteBuf); + Mockito.when(byteBuf.readableBytes()).thenReturn(1); + Mockito.when(byteBuf.readByte()).thenReturn((byte)9); + controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, pingWebSocketFrame); + Mockito.verify(pingWebSocketFrame).content(); + Mockito.verify(byteBuf).readableBytes(); + Mockito.verify(channelHandlerContext).alloc(); + Mockito.verify(WebsocketUtil.class); + WebsocketUtil.hasContextInMap(Mockito.eq(channelHandlerContext), Mockito.eq(WebSocketMap.controlWebsocketMap)); + } + + /** + * Test handleWebSocketFrame when WebSocketFrame is pingWebSocketFrame & readableBytes == 0 + * has open real-time websocket + */ + @Test + public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfPingWebSocketFrameAndReadableBytesIs0() { + Mockito.when(pingWebSocketFrame.content()).thenReturn(byteBuf); + Mockito.when(byteBuf.readableBytes()).thenReturn(0); + Mockito.when(byteBuf.readByte()).thenReturn((byte)9); + controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, pingWebSocketFrame); + Mockito.verify(pingWebSocketFrame).content(); + Mockito.verify(WebsocketUtil.class, Mockito.never()); + WebsocketUtil.hasContextInMap(Mockito.eq(channelHandlerContext), Mockito.eq(WebSocketMap.controlWebsocketMap)); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Opcode not found for sending control signal"); + } + + /** + * Test handleWebSocketFrame when binaryWebSocketFrame & + * readableBytes 9 + */ + @Test + public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfbinaryWebSocketFrame() { + Mockito.when(binaryWebSocketFrame.content()).thenReturn(byteBuf); + Mockito.when(byteBuf.readableBytes()).thenReturn(1); + Mockito.when(byteBuf.readByte()).thenReturn((byte)9); + controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, binaryWebSocketFrame); + Mockito.verify(binaryWebSocketFrame).content(); + Mockito.verify(byteBuf).readableBytes(); + Mockito.verify(byteBuf).readByte(); + } + + /** + * Test handleWebSocketFrame when binaryWebSocketFrame & + * readableBytes 11 + */ + @Test + public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfCloseWebSocketFrame() { + Mockito.when(binaryWebSocketFrame.content()).thenReturn(byteBuf); + Mockito.when(byteBuf.readableBytes()).thenReturn(1); + Mockito.when(byteBuf.readByte()).thenReturn((byte)11); + controlWebsocketHandler.handleWebSocketFrame(channelHandlerContext, binaryWebSocketFrame); + Mockito.verify(binaryWebSocketFrame).content(); + Mockito.verify(byteBuf).readableBytes(); + Mockito.verify(byteBuf).readByte(); + } + + /** + * Test handleWebSocketFrame when binaryWebSocketFrame & + * readableBytes 9 + */ + @Test + public void testHandleWebSocketFrameWhenWebSocketFrameIsInstanceOfbinaryWebSocketFrameAndByteIs11() { + 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)); + Mockito.verify(StatusReporter.class); + StatusReporter.setLocalApiStatus(); + } catch (Exception e){ + fail("This should not happen"); + } + } + + /** + * Test initiateControlSignal when map is null + */ + @Test + public void testInitiateControlSignalWhenOldAndNewConfigMapIsNull() { + controlWebsocketHandler.initiateControlSignal(null, null); + Mockito.verify(WebsocketUtil.class, never()); + WebsocketUtil.removeWebsocketContextFromMap(Mockito.eq(channelHandlerContext), + Mockito.eq(WebSocketMap.controlWebsocketMap)); + } + + /** + * Test initiateControlSignal when controlWebsocketMap has different value than changedConfigElmtsList + */ + @Test + public void testInitiateControlSignalWhenControlWebsocketMapHasDifferentValue() { + Map newConfigMap = new HashMap<>(); + newConfigMap.put("log-level", "INFO"); + Map oldConfigMap = new HashMap<>(); + oldConfigMap.put("log-level", "SEVERE"); + WebSocketMap.addWebsocket('C', "log-directory", channelHandlerContext); + controlWebsocketHandler.initiateControlSignal(oldConfigMap, newConfigMap); + } + + /** + * Test initiateControlSignal when controlWebsocketMap has different value than changedConfigElmtsList + */ + @Test + public void testInitiateControlSignalWhenOldAndNewConfigMapHasDifferentValue() { + Map newConfigMap = new HashMap<>(); + newConfigMap.put("log-level", "INFO"); + Map oldConfigMap = new HashMap<>(); + oldConfigMap.put("log-directory", "SEVERE"); + WebSocketMap.addWebsocket('C', "log-directory", channelHandlerContext); + controlWebsocketHandler.initiateControlSignal(oldConfigMap, newConfigMap); + } + + @Test + public void testInitiateControlSignalWhenControlWebsocketMapHasSameValue() { + Map newConfigMap = new HashMap<>(); + newConfigMap.put("log-level", "INFO"); + Map oldConfigMap = new HashMap<>(); + newConfigMap.put("log-level", "SEVERE"); + WebSocketMap.addWebsocket('C', "log-level", channelHandlerContext); + controlWebsocketHandler.initiateControlSignal(oldConfigMap, newConfigMap); + Mockito.verify(channelHandlerContext).alloc(); + Mockito.verify(byteBuf).writeByte(Mockito.eq(0xC)); + } +} \ No newline at end of file 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 adc38537..9510f589 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,126 +1,127 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.buffer.ByteBuf; -//import io.netty.buffer.ByteBufAllocator; -//import io.netty.channel.Channel; -//import io.netty.channel.ChannelHandlerContext; -//import org.eclipse.iofog.status_reporter.StatusReporter; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({ControlWebsocketWorker.class, LoggingService.class, ChannelHandlerContext.class, ControlSignalSentInfo.class, -// ByteBufAllocator.class, ByteBuf.class, Channel.class, WebsocketUtil.class, StatusReporter.class, LocalApiStatus.class}) -//@Ignore -//public class ControlWebsocketWorkerTest { -// private String MODULE_NAME; -// private ControlWebsocketWorker controlWebsocketWorker; -// private ChannelHandlerContext context; -// private ControlSignalSentInfo controlSignalSentInfo; -// private ByteBufAllocator byteBufAllocator; -// private ByteBuf byteBuf; -// private Channel channel; -// private LocalApiStatus localApiStatus; -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "Local API"; -// context = Mockito.mock(ChannelHandlerContext.class); -// channel = Mockito.mock(Channel.class); -// byteBufAllocator = Mockito.mock(ByteBufAllocator.class); -// controlSignalSentInfo = Mockito.mock(ControlSignalSentInfo.class); -// localApiStatus = Mockito.mock(LocalApiStatus.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(StatusReporter.class); -// Mockito.mockStatic(WebsocketUtil.class); -// controlWebsocketWorker = Mockito.spy(new ControlWebsocketWorker()); -// byteBuf = Mockito.mock(ByteBuf.class); -// Mockito.when(context.alloc()).thenReturn(byteBufAllocator); -// Mockito.when(byteBufAllocator.buffer()).thenReturn(byteBuf); -// Mockito.when(context.channel()).thenReturn(channel); -// Mockito.when(StatusReporter.setLocalApiStatus()).thenReturn(localApiStatus); -// -// } -// -// @After -// public void tearDown() throws Exception { -// Mockito.reset(controlWebsocketWorker, controlSignalSentInfo); -// WebSocketMap.unackControlSignalsMap.remove(context); -// } -// -// /** -// * Test run when WebSocketMap.unackControlSignalsMap is empty -// */ -// @Test -// public void testRunWhenUnackControlSignalsMapIsEmpty() { -// controlWebsocketWorker.run(); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME,"Initiating control signals for unacknowledged signals"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME,"Finished Initiating control signals for unacknowledged signals"); -// } -// -// /** -// * Test run when WebSocketMap.unackControlSignalsMap is not empty -// * controlSignalSentInfo.getSendTryCount() < 10 -// */ -// @Test -// public void testRunWhenUnackControlSignalsMapIsNotEmpty() { -// try { -// WebSocketMap.unackControlSignalsMap.put(context, controlSignalSentInfo); -// controlWebsocketWorker.run(); -// Mockito.verify(controlSignalSentInfo, Mockito.atLeastOnce()).getSendTryCount(); -// Mockito.verifyPrivate(controlWebsocketWorker).invoke("initiateControlSignal", Mockito.eq(context)); -// Mockito.verify(context).alloc(); -// Mockito.verify(context).channel(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test run when WebSocketMap.unackControlSignalsMap is not empty -// * controlSignalSentInfo.getSendTryCount() > 10 -// */ -// @Test -// public void testRunWhenUnackControlSignalsMapIsNotEmptyAndSendTryCountIsGreaterThan10() { -// try { -// WebSocketMap.unackControlSignalsMap.put(context, controlSignalSentInfo); -// Mockito.when(controlSignalSentInfo.getSendTryCount()).thenReturn(11); -// controlWebsocketWorker.run(); -// Mockito.verify(controlSignalSentInfo, Mockito.atLeastOnce()).getSendTryCount(); -// Mockito.verifyPrivate(controlWebsocketWorker, Mockito.never()).invoke("initiateControlSignal", Mockito.eq(context)); -// Mockito.verify(WebsocketUtil.class); -// WebsocketUtil.removeWebsocketContextFromMap(Mockito.eq(context), Mockito.eq(WebSocketMap.controlWebsocketMap)); -// Mockito.verify(localApiStatus).setOpenConfigSocketsCount(Mockito.eq(WebSocketMap.controlWebsocketMap.size())); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import org.eclipse.iofog.status_reporter.StatusReporter; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.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.fail; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class ControlWebsocketWorkerTest { + private String MODULE_NAME; + 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; + private MockedStatic websocketUtilMockedStatic; + @BeforeEach + public void setUp() throws Exception { + MODULE_NAME = "Local API"; + context = Mockito.mock(ChannelHandlerContext.class); + channel = Mockito.mock(Channel.class); + 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); + Mockito.when(context.alloc()).thenReturn(byteBufAllocator); + Mockito.when(byteBufAllocator.buffer()).thenReturn(byteBuf); + Mockito.when(context.channel()).thenReturn(channel); + Mockito.when(StatusReporter.setLocalApiStatus()).thenReturn(localApiStatus); + + } + + @AfterEach + public void tearDown() throws Exception { + Mockito.reset(controlWebsocketWorker, controlSignalSentInfo); + WebSocketMap.unackControlSignalsMap.remove(context); + statusReporterMockedStatic.close(); + loggingServiceMockedStatic.close(); + websocketUtilMockedStatic.close(); + } + + /** + * Test run when WebSocketMap.unackControlSignalsMap is empty + */ + @Test + public void testRunWhenUnackControlSignalsMapIsEmpty() { + controlWebsocketWorker.run(); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME,"Initiating control signals for unacknowledged signals"); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME,"Finished Initiating control signals for unacknowledged signals"); + } + + /** + * Test run when WebSocketMap.unackControlSignalsMap is not empty + * controlSignalSentInfo.getSendTryCount() < 10 + */ + @Test + public void testRunWhenUnackControlSignalsMapIsNotEmpty() { + try { + WebSocketMap.unackControlSignalsMap.put(context, controlSignalSentInfo); + controlWebsocketWorker.run(); + Mockito.verify(controlSignalSentInfo, Mockito.atLeastOnce()).getSendTryCount(); + Mockito.verify(context).alloc(); + Mockito.verify(context).channel(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test run when WebSocketMap.unackControlSignalsMap is not empty + * controlSignalSentInfo.getSendTryCount() > 10 + */ + @Test + public void testRunWhenUnackControlSignalsMapIsNotEmptyAndSendTryCountIsGreaterThan10() { + try { + WebSocketMap.unackControlSignalsMap.put(context, controlSignalSentInfo); + Mockito.when(controlSignalSentInfo.getSendTryCount()).thenReturn(11); + controlWebsocketWorker.run(); + Mockito.verify(controlSignalSentInfo, Mockito.atLeastOnce()).getSendTryCount(); + Mockito.verify(WebsocketUtil.class); + WebsocketUtil.removeWebsocketContextFromMap(Mockito.eq(context), Mockito.eq(WebSocketMap.controlWebsocketMap)); + Mockito.verify(localApiStatus).setOpenConfigSocketsCount(Mockito.eq(WebSocketMap.controlWebsocketMap.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/local_api/DeprovisionApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/DeprovisionApiHandlerTest.java index 39bf87dc..7eb683e9 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,191 +1,185 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.buffer.ByteBuf; -//import io.netty.handler.codec.http.DefaultFullHttpResponse; -//import io.netty.handler.codec.http.HttpMethod; -//import io.netty.handler.codec.http.HttpRequest; -//import io.netty.handler.codec.http.HttpUtil; -//import org.eclipse.iofog.field_agent.FieldAgent; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import java.util.concurrent.ExecutorService; -//import java.util.concurrent.Executors; -// -//import static io.netty.handler.codec.http.HttpMethod.DELETE; -//import static io.netty.handler.codec.http.HttpMethod.POST; -//import static io.netty.handler.codec.http.HttpResponseStatus.*; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static org.junit.Assert.*; -//import static org.powermock.api.mockito.Mockito.mock; -//import static org.powermock.api.mockito.Mockito.verify; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({DeprovisionApiHandler.class, ApiHandlerHelpers.class, LoggingService.class, FieldAgent.class}) -//@Ignore -//public class DeprovisionApiHandlerTest { -// private DeprovisionApiHandler deprovisionApiHandler; -// private HttpRequest httpRequest; -// private ByteBuf byteBuf; -// private String content; -// private byte[] bytes; -// private DefaultFullHttpResponse defaultResponse; -// private FieldAgent fieldAgent; -// private ExecutorService executor; -// -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// -// @Before -// public void setUp() throws Exception { -// executor = Executors.newFixedThreadPool(1); -// Mockito.mockStatic(ApiHandlerHelpers.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(FieldAgent.class); -// httpRequest = Mockito.mock(HttpRequest.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// fieldAgent = Mockito.mock(FieldAgent.class); -// content = "content"; -// bytes = content.getBytes(); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// deprovisionApiHandler = Mockito.spy(new DeprovisionApiHandler(httpRequest, byteBuf, bytes)); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(DELETE))).thenReturn(true); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); -// Mockito.when(FieldAgent.getInstance()).thenReturn(fieldAgent); -// } -// -// @After -// public void tearDown() throws Exception { -// executor.shutdown(); -// deprovisionApiHandler = null; -// httpRequest = null; -// byteBuf = null; -// defaultResponse = null; -// bytes = null; -// content = null; -// } -// -// /** -// * Test call when httpMethod is not valid -// */ -// @Test -// public void testCallWhenMethodTypeIsInvalid() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(DELETE))).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); -// assertEquals(defaultResponse, deprovisionApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(DELETE)); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.methodNotAllowedResponse(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test ApiHandlerHelpers.validateAccessToken returns false -// */ -// @Test -// public void testCallWhenAccessTokenIsNull() { -// try { -// String errorMsg = "Incorrect access token"; -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); -// assertEquals(defaultResponse, deprovisionApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test deprovisionApiHandler.call when FieldAgent deprovision response is failure -// */ -// @Test -// public void testCallWhenFieldAgentDeprovisionReturnsFailureStatus() { -// try { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, byteBuf); -// Mockito.when(ApiHandlerHelpers.internalServerErrorResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); -// Mockito.when(fieldAgent.deProvision(false)).thenReturn("\nFailure - not provisioned"); -// assertEquals(defaultResponse, deprovisionApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.internalServerErrorResponse(Mockito.eq(byteBuf), Mockito.anyString()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test deprovisionApiHandler.call when FieldAgent deprovision throws exception -// */ -// @Test -// public void testCallWhenFieldAgentDeprovisionThrowsException() { -// try { -// RuntimeException e = new RuntimeException("Error while deprovisioning"); -// String errorMsg = "Log message parsing error, " + e.getMessage(); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); -// Mockito.when(fieldAgent.deProvision(false)).thenThrow(e); -// assertEquals(defaultResponse, deprovisionApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test deprovisionApiHandler.call when FieldAgent deprovision response is success -// */ -// @Test -// public void testCallWhenFieldAgentDeprovisionReturnsFailureStatusIsNull() { -// try { -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); -// Mockito.when(fieldAgent.deProvision(false)).thenReturn("\nSuccess - tokens, identifiers and keys removed"); -// assertEquals(defaultResponse, deprovisionApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(DELETE)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.anyString()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpRequest; +import io.netty.handler.codec.http.HttpUtil; +import org.eclipse.iofog.field_agent.FieldAgent; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +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; + +import static io.netty.handler.codec.http.HttpMethod.DELETE; +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class DeprovisionApiHandlerTest { + private DeprovisionApiHandler deprovisionApiHandler; + private HttpRequest httpRequest; + private ByteBuf byteBuf; + private String content; + private byte[] bytes; + private DefaultFullHttpResponse defaultResponse; + private FieldAgent fieldAgent; + private ExecutorService executor; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic apiHandlerHelpersMockedStatic; + private MockedStatic fieldAgentMockedStatic; + + + @BeforeEach + public void setUp() throws Exception { + executor = Executors.newFixedThreadPool(1); + apiHandlerHelpersMockedStatic = Mockito.mockStatic(ApiHandlerHelpers.class); + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + fieldAgentMockedStatic = Mockito.mockStatic(FieldAgent.class); + httpRequest = Mockito.mock(HttpRequest.class); + byteBuf = Mockito.mock(ByteBuf.class); + fieldAgent = Mockito.mock(FieldAgent.class); + content = "content"; + bytes = content.getBytes(); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + deprovisionApiHandler = Mockito.spy(new DeprovisionApiHandler(httpRequest, byteBuf, bytes)); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(DELETE))).thenReturn(true); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); + Mockito.when(FieldAgent.getInstance()).thenReturn(fieldAgent); + } + + @AfterEach + public void tearDown() throws Exception { + executor.shutdown(); + deprovisionApiHandler = null; + httpRequest = null; + byteBuf = null; + defaultResponse = null; + bytes = null; + content = null; + loggingServiceMockedStatic.close(); + apiHandlerHelpersMockedStatic.close(); + fieldAgentMockedStatic.close(); + } + + /** + * Test call when httpMethod is not valid + */ + @Test + public void testCallWhenMethodTypeIsInvalid() { + try { + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(DELETE))).thenReturn(false); + Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); + assertEquals(defaultResponse, deprovisionApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(DELETE)); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.methodNotAllowedResponse(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ApiHandlerHelpers.validateAccessToken returns false + */ + @Test + public void testCallWhenAccessTokenIsNull() { + try { + String errorMsg = "Incorrect access token"; + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); + Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); + assertEquals(defaultResponse, deprovisionApiHandler.call()); + ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); + ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test deprovisionApiHandler.call when FieldAgent deprovision response is failure + */ + @Test + public void testCallWhenFieldAgentDeprovisionReturnsFailureStatus() { + try { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR, byteBuf); + Mockito.when(ApiHandlerHelpers.internalServerErrorResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); + Mockito.when(fieldAgent.deProvision(false)).thenReturn("\nFailure - not provisioned"); + assertEquals(defaultResponse, deprovisionApiHandler.call()); + ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); + ApiHandlerHelpers.internalServerErrorResponse(Mockito.eq(byteBuf), Mockito.anyString()); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test deprovisionApiHandler.call when FieldAgent deprovision throws exception + */ + @Test + public void testCallWhenFieldAgentDeprovisionThrowsException() { + try { + RuntimeException e = new RuntimeException("Error while deprovisioning"); + String errorMsg = "Log message parsing error, " + e.getMessage(); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); + Mockito.when(fieldAgent.deProvision(false)).thenThrow(e); + assertEquals(defaultResponse, deprovisionApiHandler.call()); + ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test deprovisionApiHandler.call when FieldAgent deprovision response is success + */ + @Test + public void testCallWhenFieldAgentDeprovisionReturnsFailureStatusIsNull() { + try { + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.anyString())).thenReturn(defaultResponse); + Mockito.when(fieldAgent.deProvision(false)).thenReturn("\nSuccess - tokens, identifiers and keys removed"); + assertEquals(defaultResponse, deprovisionApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(DELETE)); + ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); + ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.anyString()); + } 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/local_api/GetConfigurationHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GetConfigurationHandlerTest.java index 1a819f33..18580eb9 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,212 +1,206 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.buffer.ByteBuf; -//import io.netty.handler.codec.http.DefaultFullHttpResponse; -//import io.netty.handler.codec.http.HttpMethod; -//import io.netty.handler.codec.http.HttpRequest; -//import io.netty.handler.codec.http.HttpUtil; -//import org.eclipse.iofog.field_agent.FieldAgent; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import javax.json.*; -// -//import java.io.StringReader; -//import java.util.concurrent.ExecutorService; -//import java.util.concurrent.Executors; -// -//import static io.netty.handler.codec.http.HttpMethod.DELETE; -//import static io.netty.handler.codec.http.HttpMethod.POST; -//import static io.netty.handler.codec.http.HttpResponseStatus.*; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static org.junit.Assert.*; -//import static org.powermock.api.mockito.Mockito.verify; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({GetConfigurationHandler.class, LoggingService.class, HttpRequest.class, ByteBuf.class, ApiHandlerHelpers.class, -// Json.class, JsonReader.class, JsonObject.class, JsonBuilderFactory.class, JsonObjectBuilder.class}) -//@Ignore -//public class GetConfigurationHandlerTest { -// private GetConfigurationHandler getConfigurationHandler; -// private HttpRequest httpRequest; -// private ByteBuf byteBuf; -// private String content; -// private byte[] bytes; -// private DefaultFullHttpResponse defaultResponse; -// private JsonReader jsonReader; -// private JsonObject jsonObject; -// private JsonBuilderFactory jsonBuilderFactory; -// private JsonObjectBuilder jsonObjectBuilder; -// private String result; -// private ExecutorService executor; -// -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// -// @Before -// public void setUp() throws Exception { -// executor = Executors.newFixedThreadPool(1); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(ApiHandlerHelpers.class); -// Mockito.mockStatic(Json.class); -// httpRequest = Mockito.mock(HttpRequest.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// jsonReader = Mockito.mock(JsonReader.class); -// jsonObject = Mockito.mock(JsonObject.class); -// jsonBuilderFactory = Mockito.mock(JsonBuilderFactory.class); -// jsonObjectBuilder = Mockito.mock(JsonObjectBuilder.class); -// content = "content"; -// result = "result"; -// bytes = content.getBytes(); -// getConfigurationHandler = Mockito.spy(new GetConfigurationHandler(httpRequest, byteBuf, bytes)); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(true); -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); -// Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); -// Mockito.when(Json.createBuilderFactory(Mockito.eq(null))).thenReturn(jsonBuilderFactory); -// Mockito.when(jsonBuilderFactory.createObjectBuilder()).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonObjectBuilder.build()).thenReturn(jsonObject); -// Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyString())).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); -// Mockito.when(jsonObject.toString()).thenReturn(result); -// } -// -// @After -// public void tearDown() throws Exception { -// executor.shutdown(); -// getConfigurationHandler = null; -// jsonObject = null; -// httpRequest = null; -// byteBuf = null; -// result = null; -// defaultResponse = null; -// jsonReader = null; -// bytes = null; -// content = null; -// jsonBuilderFactory = null; -// jsonObjectBuilder = null; -// } -// -// /** -// * Test call when httpMethod is not valid -// */ -// @Test -// public void testCallWhenMethodTypeIsInvalid() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); -// assertEquals(defaultResponse, getConfigurationHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST)); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.methodNotAllowedResponse(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// -// /** -// * Test call when contentType is not valid -// */ -// @Test -// public void testCallWhenContentTypeIsInvalid() { -// try { -// String errorMsg = "Incorrect content type text/html"; -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(errorMsg); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, getConfigurationHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when request is not valid jsonObject doesn't contain id -// */ -// @Test -// public void testCallWhenRequestIsNotValid() { -// try { -// String errorMsg = "Incorrect content/data, Id value not found "; -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, getConfigurationHandler.call()); -// Mockito.verifyPrivate(getConfigurationHandler, Mockito.atLeastOnce()).invoke("validateRequest", Mockito.eq(jsonObject)); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when request is valid jsonObjectcontain id & No configuration found -// */ -// @Test -// public void testCallWhenRequestIsValid() { -// try { -// Mockito.when(jsonObject.containsKey("id")).thenReturn(true); -// Mockito.when(jsonObject.isNull("id")).thenReturn(false); -// Mockito.when(jsonObject.getString("id")).thenReturn("id"); -// String errorMsg = "No configuration found for the id id"; -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, getConfigurationHandler.call()); -// Mockito.verifyPrivate(getConfigurationHandler, Mockito.atLeastOnce()).invoke("validateRequest", Mockito.eq(jsonObject)); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test call when request is valid jsonObjectcontain id & No configuration found -// */ -// @Test -// public void testCallWhenRequestIsValidAndIsPresentInConfigurationMap() { -// try { -// Mockito.when(jsonObject.containsKey("id")).thenReturn(true); -// Mockito.when(jsonObject.isNull("id")).thenReturn(false); -// Mockito.when(jsonObject.getString("id")).thenReturn("id"); -// ConfigurationMap.containerConfigMap.put("id", "value"); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.any())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, getConfigurationHandler.call()); -// Mockito.verifyPrivate(getConfigurationHandler, Mockito.atLeastOnce()).invoke("validateRequest", Mockito.eq(jsonObject)); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); -// ConfigurationMap.containerConfigMap.remove("id"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpRequest; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.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.*; + +import java.io.StringReader; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static io.netty.handler.codec.http.HttpMethod.POST; +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class GetConfigurationHandlerTest { + private GetConfigurationHandler getConfigurationHandler; + private HttpRequest httpRequest; + private ByteBuf byteBuf; + private String content; + private byte[] bytes; + private DefaultFullHttpResponse defaultResponse; + private JsonReader jsonReader; + private JsonObject jsonObject; + private JsonBuilderFactory jsonBuilderFactory; + private JsonObjectBuilder jsonObjectBuilder; + private String result; + private ExecutorService executor; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic apiHandlerHelpersMockedStatic; + private MockedStatic jsonMockedStatic; + + @BeforeEach + public void setUp() throws Exception { + executor = Executors.newFixedThreadPool(1); + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + apiHandlerHelpersMockedStatic = Mockito.mockStatic(ApiHandlerHelpers.class); + jsonMockedStatic = Mockito.mockStatic(Json.class); + httpRequest = Mockito.mock(HttpRequest.class); + byteBuf = Mockito.mock(ByteBuf.class); + jsonReader = Mockito.mock(JsonReader.class); + jsonObject = Mockito.mock(JsonObject.class); + jsonBuilderFactory = Mockito.mock(JsonBuilderFactory.class); + jsonObjectBuilder = Mockito.mock(JsonObjectBuilder.class); + content = "content"; + result = "result"; + bytes = content.getBytes(); + getConfigurationHandler = Mockito.spy(new GetConfigurationHandler(httpRequest, byteBuf, bytes)); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(true); + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); + Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); + Mockito.when(Json.createBuilderFactory(Mockito.eq(null))).thenReturn(jsonBuilderFactory); + Mockito.when(jsonBuilderFactory.createObjectBuilder()).thenReturn(jsonObjectBuilder); + Mockito.when(jsonObjectBuilder.build()).thenReturn(jsonObject); + Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyString())).thenReturn(jsonObjectBuilder); + Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); + Mockito.when(jsonObject.toString()).thenReturn(result); + } + + @AfterEach + public void tearDown() throws Exception { + jsonMockedStatic.close(); + loggingServiceMockedStatic.close(); + apiHandlerHelpersMockedStatic.close(); + executor.shutdown(); + getConfigurationHandler = null; + jsonObject = null; + httpRequest = null; + byteBuf = null; + result = null; + defaultResponse = null; + jsonReader = null; + bytes = null; + content = null; + jsonBuilderFactory = null; + jsonObjectBuilder = null; + } + + /** + * Test call when httpMethod is not valid + */ + @Test + public void testCallWhenMethodTypeIsInvalid() { + try { + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(false); + Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); + assertEquals(defaultResponse, getConfigurationHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST)); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.methodNotAllowedResponse(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + + /** + * Test call when contentType is not valid + */ + @Test + public void testCallWhenContentTypeIsInvalid() { + try { + String errorMsg = "Incorrect content type text/html"; + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(errorMsg); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, getConfigurationHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when request is not valid jsonObject doesn't contain id + */ + @Test + public void testCallWhenRequestIsNotValid() { + try { + String errorMsg = "Incorrect content/data, Id value not found "; + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, getConfigurationHandler.call()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when request is valid jsonObjectcontain id & No configuration found + */ + @Test + public void testCallWhenRequestIsValid() { + try { + Mockito.when(jsonObject.containsKey("id")).thenReturn(true); + Mockito.when(jsonObject.isNull("id")).thenReturn(false); + Mockito.when(jsonObject.getString("id")).thenReturn("id"); + String errorMsg = "No configuration found for the id id"; + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, getConfigurationHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test call when request is valid jsonObjectcontain id & No configuration found + */ + @Test + public void testCallWhenRequestIsValidAndIsPresentInConfigurationMap() { + try { + Mockito.when(jsonObject.containsKey("id")).thenReturn(true); + Mockito.when(jsonObject.isNull("id")).thenReturn(false); + Mockito.when(jsonObject.getString("id")).thenReturn("id"); + ConfigurationMap.containerConfigMap.put("id", "value"); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.any())).thenReturn(defaultResponse); + assertEquals(defaultResponse, getConfigurationHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); + ConfigurationMap.containerConfigMap.remove("id"); + } 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/local_api/GpsApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/GpsApiHandlerTest.java index 098e48c7..f5c38861 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,221 +1,225 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.buffer.ByteBuf; -//import io.netty.handler.codec.http.DefaultFullHttpResponse; -//import io.netty.handler.codec.http.HttpMethod; -//import io.netty.handler.codec.http.HttpRequest; -//import org.eclipse.iofog.utils.configuration.Configuration; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import javax.json.*; -// -//import java.io.StringReader; -//import java.util.concurrent.ExecutorService; -//import java.util.concurrent.Executors; -// -//import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; -//import static io.netty.handler.codec.http.HttpResponseStatus.OK; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({GpsApiHandler.class, HttpRequest.class, ByteBuf.class, ApiHandlerHelpers.class, LoggingService.class, -// Json.class, JsonReader.class, JsonObject.class, Configuration.class, JsonBuilderFactory.class, JsonObjectBuilder.class}) -//@Ignore -//public class GpsApiHandlerTest { -// private GpsApiHandler gpsApiHandler; -// private HttpRequest httpRequest; -// private ByteBuf byteBuf; -// private String content; -// private byte[] bytes; -// private JsonReader jsonReader; -// private JsonObject jsonObject; -// private DefaultFullHttpResponse defaultResponse; -// private JsonBuilderFactory jsonBuilderFactory; -// private JsonObjectBuilder jsonObjectBuilder; -// private String result; -// private ExecutorService executor; -// -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// -// @Before -// public void setUp() throws Exception { -// executor = Executors.newFixedThreadPool(1); -// Mockito.mockStatic(ApiHandlerHelpers.class); -// Mockito.mockStatic(Configuration.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(Json.class); -// httpRequest = Mockito.mock(HttpRequest.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// content = "content"; -// bytes = content.getBytes(); -// result = "result"; -// jsonReader = Mockito.mock(JsonReader.class); -// jsonObject = Mockito.mock(JsonObject.class); -// jsonBuilderFactory = Mockito.mock(JsonBuilderFactory.class); -// jsonObjectBuilder = Mockito.mock(JsonObjectBuilder.class); -// gpsApiHandler = Mockito.spy(new GpsApiHandler(httpRequest, byteBuf, bytes)); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); -// Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); -// Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); -// Mockito.doNothing().when(Configuration.class, "setGpsDataIfValid", Mockito.any(), Mockito.anyString()); -// Mockito.doNothing().when(Configuration.class, "writeGpsToConfigFile"); -// Mockito.doNothing().when(Configuration.class, "saveConfigUpdates"); -// Mockito.when(Json.createBuilderFactory(Mockito.eq(null))).thenReturn(jsonBuilderFactory); -// Mockito.when(jsonBuilderFactory.createObjectBuilder()).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonObjectBuilder.build()).thenReturn(jsonObject); -// Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyString())).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonObject.toString()).thenReturn(result); -// -// } -// -// @After -// public void tearDown() throws Exception { -// executor.shutdown(); -// gpsApiHandler = null; -// jsonObject = null; -// httpRequest = null; -// byteBuf = null; -// result = null; -// defaultResponse = null; -// jsonReader = null; -// bytes = null; -// content = null; -// jsonBuilderFactory = null; -// jsonObjectBuilder = null; -// } -// -// /** -// * Test call when contentType is not valid -// */ -// @Test -// public void testCallWhenContentTypeIsInvalid() { -// try { -// String errorMsg = "Incorrect content type text/html"; -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(errorMsg); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, gpsApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when contentType is valid -// * Request type is DELETE which is not supported -// */ -// @Test -// public void testCallWhenRequestTypeIsDelete() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.DELETE); -// String errorMsg = "Not supported method: " + httpRequest.method(); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, gpsApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when contentType is valid -// * Request type is POST & there is Error with setting GPS -// */ -// @Test -// public void testCallWhenRequestTypeIsPostAndSaveConfigurationThrowsException() { -// try { -// Exception exp = new Exception("Error"); -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.POST); -// Mockito.doThrow(exp).when(Configuration.class, "saveConfigUpdates"); -// 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()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// Mockito.verify(Configuration.class); -// Configuration.writeGpsToConfigFile(); -// Mockito.verify(Configuration.class); -// Configuration.saveConfigUpdates(); -// Mockito.verifyPrivate(gpsApiHandler).invoke("setAgentGpsCoordinates"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when contentType is valid -// * Request type is POST & successfully updates configuration -// */ -// @Test -// public void testCallWhenRequestTypeIsPost() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.POST); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, gpsApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); -// Mockito.verify(Configuration.class); -// Configuration.writeGpsToConfigFile(); -// Mockito.verify(Configuration.class); -// Configuration.saveConfigUpdates(); -// Mockito.verifyPrivate(gpsApiHandler).invoke("setAgentGpsCoordinates"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when contentType is valid -// * Request type is GET -// */ -// @Test -// public void testCallWhenRequestTypeIsGET() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// Mockito.when(Configuration.getGpsCoordinates()).thenReturn("10.20.30,120.90.80"); -// assertEquals(defaultResponse, gpsApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); -// Mockito.verify(Configuration.class); -// Configuration.getGpsCoordinates(); -// Mockito.verifyPrivate(gpsApiHandler).invoke("getAgentGpsCoordinates"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpRequest; +import org.eclipse.iofog.utils.configuration.Configuration; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; +import org.mockito.stubbing.Answer; + +import javax.json.*; + +import java.io.StringReader; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; +import static io.netty.handler.codec.http.HttpResponseStatus.OK; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anySet; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class GpsApiHandlerTest { + private GpsApiHandler gpsApiHandler; + private HttpRequest httpRequest; + private ByteBuf byteBuf; + private String content; + private byte[] bytes; + private JsonReader jsonReader; + private JsonObject jsonObject; + private DefaultFullHttpResponse defaultResponse; + private JsonBuilderFactory jsonBuilderFactory; + private JsonObjectBuilder jsonObjectBuilder; + private String result; + private ExecutorService executor; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic apiHandlerHelpersMockedStatic; + private MockedStatic jsonMockedStatic; + private MockedStatic configurationMockedStatic; + + @BeforeEach + public void setUp() throws Exception { + executor = Executors.newFixedThreadPool(1); + apiHandlerHelpersMockedStatic = Mockito.mockStatic(ApiHandlerHelpers.class); + configurationMockedStatic = Mockito.mockStatic(Configuration.class); + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + jsonMockedStatic = Mockito.mockStatic(Json.class); + httpRequest = Mockito.mock(HttpRequest.class); + byteBuf = Mockito.mock(ByteBuf.class); + content = "content"; + bytes = content.getBytes(); + result = "result"; + jsonReader = Mockito.mock(JsonReader.class); + jsonObject = Mockito.mock(JsonObject.class); + jsonBuilderFactory = Mockito.mock(JsonBuilderFactory.class); + jsonObjectBuilder = Mockito.mock(JsonObjectBuilder.class); + gpsApiHandler = Mockito.spy(new GpsApiHandler(httpRequest, byteBuf, bytes)); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); + Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); + Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); + configurationMockedStatic.when(Configuration::writeGpsToConfigFile).thenAnswer((Answer) invocation -> null); + configurationMockedStatic.when(Configuration::saveConfigUpdates).thenAnswer((Answer) invocation -> null); + configurationMockedStatic.when(() -> Configuration.setGpsDataIfValid(any(), any())).thenAnswer((Answer) invocation -> null); + Mockito.when(Json.createBuilderFactory(Mockito.eq(null))).thenReturn(jsonBuilderFactory); + Mockito.when(jsonBuilderFactory.createObjectBuilder()).thenReturn(jsonObjectBuilder); + Mockito.when(jsonObjectBuilder.build()).thenReturn(jsonObject); + Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyString())).thenReturn(jsonObjectBuilder); + Mockito.when(jsonObject.toString()).thenReturn(result); + + } + + @AfterEach + public void tearDown() throws Exception { + loggingServiceMockedStatic.close(); + apiHandlerHelpersMockedStatic.close(); + jsonMockedStatic.close(); + configurationMockedStatic.close(); + executor.shutdown(); + gpsApiHandler = null; + jsonObject = null; + httpRequest = null; + byteBuf = null; + result = null; + defaultResponse = null; + jsonReader = null; + bytes = null; + content = null; + jsonBuilderFactory = null; + jsonObjectBuilder = null; + } + + /** + * Test call when contentType is not valid + */ + @Test + public void testCallWhenContentTypeIsInvalid() { + try { + String errorMsg = "Incorrect content type text/html"; + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(errorMsg); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, gpsApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when contentType is valid + * Request type is DELETE which is not supported + */ + @Test + public void testCallWhenRequestTypeIsDelete() { + try { + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.DELETE); + String errorMsg = "Not supported method: " + httpRequest.method(); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, gpsApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when contentType is valid + * Request type is POST & there is Error with setting GPS + */ + @Test + public void testCallWhenRequestTypeIsPostAndSaveConfigurationThrowsException() { + try { + 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()); + Mockito.verify(Configuration.class); + Configuration.writeGpsToConfigFile(); + Mockito.verify(Configuration.class); + Configuration.saveConfigUpdates(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when contentType is valid + * Request type is POST & successfully updates configuration + */ + @Test + public void testCallWhenRequestTypeIsPost() { + try { + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.POST); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, gpsApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); + Mockito.verify(Configuration.class); + Configuration.writeGpsToConfigFile(); + Mockito.verify(Configuration.class); + Configuration.saveConfigUpdates(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when contentType is valid + * Request type is GET + */ + @Test + public void testCallWhenRequestTypeIsGET() { + try { + Mockito.when(httpRequest.method()).thenReturn(HttpMethod.GET); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + Mockito.when(Configuration.getGpsCoordinates()).thenReturn("10.20.30,120.90.80"); + assertEquals(defaultResponse, gpsApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); + Mockito.verify(Configuration.class); + Configuration.getGpsCoordinates(); + } 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/local_api/InfoApiHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/InfoApiHandlerTest.java index 3ad42aba..d021967d 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 @@ -1,180 +1,195 @@ -//package org.eclipse.iofog.local_api; -// -//import com.fasterxml.jackson.core.JsonProcessingException; -//import com.fasterxml.jackson.databind.ObjectMapper; -//import io.netty.buffer.ByteBuf; -//import io.netty.handler.codec.http.*; -//import org.eclipse.iofog.utils.configuration.Configuration; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.*; -//import org.junit.rules.Timeout; -//import org.junit.runner.RunWith; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import javax.json.*; -// -//import java.io.StringReader; -//import java.util.concurrent.ExecutorService; -//import java.util.concurrent.Executors; -// -//import static io.netty.handler.codec.http.HttpMethod.GET; -//import static io.netty.handler.codec.http.HttpMethod.POST; -//import static io.netty.handler.codec.http.HttpResponseStatus.*; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static org.junit.Assert.*; -//import static org.powermock.api.mockito.Mockito.verify; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({InfoApiHandler.class, HttpRequest.class, ByteBuf.class, ApiHandlerHelpers.class, LoggingService.class, -// Json.class, JsonReader.class, JsonObject.class, Configuration.class, -// ObjectMapper.class}) -//@Ignore -//public class InfoApiHandlerTest { -// private InfoApiHandler infoApiHandler; -// private HttpRequest httpRequest; -// private ByteBuf byteBuf; -// private String content; -// private byte[] bytes; -// private JsonReader jsonReader; -// private JsonObject jsonObject; -// private DefaultFullHttpResponse defaultResponse; -// private String result; -// private ObjectMapper objectMapper; -// private ExecutorService executor; -// -// -// //global timeout rule -// @Rule -// public Timeout globalTimeout = Timeout.millis(100000l); -// -// @Before -// public void setUp() throws Exception { -// executor = Executors.newFixedThreadPool(1); -// Mockito.mockStatic(ApiHandlerHelpers.class); -// Mockito.mockStatic(Configuration.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(Json.class); -// httpRequest = Mockito.mock(HttpRequest.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// content = "content"; -// bytes = content.getBytes(); -// result = "result"; -// jsonReader = Mockito.mock(JsonReader.class); -// objectMapper = Mockito.mock(ObjectMapper.class); -// jsonObject = Mockito.mock(JsonObject.class); -// infoApiHandler = Mockito.spy(new InfoApiHandler(httpRequest, byteBuf, bytes)); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(GET))).thenReturn(true); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); -// Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); -// Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); -// Mockito.when(jsonObject.toString()).thenReturn(result); +package org.eclipse.iofog.local_api; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.*; +import org.eclipse.iofog.utils.configuration.Configuration; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import javax.json.*; + +import java.io.StringReader; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static io.netty.handler.codec.http.HttpMethod.GET; +import static io.netty.handler.codec.http.HttpMethod.POST; +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class InfoApiHandlerTest { + private InfoApiHandler infoApiHandler; + private HttpRequest httpRequest; + private ByteBuf byteBuf; + private String content; + private byte[] bytes; + private JsonReader jsonReader; + private JsonObject jsonObject; + private DefaultFullHttpResponse defaultResponse; + private String result; + private ObjectMapper objectMapper; + private ExecutorService executor; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic apiHandlerHelpersMockedStatic; + private MockedStatic jsonMockedStatic; + private MockedStatic configurationMockedStatic; + private MockedConstruction objectMapperMockedConstruction; + @BeforeEach + public void setUp() throws Exception { + executor = Executors.newFixedThreadPool(1); + apiHandlerHelpersMockedStatic = Mockito.mockStatic(ApiHandlerHelpers.class); + configurationMockedStatic = Mockito.mockStatic(Configuration.class); + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + jsonMockedStatic = Mockito.mockStatic(Json.class); + httpRequest = Mockito.mock(HttpRequest.class); + byteBuf = Mockito.mock(ByteBuf.class); + content = "content"; + bytes = content.getBytes(); + result = "result"; + jsonReader = Mockito.mock(JsonReader.class); + objectMapper = Mockito.mock(ObjectMapper.class); + jsonObject = Mockito.mock(JsonObject.class); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(GET))).thenReturn(true); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); + Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); + Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); + Mockito.when(jsonObject.toString()).thenReturn(result); + 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); -// } -// -// @After -// public void tearDown() throws Exception { -// infoApiHandler = null; -// objectMapper = null; -// jsonObject = null; -// httpRequest = null; -// byteBuf = null; -// result = null; -// defaultResponse = null; -// jsonReader = null; -// bytes = null; -// content = null; -// executor.shutdown(); -// } -// -// /** -// * Test call when httpMethod is not valid -// */ -// @Test -// public void testCallWhenMethodTypeIsInvalid() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(POST); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(GET))).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); -// assertEquals(defaultResponse, infoApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(GET)); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.methodNotAllowedResponse(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test ApiHandlerHelpers.validateAccessToken returns false -// */ -// @Test -// public void testCallWhenAccessTokenIsNull() { -// try { -// String errorMsg = "Incorrect access token"; -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); -// assertEquals(defaultResponse, infoApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when method & access token is valid -// */ -// @Test -// public void testCallWhenMethodAndAccessTokenAreValid() { -// try { -// Mockito.when(Configuration.getConfigReport()).thenReturn("gps-coordinates(lat,lon) : 10.20.10.90,100.30.50"); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result))).thenReturn(defaultResponse); -// assertEquals(defaultResponse, infoApiHandler.call()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when method & access token is valid -// */ -// @Test -// public void testCallWhenMethodAndAccessTokenAreValidObjectMapperThrowsException() { -// try { -// String errorMsg = "Log message parsing error, null"; -// Mockito.when(Configuration.getConfigReport()).thenReturn("developer's-mode : true"); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(objectMapper.writeValueAsString(Mockito.any())).thenReturn(result); + infoApiHandler = Mockito.spy(new InfoApiHandler(httpRequest, byteBuf, bytes)); + + } + + @AfterEach + public void tearDown() throws Exception { + configurationMockedStatic.close(); + loggingServiceMockedStatic.close(); + jsonMockedStatic.close(); + apiHandlerHelpersMockedStatic.close(); + objectMapperMockedConstruction.close(); + infoApiHandler = null; + objectMapper = null; + jsonObject = null; + httpRequest = null; + byteBuf = null; + result = null; + defaultResponse = null; + jsonReader = null; + bytes = null; + content = null; + executor.shutdown(); + } + + /** + * Test call when httpMethod is not valid + */ + @Test + public void testCallWhenMethodTypeIsInvalid() { + try { + Mockito.when(httpRequest.method()).thenReturn(POST); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(GET))).thenReturn(false); + Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); + assertEquals(defaultResponse, infoApiHandler.call()); + verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(GET)); + verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.methodNotAllowedResponse(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test ApiHandlerHelpers.validateAccessToken returns false + */ + @Test + public void testCallWhenAccessTokenIsNull() { + try { + String errorMsg = "Incorrect access token"; + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, UNAUTHORIZED, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(false); + Mockito.when(ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); + assertEquals(defaultResponse, infoApiHandler.call()); + verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); + verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.unauthorizedResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when method & access token is valid + */ + @Test + public void testCallWhenMethodAndAccessTokenAreValid() { + try { + Mockito.when(Configuration.getConfigReport()).thenReturn("gps-coordinates(lat,lon) : 10.20.10.90,100.30.50"); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + HttpUtil.setContentLength(defaultResponse, byteBuf.readableBytes()); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result))).thenReturn(defaultResponse); + assertEquals(defaultResponse, infoApiHandler.call()); + verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); + verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when method & access token is valid + */ + @Test + @Disabled + public void testCallWhenMethodAndAccessTokenAreValidObjectMapperThrowsException() { + try { + String errorMsg = "Log message parsing error, null"; + Mockito.when(Configuration.getConfigReport()).thenReturn("developer's-mode : true"); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + objectMapperMockedConstruction.close(); + 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()); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); -// verifyStatic(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -//} \ No newline at end of file + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg))).thenReturn(defaultResponse); + assertEquals(defaultResponse, infoApiHandler.call()); + verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateAccessToken(Mockito.eq(httpRequest)); + verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } 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/local_api/LocalApiServerHandlerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerHandlerTest.java index e182e718..df88c8ea 100644 --- a/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerHandlerTest.java +++ b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerHandlerTest.java @@ -1,30 +1,28 @@ -//package org.eclipse.iofog.local_api; -// -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -// -//import static org.junit.Assert.*; -// -//public class LocalApiServerHandlerTest { -// -// @Before -// public void setUp() throws Exception { -// } -// -// @After -// public void tearDown() throws Exception { -// } -// -// @Test -// public void channelRead0() { -// } -// -// @Test -// public void channelReadComplete() { -// } -// -// @Test -// public void exceptionCaught() { -// } -//} \ No newline at end of file +package org.eclipse.iofog.local_api; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class LocalApiServerHandlerTest { + + @BeforeEach + public void setUp() throws Exception { + } + + @AfterEach + public void tearDown() throws Exception { + } + + @Test + public void channelRead0() { + } + + @Test + public void channelReadComplete() { + } + + @Test + public void exceptionCaught() { + } +} \ No newline at end of file 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 3af283af..97e13107 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,110 +1,108 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.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.After; -//import org.junit.Before; -//import org.junit.Ignore; -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.mockito.Mock; -//import org.mockito.Mockito; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import java.util.concurrent.ExecutorService; -//import java.util.concurrent.Executors; -// -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({LocalApiServerPipelineFactory.class, SslContext.class, SocketChannel.class, ChannelPipeline.class, -// LoggingService.class, HttpServerCodec.class, HttpObjectAggregator.class, LocalApiServerHandler.class, DefaultEventExecutorGroup.class}) -//@Ignore -//public class LocalApiServerPipelineFactoryTest { -// private LocalApiServerPipelineFactory localApiServerPipelineFactory; -// private SslContext sslContext; -// private SocketChannel channel; -// private ChannelPipeline pipeline; -// private LocalApiServerHandler serverHandler; -// private HttpObjectAggregator httpObjectAggregator; -// private HttpServerCodec httpServerCodec; -// private DefaultEventExecutorGroup defaultEventExecutorGroup; -// private ExecutorService executor; -// -// -// @Before -// public void setUp() throws Exception { -// executor = Executors.newFixedThreadPool(1); -// httpServerCodec = Mockito.mock(HttpServerCodec.class); -// httpObjectAggregator = Mockito.mock(HttpObjectAggregator.class); +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import 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; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.junit.jupiter.api.Assertions.fail; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class LocalApiServerPipelineFactoryTest { + private LocalApiServerPipelineFactory localApiServerPipelineFactory; + private SslContext sslContext; + private SocketChannel channel; + private ChannelPipeline pipeline; + private ExecutorService executor; + private MockedConstruction httpServerCodecMockedConstruction; + private MockedConstruction localApiServerHandlerMockedConstruction; + private MockedConstruction httpObjectAggregatorMockedConstruction; + private MockedConstruction defaultEventExecutorGroupMockedConstruction; + private MockedStatic loggingServiceMockedStatic; + + + + @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); + sslContext = Mockito.mock(SslContext.class); + channel = Mockito.mock(SocketChannel.class); + pipeline = Mockito.mock(ChannelPipeline.class); // defaultEventExecutorGroup = Mockito.mock(DefaultEventExecutorGroup.class); -// Mockito.mockStatic(LoggingService.class); -// localApiServerPipelineFactory = Mockito.spy(new LocalApiServerPipelineFactory(sslContext)); -// Mockito.when(channel.pipeline()).thenReturn(pipeline); -// Mockito.whenNew(HttpServerCodec.class).withNoArguments().thenReturn(httpServerCodec); -// Mockito.whenNew(LocalApiServerHandler.class) -// .withArguments(Mockito.any(EventExecutorGroup.class)) -// .thenReturn(serverHandler); -// Mockito.whenNew(HttpObjectAggregator.class) -// .withArguments(Mockito.eq(Integer.MAX_VALUE)) -// .thenReturn(httpObjectAggregator); -// Mockito.whenNew(DefaultEventExecutorGroup.class) -// .withArguments(Mockito.eq(10)) -// .thenReturn(defaultEventExecutorGroup); -// } -// -// @After -// public void tearDown() throws Exception { -// localApiServerPipelineFactory = null; -// sslContext = null; + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + localApiServerPipelineFactory = Mockito.spy(new LocalApiServerPipelineFactory(sslContext)); + Mockito.when(channel.pipeline()).thenReturn(pipeline); + httpServerCodecMockedConstruction = Mockito.mockConstruction(HttpServerCodec.class); + localApiServerHandlerMockedConstruction= Mockito.mockConstruction(LocalApiServerHandler.class); + httpObjectAggregatorMockedConstruction = Mockito.mockConstruction(HttpObjectAggregator.class); + defaultEventExecutorGroupMockedConstruction =Mockito.mockConstruction(DefaultEventExecutorGroup.class); + } + + @AfterEach + public void tearDown() throws Exception { + defaultEventExecutorGroupMockedConstruction.close(); + httpServerCodecMockedConstruction.close(); + localApiServerHandlerMockedConstruction.close(); + httpObjectAggregatorMockedConstruction.close(); + loggingServiceMockedStatic.close(); + localApiServerPipelineFactory = null; + sslContext = null; // httpObjectAggregator = null; // serverHandler = null; // httpServerCodec = null; // defaultEventExecutorGroup = null; -// pipeline = null; -// channel = null; -// executor.shutdown(); -// } -// -// /** -// * Test initChannel -// */ -// @Test -// public void testInitChannel() { -// try { -// localApiServerPipelineFactory.initChannel(channel); -// Mockito.verify(pipeline).addLast(Mockito.eq(httpObjectAggregator)); -// Mockito.verify(pipeline).addLast(Mockito.eq(serverHandler)); -// Mockito.verify(pipeline).addLast(Mockito.eq(httpServerCodec)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file + pipeline = null; + channel = null; + executor.shutdown(); + } + + /** + * Test initChannel + */ + @Test + public void testInitChannel() { + try { + localApiServerPipelineFactory.initChannel(channel); + Mockito.verify(pipeline,Mockito.times(4)).addLast(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/local_api/LocalApiServerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiServerTest.java index 3197c22f..aaa6bfc1 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,138 +1,135 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.bootstrap.ServerBootstrap; -//import io.netty.channel.Channel; -//import io.netty.channel.ChannelFuture; -//import io.netty.channel.nio.NioEventLoopGroup; -//import io.netty.channel.socket.nio.NioServerSocketChannel; -//import io.netty.handler.ssl.util.SelfSignedCertificate; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Ignore; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({LocalApiServer.class, NioEventLoopGroup.class, SelfSignedCertificate.class, ServerBootstrap.class, LocalApiServerPipelineFactory.class, LoggingService.class, -// ChannelFuture.class, ControlWebsocketWorker.class, MessageWebsocketWorker.class}) -//@Ignore -//public class LocalApiServerTest { -// private LocalApiServer localApiServer; -// private NioEventLoopGroup nioEventLoopGroup; -// private SelfSignedCertificate selfSignedCertificate; -// private ServerBootstrap serverBootstrap; -// private LocalApiServerPipelineFactory localApiServerPipelineFactory; -// private ChannelFuture channelFuture; -// private Channel channel; -// private ControlWebsocketWorker controlWebsocketWorker; -// private MessageWebsocketWorker messageWebsocketWorker; -// private String MODULE_NAME; -// -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "Local API"; -// Mockito.mockStatic(LoggingService.class); -// nioEventLoopGroup = Mockito.mock(NioEventLoopGroup.class); -// channel = Mockito.mock(Channel.class); -// controlWebsocketWorker = Mockito.mock(ControlWebsocketWorker.class); -// messageWebsocketWorker = Mockito.mock(MessageWebsocketWorker.class); -// channelFuture = Mockito.mock(ChannelFuture.class); -// selfSignedCertificate = Mockito.mock(SelfSignedCertificate.class); -// serverBootstrap = Mockito.mock(ServerBootstrap.class); -// localApiServerPipelineFactory = Mockito.mock(LocalApiServerPipelineFactory.class); -// localApiServer = Mockito.spy(new LocalApiServer()); -// Mockito.whenNew(NioEventLoopGroup.class).withArguments(Mockito.eq(1)) -// .thenReturn(nioEventLoopGroup); -// Mockito.whenNew(NioEventLoopGroup.class).withArguments(Mockito.eq(10)) -// .thenReturn(nioEventLoopGroup); -// Mockito.whenNew(SelfSignedCertificate.class).withNoArguments() -// .thenReturn(selfSignedCertificate); -// Mockito.whenNew(LocalApiServerPipelineFactory.class).withArguments(Mockito.any()) -// .thenReturn(localApiServerPipelineFactory); -// Mockito.whenNew(ServerBootstrap.class).withNoArguments() -// .thenReturn(serverBootstrap); -// Mockito.whenNew(MessageWebsocketWorker.class).withNoArguments() -// .thenReturn(messageWebsocketWorker); -// Mockito.whenNew(ControlWebsocketWorker.class).withNoArguments() -// .thenReturn(controlWebsocketWorker); -// Mockito.when(serverBootstrap.group(Mockito.any(NioEventLoopGroup.class), Mockito.any(NioEventLoopGroup.class))).thenReturn(serverBootstrap); -// Mockito.when(serverBootstrap.channel(Mockito.any())).thenReturn(serverBootstrap); -// Mockito.when(serverBootstrap.childHandler(Mockito.any())).thenReturn(serverBootstrap); -// Mockito.when(serverBootstrap.bind(Mockito.eq(54321))).thenReturn(channelFuture); -// Mockito.when(channelFuture.sync()).thenReturn(channelFuture); -// Mockito.when(channelFuture.channel()).thenReturn(channel); -// Mockito.when(channel.closeFuture()).thenReturn(channelFuture); -// } -// -// @After -// public void tearDown() throws Exception { -// localApiServer.stop(); -// localApiServer = null; -// MODULE_NAME = null; -// nioEventLoopGroup = null; -// channel = null; -// controlWebsocketWorker = null; -// messageWebsocketWorker = null; -// channelFuture = null; -// selfSignedCertificate = null; -// serverBootstrap = null; -// localApiServerPipelineFactory = null; -// } -// -// /** -// * Test start -// */ -// @Test -// public void testStart() { -// try { -// localApiServer.start(); -// Mockito.verify(serverBootstrap).childHandler(Mockito.eq(localApiServerPipelineFactory)); -// Mockito.verify(serverBootstrap).channel(Mockito.eq(NioServerSocketChannel.class)); -// Mockito.verify(serverBootstrap).bind(Mockito.eq(54321)); -// Mockito.verify(channel).closeFuture(); -// Mockito.verify(channelFuture).channel(); -// Mockito.verify(channelFuture, Mockito.atLeastOnce()).sync(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test stop -// */ -// @Test -// public void testStop() { -// try { -// localApiServer.stop(); -// Mockito.mockStatic(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Start stopping Local api server\n"); -// Mockito.mockStatic(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME, "Local api server stopped\n"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.util.SelfSignedCertificate; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Answers; +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 org.mockito.stubbing.Answer; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class LocalApiServerTest { + private LocalApiServer localApiServer; + private ServerBootstrap serverBootstrap; + private ChannelFuture channelFuture; + private Channel channel; + private String MODULE_NAME; + private MockedStatic loggingServiceMockedStatic; + private MockedConstruction nioEventLoopGroupMockedConstruction; + private MockedConstruction selfSignedCertificateMockedConstruction; + private MockedConstruction localApiServerPipelineFactoryMockedConstruction; + private MockedConstruction serverBootstrapMockedConstruction; + private MockedConstruction messageWebsocketWorkerMockedConstruction; + private MockedConstruction controlWebsocketWorkerMockedConstruction; + + + + @BeforeEach + public void setUp() throws Exception { + MODULE_NAME = "Local API"; + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + channel = Mockito.mock(Channel.class); + channelFuture = Mockito.mock(ChannelFuture.class); + serverBootstrap = Mockito.mock(ServerBootstrap.class); + LocalApiServerPipelineFactory localApiServerPipelineFactory = Mockito.mock(LocalApiServerPipelineFactory.class); + localApiServer = Mockito.spy(new LocalApiServer()); + nioEventLoopGroupMockedConstruction = Mockito.mockConstruction(NioEventLoopGroup.class); + selfSignedCertificateMockedConstruction = Mockito.mockConstruction(SelfSignedCertificate.class); + localApiServerPipelineFactoryMockedConstruction = Mockito.mockConstruction(LocalApiServerPipelineFactory.class, + withSettings().defaultAnswer((Answer) invocation -> null)); + messageWebsocketWorkerMockedConstruction = Mockito.mockConstruction(MessageWebsocketWorker.class); + controlWebsocketWorkerMockedConstruction = Mockito.mockConstruction(ControlWebsocketWorker.class); + serverBootstrapMockedConstruction = Mockito.mockConstruction(ServerBootstrap.class, (mock, context)->{ + when(mock.group(Mockito.any(NioEventLoopGroup.class), Mockito.any(NioEventLoopGroup.class))).thenReturn(serverBootstrap); + when(serverBootstrap.channel(Mockito.any())).thenReturn(serverBootstrap); + when(serverBootstrap.childHandler(Mockito.any())).thenReturn(serverBootstrap); + when(mock.bind(Mockito.eq(54321))).thenReturn(channelFuture); + }); + when(channelFuture.sync()).thenReturn(channelFuture); + when(channelFuture.channel()).thenReturn(channel); + when(channel.closeFuture()).thenReturn(channelFuture); + } + + @AfterEach + public void tearDown() throws Exception { + controlWebsocketWorkerMockedConstruction.close(); + localApiServerPipelineFactoryMockedConstruction.close(); + messageWebsocketWorkerMockedConstruction.close(); + nioEventLoopGroupMockedConstruction.close(); + selfSignedCertificateMockedConstruction.close(); + serverBootstrapMockedConstruction.close(); + localApiServer.stop(); + localApiServer = null; + MODULE_NAME = null; + channel = null; + channelFuture = null; + serverBootstrap = null; + loggingServiceMockedStatic.close(); + } + + /** + * Test start + */ + @Test + public void testStart() { + try { + localApiServer.start(); + Mockito.verify(serverBootstrap).childHandler(Mockito.any()); + Mockito.verify(serverBootstrap).channel(Mockito.eq(NioServerSocketChannel.class)); + Mockito.verify(channel).closeFuture(); + Mockito.verify(channelFuture).channel(); + Mockito.verify(channelFuture, Mockito.atLeastOnce()).sync(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test stop + */ + @Test + public void testStop() { + try { + localApiServer.stop(); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Stopping Local api server\n"); + } 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/local_api/LocalApiStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/LocalApiStatusTest.java index e5967c5f..9be6e8f6 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,63 +1,65 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({LocalApiStatus.class}) -//public class LocalApiStatusTest { -// private LocalApiStatus localApiStatus; -// -// @Before -// public void setUp() throws Exception { -// localApiStatus = Mockito.spy(new LocalApiStatus()); -// } -// -// @After -// public void tearDown() throws Exception { -// localApiStatus = null; -// } -// -// /** -// * Test getter and setter of OpenConfigSocketsCount -// */ -// @Test -// public void testGetAndSetOfOpenConfigSocketsCount() { -// assertEquals(0, localApiStatus.getOpenConfigSocketsCount()); -// localApiStatus.setOpenConfigSocketsCount(10); -// assertEquals(10, localApiStatus.getOpenConfigSocketsCount()); -// } -// -// /** -// * Test getter and setter of penMessageSocketsCount -// */ -// @Test -// public void testGetAndSetOpenMessageSocketsCount() { -// assertEquals(0, localApiStatus.getOpenMessageSocketsCount()); -// localApiStatus.setOpenMessageSocketsCount(10); -// assertEquals(10, localApiStatus.getOpenMessageSocketsCount()); -// } -// -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import 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.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; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class LocalApiStatusTest { + private LocalApiStatus localApiStatus; + + @BeforeEach + public void setUp() throws Exception { + localApiStatus = Mockito.spy(new LocalApiStatus()); + } + + @AfterEach + public void tearDown() throws Exception { + localApiStatus = null; + } + + /** + * Test getter and setter of OpenConfigSocketsCount + */ + @Test + public void testGetAndSetOfOpenConfigSocketsCount() { + assertEquals(0, localApiStatus.getOpenConfigSocketsCount()); + localApiStatus.setOpenConfigSocketsCount(10); + assertEquals(10, localApiStatus.getOpenConfigSocketsCount()); + } + + /** + * Test getter and setter of penMessageSocketsCount + */ + @Test + public void testGetAndSetOpenMessageSocketsCount() { + assertEquals(0, localApiStatus.getOpenMessageSocketsCount()); + localApiStatus.setOpenMessageSocketsCount(10); + assertEquals(10, localApiStatus.getOpenMessageSocketsCount()); + } + +} \ No newline at end of file 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 abe1e7a7..51e52a03 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,230 +1,237 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import io.netty.buffer.ByteBuf; -//import io.netty.handler.codec.http.DefaultFullHttpResponse; -//import io.netty.handler.codec.http.HttpRequest; -//import org.eclipse.iofog.utils.configuration.Configuration; -//import org.eclipse.iofog.utils.logging.LoggingService; -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Ignore; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import javax.json.*; -// -//import java.io.StringReader; -//import java.util.concurrent.ExecutorService; -//import java.util.concurrent.Executors; -// -//import static io.netty.handler.codec.http.HttpMethod.GET; -//import static io.netty.handler.codec.http.HttpMethod.POST; -//import static io.netty.handler.codec.http.HttpResponseStatus.*; -//import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({LogApiHandler.class, LoggingService.class, HttpRequest.class, HttpRequest.class, ByteBuf.class, JsonReader.class, -// JsonObject.class, ApiHandlerHelpers.class, Configuration.class, Json.class, JsonBuilderFactory.class, JsonObjectBuilder.class}) -//@Ignore -//public class LogApiHandlerTest { -// private LogApiHandler logApiHandler; -// private HttpRequest httpRequest; -// private ByteBuf byteBuf; -// private String content; -// private byte[] bytes; -// private JsonReader jsonReader; -// private JsonObject jsonObject; -// private DefaultFullHttpResponse defaultResponse; -// private String result; -// private JsonBuilderFactory jsonBuilderFactory; -// private JsonObjectBuilder jsonObjectBuilder; -// private ExecutorService executor; -// -// @Before -// public void setUp() throws Exception { -// executor = Executors.newFixedThreadPool(1); -// Mockito.mockStatic(ApiHandlerHelpers.class); -// Mockito.mockStatic(Configuration.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(Json.class); -// httpRequest = Mockito.mock(HttpRequest.class); -// byteBuf = Mockito.mock(ByteBuf.class); -// content = "content"; -// bytes = content.getBytes(); -// result = "result"; -// jsonReader = Mockito.mock(JsonReader.class); -// jsonObject = Mockito.mock(JsonObject.class); -// jsonBuilderFactory = Mockito.mock(JsonBuilderFactory.class); -// jsonObjectBuilder = Mockito.mock(JsonObjectBuilder.class); -// logApiHandler = Mockito.spy(new LogApiHandler(httpRequest, byteBuf, bytes)); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(GET))).thenReturn(true); -// Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); -// Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); -// Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); -// Mockito.when(httpRequest.method()).thenReturn(POST); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(true); -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); -// Mockito.when(Json.createBuilderFactory(Mockito.eq(null))).thenReturn(jsonBuilderFactory); -// Mockito.when(jsonBuilderFactory.createObjectBuilder()).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonObjectBuilder.build()).thenReturn(jsonObject); -// Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyString())).thenReturn(jsonObjectBuilder); -// Mockito.when(jsonObject.toString()).thenReturn(result); -// Mockito.when(LoggingService.microserviceLogInfo(Mockito.anyString(), Mockito.anyString())).thenReturn(true); -// Mockito.when(LoggingService.microserviceLogWarning(Mockito.anyString(), Mockito.anyString())).thenReturn(true); -// } -// -// @After -// public void tearDown() throws Exception { -// logApiHandler = null; -// jsonObject = null; -// httpRequest = null; -// byteBuf = null; -// result = null; -// defaultResponse = null; -// jsonReader = null; -// bytes = null; -// content = null; -// jsonBuilderFactory = null; -// jsonObjectBuilder = null; -// executor.shutdown(); -// } -// -// /** -// * Test call when httpMethod is not valid -// */ -// @Test -// public void testCallWhenMethodTypeIsInvalid() { -// try { -// Mockito.when(httpRequest.method()).thenReturn(GET); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); -// Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(false); -// Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); -// assertEquals(defaultResponse, logApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST)); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.methodNotAllowedResponse(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when contentType is not valid -// */ -// @Test -// public void testCallWhenContentTypeIsInvalid() { -// try { -// String errorMsg = "Incorrect content type text/html"; -// Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(errorMsg); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, logApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when content doesn't has message, logType and id -// */ -// @Test -// public void testCallWhenRequestDoesnotContainMessage() { -// try { -// String errorMsg = "Log message parsing error, " + "Logger initialized null"; -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); -// Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, logApiHandler.call()); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test call when content has message, logType and id -// * logType is info -// */ -// @Test -// public void testCallWhenRequestContainMessage() { -// try { -// Mockito.when(jsonObject.containsKey(Mockito.eq("message"))).thenReturn(true); -// Mockito.when(jsonObject.containsKey(Mockito.eq("type"))).thenReturn(true); -// Mockito.when(jsonObject.containsKey(Mockito.eq("id"))).thenReturn(true); -// Mockito.when(jsonObject.getString(Mockito.eq("id"))).thenReturn("id"); -// Mockito.when(jsonObject.getString(Mockito.eq("message"))).thenReturn("message"); -// Mockito.when(jsonObject.getString(Mockito.eq("type"))).thenReturn("info"); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, logApiHandler.call()); -// Mockito.verify(jsonObject).containsKey(Mockito.eq("message")); -// Mockito.verify(jsonObject).containsKey(Mockito.eq("id")); -// Mockito.verify(jsonObject).containsKey(Mockito.eq("type")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); -// Mockito.verify(LoggingService.class); -// LoggingService.microserviceLogInfo(Mockito.eq("id"), Mockito.eq("message")); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test call when content has message, logType and id -// * logType is info -// */ -// @Test -// public void testCallWhenRequestContainLogTypeSevere() { -// try { -// Mockito.when(jsonObject.containsKey(Mockito.eq("message"))).thenReturn(true); -// Mockito.when(jsonObject.containsKey(Mockito.eq("type"))).thenReturn(true); -// Mockito.when(jsonObject.containsKey(Mockito.eq("id"))).thenReturn(true); -// Mockito.when(jsonObject.getString(Mockito.eq("id"))).thenReturn("id"); -// Mockito.when(jsonObject.getString(Mockito.eq("message"))).thenReturn("message"); -// Mockito.when(jsonObject.getString(Mockito.eq("type"))).thenReturn("severe"); -// defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); -// Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); -// assertEquals(defaultResponse, logApiHandler.call()); -// Mockito.verify(jsonObject).containsKey(Mockito.eq("message")); -// Mockito.verify(jsonObject).containsKey(Mockito.eq("id")); -// Mockito.verify(jsonObject).containsKey(Mockito.eq("type")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); -// Mockito.verify(ApiHandlerHelpers.class); -// ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); -// Mockito.verify(LoggingService.class); -// LoggingService.microserviceLogWarning(Mockito.eq("id"), Mockito.eq("message")); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import io.netty.buffer.ByteBuf; +import io.netty.handler.codec.http.DefaultFullHttpResponse; +import io.netty.handler.codec.http.HttpRequest; +import org.eclipse.iofog.command_line.CommandLineParser; +import org.eclipse.iofog.utils.configuration.Configuration; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.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.*; +import java.io.StringReader; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import static io.netty.handler.codec.http.HttpMethod.GET; +import static io.netty.handler.codec.http.HttpMethod.POST; +import static io.netty.handler.codec.http.HttpResponseStatus.*; +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class LogApiHandlerTest { + private LogApiHandler logApiHandler; + private HttpRequest httpRequest; + private ByteBuf byteBuf; + private String content; + private byte[] bytes; + private JsonReader jsonReader; + private JsonObject jsonObject; + private DefaultFullHttpResponse defaultResponse; + private String result; + private JsonBuilderFactory jsonBuilderFactory; + private JsonObjectBuilder jsonObjectBuilder; + private ExecutorService executor; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic apiHandlerHelpersMockedStatic; + private MockedStatic jsonMockedStatic; + private MockedStatic configurationMockedStatic; + + @BeforeEach + public void setUp() throws Exception { + executor = Executors.newFixedThreadPool(1); + apiHandlerHelpersMockedStatic = Mockito.mockStatic(ApiHandlerHelpers.class); + configurationMockedStatic = Mockito.mockStatic(Configuration.class); + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + jsonMockedStatic = Mockito.mockStatic(Json.class); + httpRequest = Mockito.mock(HttpRequest.class); + byteBuf = Mockito.mock(ByteBuf.class); + content = "content"; + bytes = content.getBytes(); + result = "result"; + jsonReader = Mockito.mock(JsonReader.class); + jsonObject = Mockito.mock(JsonObject.class); + jsonBuilderFactory = Mockito.mock(JsonBuilderFactory.class); + jsonObjectBuilder = Mockito.mock(JsonObjectBuilder.class); + logApiHandler = Mockito.spy(new LogApiHandler(httpRequest, byteBuf, bytes)); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(GET))).thenReturn(true); + Mockito.when(ApiHandlerHelpers.validateAccessToken(Mockito.any())).thenReturn(true); + Mockito.when(Json.createReader(Mockito.any(StringReader.class))).thenReturn(jsonReader); + Mockito.when(jsonReader.readObject()).thenReturn(jsonObject); + Mockito.when(httpRequest.method()).thenReturn(POST); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(true); + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(null); + Mockito.when(Json.createBuilderFactory(Mockito.eq(null))).thenReturn(jsonBuilderFactory); + Mockito.when(jsonBuilderFactory.createObjectBuilder()).thenReturn(jsonObjectBuilder); + Mockito.when(jsonObjectBuilder.build()).thenReturn(jsonObject); + Mockito.when(jsonObjectBuilder.add(Mockito.anyString(), Mockito.anyString())).thenReturn(jsonObjectBuilder); + Mockito.when(jsonObject.toString()).thenReturn(result); + Mockito.when(LoggingService.microserviceLogInfo(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + Mockito.when(LoggingService.microserviceLogWarning(Mockito.anyString(), Mockito.anyString())).thenReturn(true); + } + + @AfterEach + public void tearDown() throws Exception { + configurationMockedStatic.close(); + loggingServiceMockedStatic.close(); + apiHandlerHelpersMockedStatic.close(); + jsonMockedStatic.close(); + logApiHandler = null; + jsonObject = null; + httpRequest = null; + byteBuf = null; + result = null; + defaultResponse = null; + jsonReader = null; + bytes = null; + content = null; + jsonBuilderFactory = null; + jsonObjectBuilder = null; + executor.shutdown(); + } + + /** + * Test call when httpMethod is not valid + */ + @Test + public void testCallWhenMethodTypeIsInvalid() { + try { + Mockito.when(httpRequest.method()).thenReturn(GET); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, METHOD_NOT_ALLOWED); + Mockito.when(ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST))).thenReturn(false); + Mockito.when(ApiHandlerHelpers.methodNotAllowedResponse()).thenReturn(defaultResponse); + assertEquals(defaultResponse, logApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateMethod(Mockito.eq(httpRequest), Mockito.eq(POST)); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.methodNotAllowedResponse(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when contentType is not valid + */ + @Test + public void testCallWhenContentTypeIsInvalid() { + try { + String errorMsg = "Incorrect content type text/html"; + Mockito.when(ApiHandlerHelpers.validateContentType(Mockito.any(), Mockito.anyString())).thenReturn(errorMsg); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, logApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when content doesn't has message, logType and id + */ + @Test + public void testCallWhenRequestDoesnotContainMessage() { + try { + String errorMsg = "Log message parsing error, " + "Logger initialized null"; + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST, byteBuf); + Mockito.when(ApiHandlerHelpers.badRequestResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, logApiHandler.call()); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.badRequestResponse(Mockito.eq(byteBuf), Mockito.eq(errorMsg)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test call when content has message, logType and id + * logType is info + */ + @Test + public void testCallWhenRequestContainMessage() { + try { + Mockito.when(jsonObject.containsKey(Mockito.eq("message"))).thenReturn(true); + Mockito.when(jsonObject.containsKey(Mockito.eq("type"))).thenReturn(true); + Mockito.when(jsonObject.containsKey(Mockito.eq("id"))).thenReturn(true); + Mockito.when(jsonObject.getString(Mockito.eq("id"))).thenReturn("id"); + Mockito.when(jsonObject.getString(Mockito.eq("message"))).thenReturn("message"); + Mockito.when(jsonObject.getString(Mockito.eq("type"))).thenReturn("info"); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, logApiHandler.call()); + Mockito.verify(jsonObject).containsKey(Mockito.eq("message")); + Mockito.verify(jsonObject).containsKey(Mockito.eq("id")); + Mockito.verify(jsonObject).containsKey(Mockito.eq("type")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); + Mockito.verify(LoggingService.class); + LoggingService.microserviceLogInfo(Mockito.eq("id"), Mockito.eq("message")); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test call when content has message, logType and id + * logType is info + */ + @Test + public void testCallWhenRequestContainLogTypeSevere() { + try { + Mockito.when(jsonObject.containsKey(Mockito.eq("message"))).thenReturn(true); + Mockito.when(jsonObject.containsKey(Mockito.eq("type"))).thenReturn(true); + Mockito.when(jsonObject.containsKey(Mockito.eq("id"))).thenReturn(true); + Mockito.when(jsonObject.getString(Mockito.eq("id"))).thenReturn("id"); + Mockito.when(jsonObject.getString(Mockito.eq("message"))).thenReturn("message"); + Mockito.when(jsonObject.getString(Mockito.eq("type"))).thenReturn("severe"); + defaultResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, byteBuf); + Mockito.when(ApiHandlerHelpers.successResponse(Mockito.any(), Mockito.anyString())).thenReturn(defaultResponse); + assertEquals(defaultResponse, logApiHandler.call()); + Mockito.verify(jsonObject).containsKey(Mockito.eq("message")); + Mockito.verify(jsonObject).containsKey(Mockito.eq("id")); + Mockito.verify(jsonObject).containsKey(Mockito.eq("type")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.validateContentType(Mockito.eq(httpRequest), Mockito.eq("application/json")); + Mockito.verify(ApiHandlerHelpers.class); + ApiHandlerHelpers.successResponse(Mockito.eq(byteBuf), Mockito.eq(result)); + Mockito.verify(LoggingService.class); + LoggingService.microserviceLogWarning(Mockito.eq("id"), Mockito.eq("message")); + } 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/local_api/MessageCallbackTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/local_api/MessageCallbackTest.java index a7a7614e..d43eb1a0 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,63 +1,71 @@ -///* -// * ******************************************************************************* -// * * Copyright (c) 2018-2022 Edgeworx, Inc. -// * * -// * * This program and the accompanying materials are made available under the -// * * terms of the Eclipse Public License v. 2.0 which is available at -// * * http://www.eclipse.org/legal/epl-2.0 -// * * -// * * SPDX-License-Identifier: EPL-2.0 -// * ******************************************************************************* -// * -// */ -//package org.eclipse.iofog.local_api; -// -//import org.eclipse.iofog.message_bus.Message; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static org.junit.Assert.*; -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessageCallback.class, MessageWebsocketHandler.class, Message.class}) -//public class MessageCallbackTest { -// private MessageCallback messageCallback; -// private String name; -// private MessageWebsocketHandler messageWebsocketHandler; -// private Message message; -// -// @Before -// public void setUp() throws Exception { -// name = "message"; -// message = Mockito.mock(Message.class); -// messageWebsocketHandler = Mockito.mock(MessageWebsocketHandler.class); -// messageCallback = Mockito.spy(new MessageCallback(name)); +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.local_api; + +import org.eclipse.iofog.message_bus.Message; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import static org.mockito.Mockito.when; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class MessageCallbackTest { + private MessageCallback messageCallback; + private String name; + private MessageWebsocketHandler messageWebsocketHandler; + private Message message; + private MockedConstruction messageWebsocketHandlerMockedConstruction; + + @BeforeEach + 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); -// } -// -// @After -// public void tearDown() throws Exception { -// name = null; -// messageCallback = null; -// message = null; -// messageWebsocketHandler = null; -// } -// -// /** -// * Test sendRealtimeMessage -// */ -// @Test -// public void testSendRealtimeMessage() { -// messageCallback.sendRealtimeMessage(message); -// Mockito.verify(messageWebsocketHandler).sendRealTimeMessage(Mockito.eq(name), Mockito.eq(message)); -// } -//} \ No newline at end of file + } + + @AfterEach + public void tearDown() throws Exception { + messageWebsocketHandlerMockedConstruction.close(); + name = null; + messageCallback = null; + message = null; + messageWebsocketHandler = null; + } + + /** + * Test sendRealtimeMessage + */ + @Test + public void testSendRealtimeMessage() { + messageCallback.sendRealtimeMessage(message); + MessageWebsocketHandler aMock = messageWebsocketHandlerMockedConstruction.constructed().get(0); + Mockito.verify(aMock).sendRealTimeMessage(Mockito.any(), Mockito.any()); + } +} \ No newline at end of file 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 4e3ffc55..ca97c4bf 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,98 +1,102 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.eclipse.iofog.local_api.MessageCallback; -//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.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import jakarta.jms.JMSException; -//import jakarta.jms.TextMessage; -// -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.*; -//import static org.mockito.Mockito.reset; -//import static org.mockito.Mockito.verify; -//import static org.powermock.api.mockito.Mockito.*; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({IOMessageListener.class, MessageCallback.class, TextMessage.class, Message.class, LoggingService.class}) -//public class IOMessageListenerTest { -// private IOMessageListener ioMessageListener; -// private MessageCallback messageCallback; -// private TextMessage textMessage; -// private Message message; -// private String MODULE_NAME = "MessageListener"; -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "MessageListener"; -// messageCallback = mock(MessageCallback.class); -// textMessage = mock(TextMessage.class); -// message = mock(Message.class); -// mockStatic(LoggingService.class); -// ioMessageListener = spy(new IOMessageListener(messageCallback)); -// doNothing().when(textMessage).acknowledge(); -// Mockito.when(textMessage.getText()).thenReturn("{}"); -// Mockito.whenNew(Message.class).withArguments(anyString()).thenReturn(message); -// Mockito.doNothing().when(messageCallback).sendRealtimeMessage(any(Message.class)); -// } -// -// @After -// public void tearDown() throws Exception { -// reset(messageCallback); -// MODULE_NAME = null; -// } -// -// /** -// * Test onMessage success scenario -// */ -// @Test -// public void testOnMessage() { -// try { -// ioMessageListener.onMessage(textMessage); -// verify(textMessage).acknowledge(); -// verify(messageCallback).sendRealtimeMessage(any()); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Start acknowledging message onMessage"); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Finish acknowledging message onMessage"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test onMessage error scenario -// */ -// @Test -// public void throwsExceptionOnMessage() { -// try { -// Mockito.doThrow(mock(JMSException.class)).when(textMessage).acknowledge(); -// ioMessageListener.onMessage(textMessage); -// LoggingService.logError(eq(MODULE_NAME), eq("Error acknowledging message"), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.message_bus; + +import org.eclipse.iofog.local_api.MessageCallback; +import org.eclipse.iofog.utils.logging.LoggingService; +import jakarta.jms.JMSException; +import jakarta.jms.TextMessage; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +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; + + @BeforeEach + 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("{}"); + messageMockedConstruction = Mockito.mockConstruction(Message.class); + Mockito.doNothing().when(messageCallback).sendRealtimeMessage(any(Message.class)); + ioMessageListener = spy(new IOMessageListener(messageCallback)); + } + + @AfterEach + public void tearDown() throws Exception { + reset(messageCallback); + MODULE_NAME = null; + loggingServiceMockedStatic.close(); + messageMockedConstruction.close(); + } + + /** + * Test onMessage success scenario + */ + @Test + public void testOnMessage() { + try { + ioMessageListener.onMessage(textMessage); + verify(textMessage).acknowledge(); + verify(messageCallback).sendRealtimeMessage(any()); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Start acknowledging message onMessage"); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Finish acknowledging message onMessage"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test onMessage error scenario + */ + @Test + public void throwsExceptionOnMessage() { + try { + Mockito.doThrow(mock(JMSException.class)).when(textMessage).acknowledge(); + ioMessageListener.onMessage(textMessage); + LoggingService.logError(eq(MODULE_NAME), eq("Error acknowledging message"), 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/message_bus/MessageArchiveTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageArchiveTest.java index 87537d2c..e58fd9cb 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,188 +1,203 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.eclipse.iofog.utils.configuration.Configuration; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import java.io.*; -//import java.lang.reflect.Method; -//import java.nio.file.*; -//import java.nio.file.attribute.BasicFileAttributes; -//import java.util.List; -// -//import static java.lang.System.currentTimeMillis; -//import static java.nio.charset.StandardCharsets.UTF_8; -//import static org.junit.Assert.*; -//import static org.junit.Assert.assertEquals; -//import static org.mockito.ArgumentMatchers.*; -//import static org.mockito.Mockito.reset; -//import static org.powermock.api.mockito.Mockito.*; -// -///** -// * @author nehanaithani -// * -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessageArchive.class, Configuration.class, LoggingService.class, File.class, -// RandomAccessFile.class, Runtime.class}) -//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; -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "MessageArchive"; -// timestamp = currentTimeMillis(); -// message = "message"; -// mockStatic(Configuration.class); -// mockStatic(LoggingService.class); +/* + * ******************************************************************************* + * * 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.message_bus; + +import org.eclipse.iofog.local_api.ApiHandlerHelpers; +import org.eclipse.iofog.utils.configuration.Configuration; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import javax.json.Json; +import java.io.*; +import java.lang.reflect.Method; +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; + +import static java.lang.System.currentTimeMillis; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + * + */ +@ExtendWith(MockitoExtension.class) +@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; + private MockedConstruction fileMockedConstruction; + private MockedConstruction randomAccessFileMockedConstruction; + + @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); -// when(files[0].isFile()).thenReturn(true); -// when(file.getName()).thenReturn("message.idx"); + 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); + when(files[0].isFile()).thenReturn(true); + when(file.getName()).thenReturn("message.idx"); + fileMockedConstruction = Mockito.mockConstruction(File.class); + randomAccessFileMockedConstruction = Mockito.mockConstruction(RandomAccessFile.class, (mock, context) -> { + when(mock.getFilePointer()).thenReturn(1L); + when(mock.length()).thenReturn(10L); + 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); -// Mockito.when(Runtime.getRuntime()).thenReturn(runtime); -// Mockito.when(runtime.maxMemory()).thenReturn(1048576460l * 32); -// Mockito.when(runtime.totalMemory()).thenReturn(1l); -// Mockito.when(runtime.freeMemory()).thenReturn(1l); -// messageArchive = spy(new MessageArchive("message.idx")); -// } -// -// @After -// public void tearDown() throws Exception { -// MODULE_NAME = null; -// files = null; -// reset(messageArchive, randomAccessFile); -// deleteDirectory("dir/messages/archive"); -// } -// -// void deleteDirectory(String directoryFilePath) throws IOException { -// Path directory = Paths.get(directoryFilePath); -// -// if (Files.exists(directory)) -// { -// Files.walkFileTree(directory, new SimpleFileVisitor() -// { -// @Override -// public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException -// { -// Files.delete(path); -// return FileVisitResult.CONTINUE; -// } -// -// @Override -// public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException -// { -// Files.delete(directory); -// return FileVisitResult.CONTINUE; -// } -// }); -// } -// } -// /** -// * Test save -// */ -// @Test -// public void testSave() { -// try { -// messageArchive.save(message.getBytes(UTF_8),timestamp); +// 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"); + configurationMockedStatic.close(); + loggingServiceMockedStatic.close(); + fileMockedConstruction.close(); + randomAccessFileMockedConstruction.close(); + } + + void deleteDirectory(String directoryFilePath) throws IOException { + Path directory = Paths.get(directoryFilePath); + + if (Files.exists(directory)) + { + Files.walkFileTree(directory, new SimpleFileVisitor() + { + @Override + public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException + { + Files.delete(path); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path directory, IOException ioException) throws IOException + { + Files.delete(directory); + return FileVisitResult.CONTINUE; + } + }); + } + } + /** + * Test save + */ + @Test + 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(); + } catch (Exception e) { + fail("This shall never happen"); + } + } + + /** + * Test close + */ + @Test + 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(); -// } catch (Exception e) { -// fail("This shall never happen"); -// } -// } -// -// /** -// * Test close -// */ -// @Test -// 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(); -// Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).close(); -// } catch (Exception e) { -// fail("This shall never happen"); -// } -// } -// -// /** -// * Test messageQuery -// */ -// @Test -// public void testMessageQueryWithMessages() { -// try{ -// when(files[0].isFile()).thenReturn(true); -// when(files[0].getName()).thenReturn("message1234545.idx"); -// when(randomAccessFile.getFilePointer()).thenReturn(1l); -// when(randomAccessFile.length()).thenReturn(10l); -// when(randomAccessFile.read(any(byte[].class), anyInt(), anyInt())).thenReturn(1); -// when(randomAccessFile.readLong()).thenReturn(1l); + Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).seek(anyLong()); + Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).length(); + Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).getFilePointer(); + Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).close(); + } catch (Exception e) { + fail("This shall never happen"); + } + } + + /** + * Test messageQuery + */ + @Test + 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(); -// Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).read(any(byte[].class), anyInt(), anyInt()); -// } catch (Exception e){ -// fail("This shall never happen"); -// } -// } -// -// /** -// * Test getDataSize -// */ -// @Test -// public void testGetDataSize() { -// try { -// byte[] bytes = new byte[33]; -// Method method = MessageArchive.class.getDeclaredMethod("getDataSize", byte[].class); -// method.setAccessible(true); -// assertEquals(0, (int) method.invoke(messageArchive, bytes)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file + messageArchive.messageQuery(1, 50); + Mockito.verify(file, Mockito.atLeastOnce()).listFiles(any(FilenameFilter.class)); + Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).getFilePointer(); + Mockito.verify(randomAccessFile, Mockito.atLeastOnce()).read(any(byte[].class), anyInt(), anyInt()); + } catch (Exception e){ + fail("This shall never happen"); + } + } + + /** + * Test getDataSize + */ + @Test + public void testGetDataSize() { + try { + byte[] bytes = new byte[33]; + Method method = MessageArchive.class.getDeclaredMethod("getDataSize", byte[].class); + method.setAccessible(true); + assertEquals(0, (int) method.invoke(messageArchive, bytes)); + } 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/message_bus/MessageBusServerTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusServerTest.java index 314a83be..d2c7677a 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,305 +1,308 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.apache.qpid.jms.JmsConnectionFactory; -//import org.eclipse.iofog.utils.configuration.Configuration; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import jakarta.jms.*; -// -//import java.lang.reflect.Array; -//import java.util.ArrayList; -//import java.util.List; -// -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.any; -//import static org.mockito.Mockito.*; -//import static org.powermock.api.mockito.Mockito.mockStatic; -//import static org.powermock.api.mockito.Mockito.spy; -// -///** -// * @author nehanaithani -// * -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessageBusServer.class, Configuration.class, LoggingService.class,}) -//public class MessageBusServerTest { -// private final List receivers = new ArrayList() { { add("ABCD"); add("EFGH"); } }; -// private MessageBusServer messageBusServer; -// private String MODULE_NAME; -// private Session session; -// private Connection connection; -// private ConnectionFactory connectionFactory; -// private MessageProducer messageProducer; -// private MessageConsumer messageConsumer; -// private TextMessage textMessage; -// private Queue queue; -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "Message Bus Server"; -// messageBusServer = spy(new MessageBusServer()); -// session = mock(Session.class); -// connection = mock(Connection.class); -// messageProducer = mock(MessageProducer.class); -// messageConsumer = mock(MessageConsumer.class); -// textMessage = mock(TextMessage.class); -// queue = mock(Queue.class); -// -// mockStatic(Configuration.class); -// mockStatic(LoggingService.class); -// -// connectionFactory = mock(JmsConnectionFactory.class); -// Mockito.when(connectionFactory.createConnection()).thenReturn(connection); -// Mockito.whenNew(JmsConnectionFactory.class).withArguments(anyString()).thenReturn((JmsConnectionFactory) connectionFactory); -// Mockito.when(Configuration.getMemoryLimit()).thenReturn(1.0f); -// Mockito.when(Configuration.getDiskDirectory()).thenReturn("dir/"); -// Mockito.when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session); -// Mockito.when(session.createTextMessage(any())).thenReturn(textMessage); -// Mockito.when(session.createQueue(any())).thenReturn(queue); -// Mockito.when(session.createConsumer(any())).thenReturn(messageConsumer); -// Mockito.when(session.createProducer(any())).thenReturn(messageProducer); -// } -// -// @After -// public void tearDown() throws Exception { -// messageBusServer.stopServer(); -// reset(messageBusServer); -// reset(connection); -// reset(connectionFactory); -// reset(queue); -// reset(session); -// MODULE_NAME = null; -// } -// -// /** -// * Test start server -// */ -// @Test -// public void testStartServer() { -// try { -// messageBusServer.startServer("localhost", 5672); -// Mockito.verify(connectionFactory, Mockito.atLeastOnce()).createConnection(); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Starting server"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Finished starting server"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test initialize -// */ -// @Test -// public void testInitialize() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// Mockito.verify(connection, Mockito.atLeastOnce()).createSession(false, Session.CLIENT_ACKNOWLEDGE); -// Mockito.verify(connection, Mockito.atLeastOnce()).start(); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Starting initialization"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "Finished initialization"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// -// } -// -// -// /** -// * Test stop server when all consumers and producers are not running -// */ -// @Test -// public void testStopServerWhenNothingIsRunning() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// messageBusServer.stopServer(); -// Mockito.verify(session, Mockito.atLeastOnce()).close(); -// Mockito.verify(connection, Mockito.atLeastOnce()).close(); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "stopping server started"); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logDebug(MODULE_NAME, "stopped server"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test stop server when consumers and producers present -// */ -// @Test -// public void testStopServerWhenProducerAndConsumerAreRunning() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// messageBusServer.createConsumer("consumer1"); -// messageBusServer.createConsumer("consumer2"); -// messageBusServer.createProducer("producer", receivers); -// messageBusServer.stopServer(); -// Mockito.verify(session, Mockito.atLeastOnce()).close(); -// Mockito.verify(connection, Mockito.atLeastOnce()).close(); -// Mockito.verify(messageConsumer, Mockito.atLeast(2)).close(); -// Mockito.verify(messageProducer, Mockito.atLeast(2)).close(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test stop server when server is running -// * consumer and producer throws Exception when closing -// */ -// @Test -// public void throwsExceptionWhenStoppingProducerAndConsumer() { -// try { -// Mockito.doThrow(mock(JMSException.class)).when(messageProducer).close(); -// Mockito.doThrow(mock(JMSException.class)).when(messageConsumer).close(); -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// messageBusServer.createConsumer("consumer"); -// messageBusServer.createProducer("producer", receivers); -// messageBusServer.stopServer(); -// Mockito.verify(messageConsumer, Mockito.atLeastOnce()).close(); -// Mockito.verify(messageProducer, Mockito.atLeast(2)).close(); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Error closing consumer"), any()); -// Mockito.verify(LoggingService.class, atLeastOnce()); -// LoggingService.logError(eq(MODULE_NAME), eq("Error closing producer"), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test createConsumer and getConsumer -// */ -// @Test -// public void testCreateConsumerAndGetConsumer() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// messageBusServer.createConsumer("consumer"); -// assertEquals(messageConsumer, messageBusServer.getConsumer("consumer")); -// Mockito.verify(LoggingService.class, times(1)); -// LoggingService.logDebug(MODULE_NAME, "Starting create consumer"); -// Mockito.verify(LoggingService.class, times(1)); -// LoggingService.logDebug(MODULE_NAME, "Finished create consumer"); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test removeConsumer when consumer is present -// * When getConsumer the removed consumer, MessageBusServer creates the new consumer -// */ -// @Test -// public void testRemoveConsumerWhenConsumerIsPresent() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// messageBusServer.createConsumer("consumer"); -// assertEquals(messageConsumer, messageBusServer.getConsumer("consumer")); -// messageBusServer.removeConsumer("consumer"); -// assertEquals(messageConsumer, messageBusServer.getConsumer("consumer")); -// Mockito.verify(messageBusServer, times(2)).createConsumer(anyString()); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test removeConsumer is called with random Consumer. -// * GetConsumer creates a new consumer in the map if not present -// */ -// @Test -// public void testRemoveConsumerWhenConsumerIsNotPresent() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// messageBusServer.createConsumer("consumer"); -// assertEquals(messageConsumer, messageBusServer.getConsumer("consumer")); -// messageBusServer.removeConsumer("randomConsumer"); -// assertEquals(messageConsumer, messageBusServer.getConsumer("randomConsumer")); -// Mockito.verify(messageBusServer, times(2)).createConsumer(anyString()); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * test CreateProducer and getProducer -// * the same publisher -// */ -// @Test -// public void testCreateProducerAndGetProducer() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// messageBusServer.createProducer("producer", receivers); -// Mockito.verify(messageBusServer).createProducer(anyString(), any()); -// Mockito.verify(session, atLeastOnce()).createProducer(any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * test remove and getProducer -// * the different publisher. GetProducer creates a new publisher if not present -// */ -// @Test -// public void testRemoveProducerAndThenRemoveProducerTheSamePublisher() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// messageBusServer.createProducer("producer", receivers); -// Mockito.verify(messageBusServer).createProducer(anyString(), any()); -// Mockito.verify(session, atLeastOnce()).createProducer(any()); -// messageBusServer.removeProducer("producer"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test create message is equal to mock session -// */ -// @Test -// public void getSession() { -// try { -// messageBusServer.startServer("localhost", 5672); -// messageBusServer.initialize(); -// assertEquals(textMessage, MessageBusServer.createMessage(anyString())); -// Mockito.verify(session, atLeastOnce()).createTextMessage(anyString()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.message_bus; + +import org.apache.qpid.jms.JmsConnectionFactory; +import org.eclipse.iofog.utils.configuration.Configuration; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import jakarta.jms.*; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class MessageBusServerTest { + private final List receivers = new ArrayList() { { add("ABCD"); add("EFGH"); } }; + private MessageBusServer messageBusServer; + private String MODULE_NAME; + private Session session; + private Connection connection; + private MessageProducer messageProducer; + private MessageConsumer messageConsumer; + private TextMessage textMessage; + private Queue queue; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic configurationMockedStatic; + private MockedConstruction jmsConnectionFactoryMockedConstruction; + + @BeforeEach + public void setUp() throws Exception { + MODULE_NAME = "Message Bus Server"; + messageBusServer = spy(new MessageBusServer()); + session = mock(Session.class); + connection = mock(Connection.class); + messageProducer = mock(MessageProducer.class); + messageConsumer = mock(MessageConsumer.class); + textMessage = mock(TextMessage.class); + queue = mock(Queue.class); + configurationMockedStatic = mockStatic(Configuration.class); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + jmsConnectionFactoryMockedConstruction = Mockito.mockConstruction(JmsConnectionFactory.class, (mock, context) -> { + when(mock.createConnection()).thenReturn(connection); + Mockito.when(connection.createSession(anyBoolean(), anyInt())).thenReturn(session); + Mockito.when(session.createTextMessage(any())).thenReturn(textMessage); + Mockito.when(session.createQueue(any())).thenReturn(queue); + Mockito.when(session.createConsumer(any())).thenReturn(messageConsumer); + Mockito.when(session.createProducer(any())).thenReturn(messageProducer); + }); + Mockito.when(Configuration.getMemoryLimit()).thenReturn(1.0f); + Mockito.when(Configuration.getDiskDirectory()).thenReturn("dir/"); + } + + @AfterEach + public void tearDown() throws Exception { + messageBusServer.stopServer(); + reset(messageBusServer); + reset(connection); + reset(queue); + reset(session); + MODULE_NAME = null; + loggingServiceMockedStatic.close(); + configurationMockedStatic.close(); + jmsConnectionFactoryMockedConstruction.close(); + } + + /** + * Test start server + */ + @Test + public void testStartServer() { + try { + messageBusServer.startServer("localhost", 5672); + JmsConnectionFactory mock = jmsConnectionFactoryMockedConstruction.constructed().get(0); + Mockito.verify(mock, Mockito.atLeastOnce()).createConnection(); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Starting server"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Finished starting server"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test initialize + */ + @Test + public void testInitialize() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + Mockito.verify(connection, Mockito.atLeastOnce()).createSession(false, Session.CLIENT_ACKNOWLEDGE); + Mockito.verify(connection, Mockito.atLeastOnce()).start(); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Starting initialization"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "Finished initialization"); + } catch (Exception e) { + fail("This should not happen"); + } + + } + + + /** + * Test stop server when all consumers and producers are not running + */ + @Test + public void testStopServerWhenNothingIsRunning() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + messageBusServer.stopServer(); + Mockito.verify(session, Mockito.atLeastOnce()).close(); + Mockito.verify(connection, Mockito.atLeastOnce()).close(); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "stopping server started"); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logDebug(MODULE_NAME, "stopped server"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test stop server when consumers and producers present + */ + @Test + public void testStopServerWhenProducerAndConsumerAreRunning() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + messageBusServer.createConsumer("consumer1"); + messageBusServer.createConsumer("consumer2"); + messageBusServer.createProducer("producer", receivers); + messageBusServer.stopServer(); + Mockito.verify(session, Mockito.atLeastOnce()).close(); + Mockito.verify(connection, Mockito.atLeastOnce()).close(); + Mockito.verify(messageConsumer, Mockito.atLeast(2)).close(); + Mockito.verify(messageProducer, Mockito.atLeast(2)).close(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test stop server when server is running + * consumer and producer throws Exception when closing + */ + @Test + public void throwsExceptionWhenStoppingProducerAndConsumer() { + try { + Mockito.doThrow(mock(JMSException.class)).when(messageProducer).close(); + Mockito.doThrow(mock(JMSException.class)).when(messageConsumer).close(); + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + messageBusServer.createConsumer("consumer"); + messageBusServer.createProducer("producer", receivers); + messageBusServer.stopServer(); + Mockito.verify(messageConsumer, Mockito.atLeastOnce()).close(); + Mockito.verify(messageProducer, Mockito.atLeast(2)).close(); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Error closing consumer"), any()); + Mockito.verify(LoggingService.class, atLeastOnce()); + LoggingService.logError(eq(MODULE_NAME), eq("Error closing producer"), any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test createConsumer and getConsumer + */ + @Test + public void testCreateConsumerAndGetConsumer() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + messageBusServer.createConsumer("consumer"); + assertEquals(messageConsumer, messageBusServer.getConsumer("consumer")); + Mockito.verify(LoggingService.class, times(1)); + LoggingService.logDebug(MODULE_NAME, "Starting create consumer"); + Mockito.verify(LoggingService.class, times(1)); + LoggingService.logDebug(MODULE_NAME, "Finished create consumer"); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test removeConsumer when consumer is present + * When getConsumer the removed consumer, MessageBusServer creates the new consumer + */ + @Test + public void testRemoveConsumerWhenConsumerIsPresent() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + messageBusServer.createConsumer("consumer"); + assertEquals(messageConsumer, messageBusServer.getConsumer("consumer")); + messageBusServer.removeConsumer("consumer"); + assertEquals(messageConsumer, messageBusServer.getConsumer("consumer")); + Mockito.verify(messageBusServer, times(2)).createConsumer(anyString()); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test removeConsumer is called with random Consumer. + * GetConsumer creates a new consumer in the map if not present + */ + @Test + public void testRemoveConsumerWhenConsumerIsNotPresent() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + messageBusServer.createConsumer("consumer"); + assertEquals(messageConsumer, messageBusServer.getConsumer("consumer")); + messageBusServer.removeConsumer("randomConsumer"); + assertEquals(messageConsumer, messageBusServer.getConsumer("randomConsumer")); + Mockito.verify(messageBusServer, times(2)).createConsumer(anyString()); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * test CreateProducer and getProducer + * the same publisher + */ + @Test + public void testCreateProducerAndGetProducer() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + messageBusServer.createProducer("producer", receivers); + Mockito.verify(messageBusServer).createProducer(anyString(), any()); + Mockito.verify(session, atLeastOnce()).createProducer(any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * test remove and getProducer + * the different publisher. GetProducer creates a new publisher if not present + */ + @Test + public void testRemoveProducerAndThenRemoveProducerTheSamePublisher() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + messageBusServer.createProducer("producer", receivers); + Mockito.verify(messageBusServer).createProducer(anyString(), any()); + Mockito.verify(session, atLeastOnce()).createProducer(any()); + messageBusServer.removeProducer("producer"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test create message is equal to mock session + */ + @Test + public void getSession() { + try { + messageBusServer.startServer("localhost", 5672); + messageBusServer.initialize(); + assertEquals(textMessage, MessageBusServer.createMessage(anyString())); + Mockito.verify(session, atLeastOnce()).createTextMessage(anyString()); + } 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/message_bus/MessageBusStatusTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusStatusTest.java index ad3bfa40..edd00aa1 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,124 +1,126 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.junit.After; -//import org.junit.Before; -//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.*; -//import static org.mockito.Mockito.reset; -//import static org.powermock.api.mockito.Mockito.spy; -// -///** -// * @author nehanaithani -// * -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessageBusStatus.class}) -//public class MessageBusStatusTest { -// private MessageBusStatus messageBusStatus; -// private long processedMessages; -// private float averageSpeed; -// -// @Before -// public void setUp() throws Exception { -// messageBusStatus = spy(new MessageBusStatus()); -// processedMessages = 1000L; -// averageSpeed = 1000f; -// -// } -// -// @After -// public void tearDown() throws Exception { -// reset(messageBusStatus); -// processedMessages = 0; -// averageSpeed = 0; -// } -// -// /** -// * Test getProcessedMessages -// */ -// @Test -// public void testGetProcessedMessages() { -// assertEquals(0, messageBusStatus.getProcessedMessages()); -// } -// -// /** -// * Test increasePublishedMessagesPerMicroservice -// */ -// @Test -// public void testIncreasePublishedMessagesPerMicroservice() { -// assertEquals(1, messageBusStatus.increasePublishedMessagesPerMicroservice(null).getProcessedMessages()); -// assertEquals(2, messageBusStatus.increasePublishedMessagesPerMicroservice("microservice").getProcessedMessages()); -// } -// -// /** -// * Test getPublishedMessagesPerMicroservice -// */ -// @Test -// public void testGetPublishedMessagesPerMicroservice() { -// assertEquals(0, messageBusStatus.getPublishedMessagesPerMicroservice().size()); -// assertEquals(1, messageBusStatus.increasePublishedMessagesPerMicroservice("microservice") -// .getPublishedMessagesPerMicroservice().size()); -// } -// -// /** -// * Test getPublishedMessagesPerMicroservice of specific microservice -// */ -// @Test -// public void testGetPublishedMessagesPerMicroserviceOfSpecificMicroservice() { -// assertEquals(1, messageBusStatus. -// increasePublishedMessagesPerMicroservice(null) -// .getPublishedMessagesPerMicroservice(null), 0); -// assertEquals(1, messageBusStatus -// .increasePublishedMessagesPerMicroservice("microservice"). -// getPublishedMessagesPerMicroservice("microservice"), 0); -// } -// -// /** -// * Test get and set averageSpeed -// */ -// @Test -// public void testGetAndSetAverageSpeed() { -// assertEquals(0, messageBusStatus.getAverageSpeed(), 0); -// assertEquals(averageSpeed, messageBusStatus.setAverageSpeed(averageSpeed).getAverageSpeed(), 0); -// } -// -// /** -// * Test removePublishedMessagesPerMicroservice -// */ -// @Test -// public void testRemovePublishedMessagesPerMicroservice() { -// messageBusStatus.removePublishedMessagesPerMicroservice(null); -// messageBusStatus.increasePublishedMessagesPerMicroservice("microservice"); -// assertEquals(1, messageBusStatus.getPublishedMessagesPerMicroservice().size()); -// messageBusStatus.removePublishedMessagesPerMicroservice("microservice"); -// assertEquals(0, messageBusStatus.getPublishedMessagesPerMicroservice().size()); -// } -// -// /** -// * Test GetJsonPublishedMessagesPerMicroservice when microservices are published -// * and not published -// */ -// @Test -// public void testGetJsonPublishedMessagesPerMicroservice() { -// assertFalse(messageBusStatus.getJsonPublishedMessagesPerMicroservice().contains("id")); -// messageBusStatus.increasePublishedMessagesPerMicroservice("microservice"); -// assertTrue(messageBusStatus.getJsonPublishedMessagesPerMicroservice().contains("id")); -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.message_bus; + + +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.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.spy; + +/** + * @author nehanaithani + * + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class MessageBusStatusTest { + private MessageBusStatus messageBusStatus; + private long processedMessages; + private float averageSpeed; + + @BeforeEach + public void setUp() throws Exception { + messageBusStatus = spy(new MessageBusStatus()); + processedMessages = 1000L; + averageSpeed = 1000f; + + } + + @AfterEach + public void tearDown() throws Exception { + reset(messageBusStatus); + processedMessages = 0; + averageSpeed = 0; + } + + /** + * Test getProcessedMessages + */ + @Test + public void testGetProcessedMessages() { + assertEquals(0, messageBusStatus.getProcessedMessages()); + } + + /** + * Test increasePublishedMessagesPerMicroservice + */ + @Test + public void testIncreasePublishedMessagesPerMicroservice() { + assertEquals(1, messageBusStatus.increasePublishedMessagesPerMicroservice(null).getProcessedMessages()); + assertEquals(2, messageBusStatus.increasePublishedMessagesPerMicroservice("microservice").getProcessedMessages()); + } + + /** + * Test getPublishedMessagesPerMicroservice + */ + @Test + public void testGetPublishedMessagesPerMicroservice() { + assertEquals(0, messageBusStatus.getPublishedMessagesPerMicroservice().size()); + assertEquals(1, messageBusStatus.increasePublishedMessagesPerMicroservice("microservice") + .getPublishedMessagesPerMicroservice().size()); + } + + /** + * Test getPublishedMessagesPerMicroservice of specific microservice + */ + @Test + public void testGetPublishedMessagesPerMicroserviceOfSpecificMicroservice() { + assertEquals(1, messageBusStatus. + increasePublishedMessagesPerMicroservice(null) + .getPublishedMessagesPerMicroservice(null), 0); + assertEquals(1, messageBusStatus + .increasePublishedMessagesPerMicroservice("microservice"). + getPublishedMessagesPerMicroservice("microservice"), 0); + } + + /** + * Test get and set averageSpeed + */ + @Test + public void testGetAndSetAverageSpeed() { + assertEquals(0, messageBusStatus.getAverageSpeed(), 0); + assertEquals(averageSpeed, messageBusStatus.setAverageSpeed(averageSpeed).getAverageSpeed(), 0); + } + + /** + * Test removePublishedMessagesPerMicroservice + */ + @Test + public void testRemovePublishedMessagesPerMicroservice() { + messageBusStatus.removePublishedMessagesPerMicroservice(null); + messageBusStatus.increasePublishedMessagesPerMicroservice("microservice"); + assertEquals(1, messageBusStatus.getPublishedMessagesPerMicroservice().size()); + messageBusStatus.removePublishedMessagesPerMicroservice("microservice"); + assertEquals(0, messageBusStatus.getPublishedMessagesPerMicroservice().size()); + } + + /** + * Test GetJsonPublishedMessagesPerMicroservice when microservices are published + * and not published + */ + @Test + public void testGetJsonPublishedMessagesPerMicroservice() { + assertFalse(messageBusStatus.getJsonPublishedMessagesPerMicroservice().contains("id")); + messageBusStatus.increasePublishedMessagesPerMicroservice("microservice"); + assertTrue(messageBusStatus.getJsonPublishedMessagesPerMicroservice().contains("id")); + } +} \ No newline at end of file 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 2eb42c89..4041cca6 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,355 +1,374 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.eclipse.iofog.microservice.MicroserviceManager; -//import org.eclipse.iofog.microservice.Route; -//import org.eclipse.iofog.resource_consumption_manager.ResourceConsumptionManager; -//import org.eclipse.iofog.status_reporter.StatusReporter; -//import org.eclipse.iofog.supervisor.SupervisorStatus; -//import org.eclipse.iofog.utils.Constants; -//import org.eclipse.iofog.utils.Orchestrator; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import jakarta.jms.MessageConsumer; -//import jakarta.jms.MessageProducer; -//import javax.json.Json; -//import javax.json.JsonObject; -//import javax.json.JsonObjectBuilder; -//import java.lang.reflect.Field; -//import java.util.ArrayList; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.anyString; -//import static org.mockito.Mockito.*; -//import static org.powermock.api.mockito.Mockito.whenNew; -// -///** -// * @author nehanaithani -// * -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessageBus.class, MicroserviceManager.class, MessageBusServer.class, MessageProducer.class, -// LoggingService.class, MessageReceiver.class, MessageConsumer.class ,MessagePublisher.class, -// StatusReporter.class, MessageBusStatus.class, SupervisorStatus.class, Thread.class, Orchestrator.class}) -//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; -// List receivers; -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "Message Bus"; -// messageBus = spy(MessageBus.class); -// setMock(messageBus); -// Mockito.mockStatic(MicroserviceManager.class); -// Mockito.mockStatic(LoggingService.class); -// Mockito.mockStatic(StatusReporter.class); -// microserviceManager = mock(MicroserviceManager.class); -// messageBusServer = mock(MessageBusServer.class); -// messageReceiver = mock(MessageReceiver.class); -// messageConsumer = mock(MessageConsumer.class); -// messagePublisher = mock(MessagePublisher.class); -// messageBusStatus = mock(MessageBusStatus.class); -// supervisorStatus = mock(SupervisorStatus.class); -// Mockito.when(MicroserviceManager.getInstance()).thenReturn(microserviceManager); +/* + * ******************************************************************************* + * * 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.message_bus; + +import org.eclipse.iofog.microservice.MicroserviceManager; +import org.eclipse.iofog.microservice.Route; +import org.eclipse.iofog.resource_consumption_manager.ResourceConsumptionManager; +import org.eclipse.iofog.status_reporter.StatusReporter; +import org.eclipse.iofog.supervisor.SupervisorStatus; +import org.eclipse.iofog.utils.Constants; +import org.eclipse.iofog.utils.Orchestrator; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageProducer; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +@Disabled +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; + List receivers; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic statusReporterMockedStatic; + private MockedStatic microserviceManagerMockedStatic; + private MockedConstruction messageBusServerMockedConstruction; + private MockedConstruction messageReceiverMockedConstruction; + private MockedConstruction messagePublisherMockedConstruction; + private MockedConstruction orchestratorMockedConstruction; + + @BeforeEach + public void setUp() throws Exception { + MODULE_NAME = "Message Bus"; + messageBus = spy(MessageBus.class); + setMock(messageBus); + microserviceManagerMockedStatic = Mockito.mockStatic(MicroserviceManager.class); + loggingServiceMockedStatic = Mockito.mockStatic(LoggingService.class); + statusReporterMockedStatic = Mockito.mockStatic(StatusReporter.class); + microserviceManager = mock(MicroserviceManager.class); + messageBusServer = mock(MessageBusServer.class); + messageReceiver = mock(MessageReceiver.class); + messageConsumer = mock(MessageConsumer.class); + messagePublisher = mock(MessagePublisher.class); + messageBusStatus = mock(MessageBusStatus.class); + 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); -// route = new Route(); -// receivers = new ArrayList<>(); -// receiverValue = "1"; -// receivers.add(receiverValue); -// receivers.add("2"); -// receivers.add("3"); -// route.setReceivers(receivers); -// mapRoutes = new HashMap<>(); -// mapRoutes.put("1", route); -// publishedMessagesPerMicroservice = new HashMap<>(); -// publishedMessagesPerMicroservice.put("1", 100l); -// Mockito.when(microserviceManager.getRoutes()).thenReturn(mapRoutes); -// Mockito.when(messageBusStatus.getPublishedMessagesPerMicroservice()).thenReturn(publishedMessagesPerMicroservice); -// Mockito.when(messageBusServer.getConsumer(any())).thenReturn(mock(MessageConsumer.class)); -// Mockito.when(messageBusServer.getProducer(any(), any())).thenReturn(mock(List.class)); -// Mockito.when(messageBusServer.isConnected()).thenReturn(true); -// Mockito.doNothing().when(messageReceiver).enableRealTimeReceiving(); -// Mockito.doNothing().when(messageReceiver).disableRealTimeReceiving(); -// Mockito.when(StatusReporter.getMessageBusStatus()).thenReturn(messageBusStatus); -// Mockito.when(StatusReporter.setMessageBusStatus()).thenReturn(messageBusStatus); -// Mockito.when(StatusReporter.setSupervisorStatus()).thenReturn(supervisorStatus); -// orchestrator = mock(Orchestrator.class); // whenNew(Orchestrator.class).withNoArguments().thenReturn(orchestrator); -// -// MessagePublisher messagePublisher = mock(MessagePublisher.class); // whenNew(MessagePublisher.class).withAnyArguments().thenReturn(messagePublisher); -// } -// -// @After -// public void tearDown() throws Exception { -// MODULE_NAME = null; -// receiverValue = null; -// Field instance = ResourceConsumptionManager.class.getDeclaredField("instance"); -// instance.setAccessible(true); -// instance.set(null, null); -// mapRoutes = null; -// publishedMessagesPerMicroservice = null; -// receivers = null; -// reset(messageBus); -// reset(messageBusServer); -// reset(messagePublisher); -// reset(messageConsumer); -// reset(messageReceiver); -// reset(microserviceManager); -// } -// /** -// * Set a mock to the {@link MessageBus} 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(MessageBus mock) { -// try { -// Field instance = MessageBus.class.getDeclaredField("instance"); -// instance.setAccessible(true); -// instance.set(instance, mock); -// } catch (Exception e) { -// throw new RuntimeException(e); -// } -// } -// -// /** -// * Asserts module index of MessageBus is equal to constant value -// */ -// @Test -// public void testGetModuleIndex() { -// assertEquals(Constants.MESSAGE_BUS, messageBus.getModuleIndex()); -// } -// -// /** -// * Asserts module name of messageBus is equal to constant value -// */ -// @Test -// public void testGetModuleName() { -// assertEquals("Message Bus", messageBus.getModuleName()); -// } -// -// /** -// * Assert mock is same as MessageBus.getInstance() -// */ -// @Test -// public void testGetInstance() { -// assertSame(messageBus, MessageBus.getInstance()); -// } -// -// /** -// * Test enableRealTimeReceiving when receiver passed is null -// */ -// @Test (timeout = 100000L) -// public void testEnableRealTimeReceivingWhenReceiverPassedIsNull() { -// initiateMockStart(); -// messageBus.enableRealTimeReceiving(null); -// Mockito.verify(messageReceiver, never()).enableRealTimeReceiving(); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME,"Starting enable real time receiving"); -// Mockito.verify(LoggingService.class, never()); -// LoggingService.logDebug(MODULE_NAME,"Finishing enable real time receiving"); -// } -// -// /** -// * Test enableRealTimeReceiving when receiver is not found -// */ -// @Test (timeout = 100000L) -// public void testEnableRealTimeReceivingWhenReceiverIsNotFound() { -// initiateMockStart(); -// messageBus.enableRealTimeReceiving("receiver"); -// Mockito.verify(messageReceiver, never()).enableRealTimeReceiving(); -// Mockito.verify(LoggingService.class, never()); -// LoggingService.logInfo(MODULE_NAME,"Finishing enable real time receiving"); -// } -// -// /** -// * Test disableRealTimeReceiving when receiver passed is null -// */ -// @Test (timeout = 100000L) -// public void testDisableRealTimeReceivingWhenReceiverPassedIsNull() { -// initiateMockStart(); -// messageBus.disableRealTimeReceiving(null); -// Mockito.verify(messageReceiver, never()).disableRealTimeReceiving(); -// Mockito.verify(LoggingService.class, never()); -// LoggingService.logInfo(MODULE_NAME,"Finishing disable real time receiving"); -// } -// -// /** -// * Test disableRealTimeReceiving when receiver is not null -// */ -// @Test (timeout = 100000L) -// public void testDisableRealTimeReceivingWhenReceiverPassedIsNotFound() { -// initiateMockStart(); -// messageBus.disableRealTimeReceiving("receiver"); -// Mockito.verify(messageReceiver, never()).disableRealTimeReceiving(); -// } -// -// /** -// * Test update -// */ -// @Test -// public void testUpdate() { -// initiateMockStart(); -// try { -// messageBus.update(); -// Mockito.verify(microserviceManager, atLeastOnce()).getLatestMicroservices(); -// } catch (Exception e) { -// fail("Shouldn't have happened"); -// } -// } -// -// @Test (timeout = 100000L) -// public void testInstanceConfigUpdated() { -// initiateMockStart(); -// messageBus.instanceConfigUpdated(); -// } -// -// /** -// * Test start -// */ -// @Test (timeout = 100000L) -// public void testStart() { -// try { -// initiateMockStart(); -// Mockito.verify(messageBusServer, atLeastOnce()).startServer("localhost", 5672); -// Mockito.verify(messageBusServer, atLeastOnce()).initialize(); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME,"STARTING MESSAGE BUS SERVER"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME,"MESSAGE BUS SERVER STARTED"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test stop -// */ -// @Test (timeout = 100000L) -// public void testStop() { -// try { -// initiateMockStart(); -// messageBus.stop(); -// Mockito.verify(messageBusServer, atLeastOnce()).stopServer(); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME,"Start closing receivers and publishers and stops ActiveMQ server"); -// Mockito.verify(LoggingService.class); -// LoggingService.logInfo(MODULE_NAME,"Finished closing receivers and publishers and stops ActiveMQ server"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test stop when messageBusServer.stopServer() throws exception -// */ -// @Test (timeout = 100000L) -// public void throwsExceptionWhenMessageServerStopIsCalled() { -// try { -// Mockito.doThrow(mock(Exception.class)).when(messageBusServer).stopServer(); -// initiateMockStart(); -// messageBus.stop(); -// Mockito.verify(messageBusServer, atLeastOnce()).stopServer(); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Error closing receivers and publishers and stops ActiveMQ server"), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test get receiver -// */ -// @Test (timeout = 100000L) -// public void testGetReceiver() { -// initiateMockStart(); -// assertNull(messageBus.getReceiver(receiverValue)); -// } -// -// /** -// * Test getNextId -// */ -// @Test -// public void testGetNextId() { -// initiateMockStart(); -// assertNotNull(messageBus.getNextId()); -// } -// -// /** -// * Test getRoutes -// */ -// @Test (timeout = 100000L) -// public void testGetRoutes() { + route = new Route(); + receivers = new ArrayList<>(); + receiverValue = "1"; + receivers.add(receiverValue); + receivers.add("2"); + receivers.add("3"); + route.setReceivers(receivers); + mapRoutes = new HashMap<>(); + mapRoutes.put("1", route); + publishedMessagesPerMicroservice = new HashMap<>(); + publishedMessagesPerMicroservice.put("1", 100l); + Mockito.when(microserviceManager.getRoutes()).thenReturn(mapRoutes); + Mockito.when(messageBusStatus.getPublishedMessagesPerMicroservice()).thenReturn(publishedMessagesPerMicroservice); + Mockito.when(messageBusServer.getConsumer(any())).thenReturn(mock(MessageConsumer.class)); + Mockito.when(messageBusServer.getProducer(any(), any())).thenReturn(mock(List.class)); + Mockito.when(messageBusServer.isConnected()).thenReturn(true); + Mockito.doNothing().when(messageReceiver).enableRealTimeReceiving(); + Mockito.doNothing().when(messageReceiver).disableRealTimeReceiving(); + Mockito.when(StatusReporter.getMessageBusStatus()).thenReturn(messageBusStatus); + Mockito.when(StatusReporter.setMessageBusStatus()).thenReturn(messageBusStatus); + Mockito.when(StatusReporter.setSupervisorStatus()).thenReturn(supervisorStatus); + orchestrator = mock(Orchestrator.class); + +// MessagePublisher messagePublisher = mock(MessagePublisher.class); + + } + + @AfterEach + public void tearDown() throws Exception { + MODULE_NAME = null; + receiverValue = null; + Field instance = ResourceConsumptionManager.class.getDeclaredField("instance"); + instance.setAccessible(true); + instance.set(null, null); + mapRoutes = null; + publishedMessagesPerMicroservice = null; + receivers = null; + reset(messageBus); + reset(messageBusServer); + reset(messagePublisher); + reset(messageConsumer); + reset(messageReceiver); + reset(microserviceManager); + loggingServiceMockedStatic.close(); + statusReporterMockedStatic.close(); + microserviceManagerMockedStatic.close(); + messagePublisherMockedConstruction.close(); + messageReceiverMockedConstruction.close(); + messageBusServerMockedConstruction.close(); + orchestratorMockedConstruction.close(); + } + /** + * Set a mock to the {@link MessageBus} 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(MessageBus mock) { + try { + Field instance = MessageBus.class.getDeclaredField("instance"); + instance.setAccessible(true); + instance.set(instance, mock); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Asserts module index of MessageBus is equal to constant value + */ + @Test + public void testGetModuleIndex() { + assertEquals(Constants.MESSAGE_BUS, messageBus.getModuleIndex()); + } + + /** + * Asserts module name of messageBus is equal to constant value + */ + @Test + public void testGetModuleName() { + assertEquals("Message Bus", messageBus.getModuleName()); + } + + /** + * Assert mock is same as MessageBus.getInstance() + */ + @Test + public void testGetInstance() { + assertSame(messageBus, MessageBus.getInstance()); + } + + /** + * Test enableRealTimeReceiving when receiver passed is null + */ + @Test + public void testEnableRealTimeReceivingWhenReceiverPassedIsNull() { + initiateMockStart(); + messageBus.enableRealTimeReceiving(null); + Mockito.verify(messageReceiver, never()).enableRealTimeReceiving(); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME,"Starting enable real time receiving"); + Mockito.verify(LoggingService.class, never()); + LoggingService.logDebug(MODULE_NAME,"Finishing enable real time receiving"); + } + + /** + * Test enableRealTimeReceiving when receiver is not found + */ + @Test + public void testEnableRealTimeReceivingWhenReceiverIsNotFound() { + initiateMockStart(); + messageBus.enableRealTimeReceiving("receiver"); + Mockito.verify(messageReceiver, never()).enableRealTimeReceiving(); + Mockito.verify(LoggingService.class, never()); + LoggingService.logInfo(MODULE_NAME,"Finishing enable real time receiving"); + } + + /** + * Test disableRealTimeReceiving when receiver passed is null + */ + @Test + public void testDisableRealTimeReceivingWhenReceiverPassedIsNull() { + initiateMockStart(); + messageBus.disableRealTimeReceiving(null); + Mockito.verify(messageReceiver, never()).disableRealTimeReceiving(); + Mockito.verify(LoggingService.class, never()); + LoggingService.logInfo(MODULE_NAME,"Finishing disable real time receiving"); + } + + /** + * Test disableRealTimeReceiving when receiver is not null + */ + @Test + public void testDisableRealTimeReceivingWhenReceiverPassedIsNotFound() { + initiateMockStart(); + messageBus.disableRealTimeReceiving("receiver"); + Mockito.verify(messageReceiver, never()).disableRealTimeReceiving(); + } + + /** + * Test update + */ + @Test + public void testUpdate() { + initiateMockStart(); + try { + messageBus.update(); + Mockito.verify(microserviceManager, atLeastOnce()).getLatestMicroservices(); + } catch (Exception e) { + fail("Shouldn't have happened"); + } + } + + @Test + public void testInstanceConfigUpdated() { // initiateMockStart(); -// assertNotNull(messageBus.getRoutes()); -// assertEquals(mapRoutes, messageBus.getRoutes()); -// } -// -// /** -// * Helper method -// */ -// public void initiateMockStart() { -// speedThread = mock(Thread.class); -// Thread startThread = mock(Thread.class); -// try { + messageBus.instanceConfigUpdated(); + } + + /** + * Test start + */ + @Test + public void testStart() { + try { + initiateMockStart(); + Mockito.verify(messageBusServer, atLeastOnce()).startServer("localhost", 5672); + Mockito.verify(messageBusServer, atLeastOnce()).initialize(); + Mockito.verify(LoggingService.class); + LoggingService.logInfo(MODULE_NAME,"STARTING MESSAGE BUS SERVER"); + Mockito.verify(LoggingService.class); + LoggingService.logInfo(MODULE_NAME,"MESSAGE BUS SERVER STARTED"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test stop + */ + @Test + public void testStop() { + try { + initiateMockStart(); + messageBus.stop(); + Mockito.verify(messageBusServer, atLeastOnce()).stopServer(); + Mockito.verify(LoggingService.class); + LoggingService.logInfo(MODULE_NAME,"Start closing receivers and publishers and stops ActiveMQ server"); + Mockito.verify(LoggingService.class); + LoggingService.logInfo(MODULE_NAME,"Finished closing receivers and publishers and stops ActiveMQ server"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test stop when messageBusServer.stopServer() throws exception + */ + @Test + public void throwsExceptionWhenMessageServerStopIsCalled() { + try { + Mockito.doThrow(mock(Exception.class)).when(messageBusServer).stopServer(); + initiateMockStart(); + messageBus.stop(); + Mockito.verify(messageBusServer, atLeastOnce()).stopServer(); + Mockito.verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Error closing receivers and publishers and stops ActiveMQ server"), any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test get receiver + */ + @Test + public void testGetReceiver() { + initiateMockStart(); + assertNull(messageBus.getReceiver(receiverValue)); + } + + /** + * Test getNextId + */ + @Test + public void testGetNextId() { + initiateMockStart(); + assertNotNull(messageBus.getNextId()); + } + + /** + * Test getRoutes + */ + @Test + public void testGetRoutes() { + initiateMockStart(); + assertNotNull(messageBus.getRoutes()); + assertEquals(mapRoutes, messageBus.getRoutes()); + } + + /** + * 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(speedThread).start(); -// Mockito.doNothing().when(startThread).start(); -// messageBus.start(); -// -// JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); -// JsonObject jsonObject = jsonObjectBuilder -// .add("routerHost", "localhost") -// .add("routerPort", 5672).build(); -// when(orchestrator.request(any(), any(), any(), any())).thenReturn(jsonObject); -// -// messageBus.startServer(); -// } catch (Exception e) { -// fail("this should not happen"); -// } -// -// } -//} \ No newline at end of file + Mockito.doNothing().when(messageBus).start(); + messageBus.start(); + + JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); + JsonObject jsonObject = jsonObjectBuilder + .add("routerHost", "localhost") + .add("routerPort", 5672).build(); + when(orchestrator.request(any(), any(), any(), any())).thenReturn(jsonObject); + + messageBus.startServer(); + } 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/message_bus/MessageBusUtilTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageBusUtilTest.java index 1725f5f4..b18204e3 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,291 +1,295 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.eclipse.iofog.microservice.Route; -//import org.eclipse.iofog.status_reporter.StatusReporter; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import java.util.ArrayList; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//import static java.lang.System.currentTimeMillis; -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.*; -// -//import static org.powermock.api.mockito.Mockito.*; -// -///** -// * @author nehanaithani -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessageBusUtil.class, MessageBus.class, StatusReporter.class, MessageBusStatus.class, Message.class, LoggingService.class, MessagePublisher.class, MessageReceiver.class, Route.class}) -//public class MessageBusUtilTest { -// private MessageBusUtil messageBusUtil; -// private MessageBus messageBus; -// private MessageBusStatus messageBusStatus; -// private Message message; -// private String MODULE_NAME; -// private MessagePublisher messagePublisher; -// private MessageReceiver messageReceiver; -// private Route route; -// private List messages; -// private List receivers; -// private Map routes; -// -// -// @Before -// public void setUp() throws Exception { -// MODULE_NAME = "Message Bus Util"; -// messageBus = mock(MessageBus.class); -// message = mock(Message.class); -// messagePublisher = mock(MessagePublisher.class); -// messageReceiver = mock(MessageReceiver.class); -// route = mock(Route.class); -// mockStatic(LoggingService.class); -// mockStatic(MessageBus.class); -// mockStatic(StatusReporter.class); -// messages = mock(ArrayList.class); -// receivers = mock(ArrayList.class); -// routes = mock(HashMap.class); -// messageBusStatus = mock(MessageBusStatus.class); -// Mockito.when(MessageBus.getInstance()).thenReturn(messageBus); -// Mockito.when(messageBus.getReceiver(any())).thenReturn(messageReceiver); -// Mockito.when(messageBus.getPublisher(any())).thenReturn(messagePublisher); -// Mockito.when(messageBus.getRoutes()).thenReturn(routes); -// Mockito.when(routes.get(any())).thenReturn(route); -// Mockito.when(route.getReceivers()).thenReturn(receivers); -// Mockito.when(messageReceiver.getMessages()).thenReturn(messages); -// Mockito.when(StatusReporter.setMessageBusStatus()).thenReturn(messageBusStatus); -// Mockito.when(receivers.contains(eq("receiver"))).thenReturn(true); -// messageBusUtil = spy(new MessageBusUtil()); -// } -// -// @After -// public void tearDown() throws Exception { -// MODULE_NAME = null; -// Mockito.reset(messageBusUtil); -// Mockito.reset(messageBusStatus); -// Mockito.reset(message); -// Mockito.reset(messageBus); -// Mockito.reset(messagePublisher); -// Mockito.reset(messageReceiver); -// Mockito.reset(route); -// } -// -// /** -// * Test publishMessage when messageBus.getPublisher is null -// */ -// @Test -// public void testPublishMessageWhenPublisherIsNull() { -// try { -// Mockito.when(messageBus.getPublisher(message.getPublisher())).thenReturn(null); -// messageBusUtil.publishMessage(message); -// Mockito.verify(messageBus).getPublisher(any()); -// Mockito.verify(messagePublisher, Mockito.never()).publish(any(Message.class)); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Start publish message"); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Finishing publish message"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test publishMessage when messageBus.getPublisher is not null -// */ -// @Test -// public void testPublishMessageWhenPublisherIsNotNull() { -// try { -// Mockito.when(messageBus.getPublisher(message.getPublisher())).thenReturn(messagePublisher); -// messageBusUtil.publishMessage(message); -// Mockito.verify(messageBus).getPublisher(any()); -// Mockito.verify(messagePublisher).publish(any(Message.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test publishMessage -// * publisher throws Exception -// */ -// @Test -// public void throwsExceptionWhenPublisherIsCalled() { -// Mockito.when(messageBus.getPublisher(message.getPublisher())).thenReturn(messagePublisher); -// Mockito.when(messagePublisher.getName()).thenReturn("MP"); -// try { -// Mockito.doThrow(mock(Exception.class)).when(messagePublisher).publish(any()); -// messageBusUtil.publishMessage(message); -// Mockito.verify(messageBus).getPublisher(any()); -// Mockito.verify(messagePublisher).publish(any(Message.class)); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Unable to send message : Message Publisher (MP)"), any()); -// } catch (Exception e) { -// fail("This Should not happen"); -// } -// } -// -// /** -// * Test getMessages MessageReceiver is null -// */ -// @Test -// public void testGetMessagesWhenMessageReceiverIsNull() { -// try { -// Mockito.when(messageBus.getReceiver(any())).thenReturn(null); -// assertEquals(0, messageBusUtil.getMessages("receiver").size()); -// Mockito.verify(messageBus).getReceiver(any()); -// Mockito.verify(messageReceiver, Mockito.never()).getMessages(); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Starting get message"); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Finishing get message"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getMessages MessageReceiver is not null -// */ -// @Test -// public void testGetMessagesWhenMessageReceiverIsNotNull() { -// try { -// assertEquals(messages, messageBusUtil.getMessages("receiver")); -// Mockito.verify(messageBus).getReceiver(any()); -// Mockito.verify(messageReceiver).getMessages(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getMessages when MessagePublisher throws exception -// */ -// @Test -// public void throwsExceptionWhenMessagePublisherIsCalledInGetMessages() { -// try { -// Mockito.doThrow(mock(Exception.class)).when(messageReceiver).getMessages(); -// assertEquals(0, messageBusUtil.getMessages("receiver").size()); -// Mockito.verify(messageBus).getReceiver(any()); -// Mockito.verify(messageReceiver).getMessages(); -// Mockito.verify(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("unable to receive messages : Message Receiver (receiver)"), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// -// } -// -// /** -// * Test MessageQuery when route is null -// */ -// @Test -// public void testMessageQueryWhenRouteIsNull() { -// try { -// Mockito.when(routes.get(any())).thenReturn(null); -// assertNull(messageBusUtil.messageQuery("publisher", "receiver", currentTimeMillis(), 100l)); -// Mockito.verify(messageBus).getRoutes(); -// Mockito.verify(messageBus, Mockito.never()).getPublisher(any()); -// Mockito.verify(messagePublisher, Mockito.never()).messageQuery(anyLong(), anyLong()); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Starting message query"); -// Mockito.verify(LoggingService.class, Mockito.never()); -// LoggingService.logDebug(MODULE_NAME, "Finishing message query"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test MessageQuery when input parameter to is less than from -// */ -// @Test -// public void testMessageQueryWhenInputParamToIsLessThanFrom() { -// try { -// assertNull(messageBusUtil.messageQuery("publisher", "receiver", currentTimeMillis(), 100l)); -// Mockito.verify(messageBus).getRoutes(); -// Mockito.verify(messageBus, Mockito.never()).getPublisher(any()); -// Mockito.verify(messagePublisher, Mockito.never()).messageQuery(anyLong(), anyLong()); -// Mockito.verify(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Starting message query"); -// Mockito.verify(LoggingService.class, Mockito.never()); -// LoggingService.logDebug(MODULE_NAME, "Finishing message query"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test MessageQuery when route doesn't have receiver -// */ -// @Test -// public void testMessageQueryWhenRouteDoseNotHaveReceiver() { -// try { -// Mockito.when(receivers.contains(eq("receiver"))).thenReturn(false); -// assertNull(messageBusUtil.messageQuery("publisher", "receiver", 100l, currentTimeMillis())); -// Mockito.verify(messageBus).getRoutes(); -// Mockito.verify(route).getReceivers(); -// Mockito.verify(messageBus, Mockito.never()).getPublisher(any()); -// Mockito.verify(messagePublisher, Mockito.never()).messageQuery(anyLong(), anyLong()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test MessageQuery when route have receiver -// * messageBus doesn't have publisher -// */ -// @Test -// public void testMessageQueryWhenRouteHaveReceiverButNotPublisher() { -// try { -// Mockito.when(messageBus.getPublisher(any())).thenReturn(null); -// assertNull(messageBusUtil.messageQuery("publisher", "receiver", 100l, currentTimeMillis())); -// Mockito.verify(messageBus).getRoutes(); -// Mockito.verify(route).getReceivers(); -// Mockito.verify(messageBus).getPublisher(any()); -// Mockito.verify(messagePublisher, Mockito.never()).messageQuery(anyLong(), anyLong()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test MessageQuery when route have receiver -// * messageBus have publisher -// */ -// @Test -// public void testMessageQueryWhenRouteHaveReceiverAndPublisher() { -// try { -// Mockito.when(messagePublisher.messageQuery(anyLong(), anyLong())).thenReturn(messages); -// assertEquals(messages, messageBusUtil.messageQuery("publisher", "receiver", 100l, currentTimeMillis())); -// Mockito.verify(messageBus).getRoutes(); -// Mockito.verify(messageBus).getPublisher(any()); -// Mockito.verify(messagePublisher).messageQuery(anyLong(), anyLong()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.message_bus; + +import org.eclipse.iofog.microservice.Route; +import org.eclipse.iofog.status_reporter.StatusReporter; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import static java.lang.System.currentTimeMillis; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class MessageBusUtilTest { + private MessageBusUtil messageBusUtil; + private MessageBus messageBus; + private MessageBusStatus messageBusStatus; + private Message message; + private String MODULE_NAME; + private MessagePublisher messagePublisher; + private MessageReceiver messageReceiver; + private Route route; + private List messages; + private List receivers; + private Map routes; + private MockedStatic loggingServiceMockedStatic; + private MockedStatic statusReporterMockedStatic; + private MockedStatic messageBusMockedStatic; + + @BeforeEach + public void setUp() throws Exception { + MODULE_NAME = "Message Bus Util"; + messageBus = mock(MessageBus.class); + message = mock(Message.class); + messagePublisher = mock(MessagePublisher.class); + messageReceiver = mock(MessageReceiver.class); + route = mock(Route.class); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + messageBusMockedStatic = mockStatic(MessageBus.class); + statusReporterMockedStatic = mockStatic(StatusReporter.class); + messages = mock(ArrayList.class); + receivers = mock(ArrayList.class); + routes = mock(HashMap.class); + messageBusStatus = mock(MessageBusStatus.class); + Mockito.when(MessageBus.getInstance()).thenReturn(messageBus); + Mockito.when(messageBus.getReceiver(any())).thenReturn(messageReceiver); + Mockito.when(messageBus.getPublisher(any())).thenReturn(messagePublisher); + Mockito.when(messageBus.getRoutes()).thenReturn(routes); + Mockito.when(routes.get(any())).thenReturn(route); + Mockito.when(route.getReceivers()).thenReturn(receivers); + Mockito.when(messageReceiver.getMessages()).thenReturn(messages); + Mockito.when(StatusReporter.setMessageBusStatus()).thenReturn(messageBusStatus); + Mockito.when(receivers.contains(eq("receiver"))).thenReturn(true); + messageBusUtil = spy(new MessageBusUtil()); + } + + @AfterEach + public void tearDown() throws Exception { + statusReporterMockedStatic.close(); + loggingServiceMockedStatic.close(); + messageBusMockedStatic.close(); + MODULE_NAME = null; + Mockito.reset(messageBusUtil); + Mockito.reset(messageBusStatus); + Mockito.reset(message); + Mockito.reset(messageBus); + Mockito.reset(messagePublisher); + Mockito.reset(messageReceiver); + Mockito.reset(route); + } + + /** + * Test publishMessage when messageBus.getPublisher is null + */ + @Test + public void testPublishMessageWhenPublisherIsNull() { + try { + Mockito.when(messageBus.getPublisher(message.getPublisher())).thenReturn(null); + messageBusUtil.publishMessage(message); + Mockito.verify(messageBus).getPublisher(any()); + Mockito.verify(messagePublisher, Mockito.never()).publish(any(Message.class)); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Start publish message"); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Finishing publish message"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test publishMessage when messageBus.getPublisher is not null + */ + @Test + public void testPublishMessageWhenPublisherIsNotNull() { + try { + Mockito.when(messageBus.getPublisher(message.getPublisher())).thenReturn(messagePublisher); + messageBusUtil.publishMessage(message); + Mockito.verify(messageBus).getPublisher(any()); + Mockito.verify(messagePublisher).publish(any(Message.class)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test publishMessage + * publisher throws Exception + */ + @Test + public void throwsExceptionWhenPublisherIsCalled() { + Mockito.when(messageBus.getPublisher(message.getPublisher())).thenReturn(messagePublisher); + Mockito.when(messagePublisher.getName()).thenReturn("MP"); + try { + Mockito.doThrow(mock(Exception.class)).when(messagePublisher).publish(any()); + messageBusUtil.publishMessage(message); + Mockito.verify(messageBus).getPublisher(any()); + Mockito.verify(messagePublisher).publish(any(Message.class)); + Mockito.verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Unable to send message : Message Publisher (MP)"), any()); + } catch (Exception e) { + fail("This Should not happen"); + } + } + + /** + * Test getMessages MessageReceiver is null + */ + @Test + public void testGetMessagesWhenMessageReceiverIsNull() { + try { + Mockito.when(messageBus.getReceiver(any())).thenReturn(null); + assertEquals(0, messageBusUtil.getMessages("receiver").size()); + Mockito.verify(messageBus).getReceiver(any()); + Mockito.verify(messageReceiver, Mockito.never()).getMessages(); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Starting get message"); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Finishing get message"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getMessages MessageReceiver is not null + */ + @Test + public void testGetMessagesWhenMessageReceiverIsNotNull() { + try { + assertEquals(messages, messageBusUtil.getMessages("receiver")); + Mockito.verify(messageBus).getReceiver(any()); + Mockito.verify(messageReceiver).getMessages(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getMessages when MessagePublisher throws exception + */ + @Test + public void throwsExceptionWhenMessagePublisherIsCalledInGetMessages() { + try { + Mockito.doThrow(mock(Exception.class)).when(messageReceiver).getMessages(); + assertEquals(0, messageBusUtil.getMessages("receiver").size()); + Mockito.verify(messageBus).getReceiver(any()); + Mockito.verify(messageReceiver).getMessages(); + Mockito.verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("unable to receive messages : Message Receiver (receiver)"), any()); + } catch (Exception e) { + fail("This should not happen"); + } + + } + + /** + * Test MessageQuery when route is null + */ + @Test + public void testMessageQueryWhenRouteIsNull() { + try { + Mockito.when(routes.get(any())).thenReturn(null); + assertNull(messageBusUtil.messageQuery("publisher", "receiver", currentTimeMillis(), 100l)); + Mockito.verify(messageBus).getRoutes(); + Mockito.verify(messageBus, Mockito.never()).getPublisher(any()); + Mockito.verify(messagePublisher, Mockito.never()).messageQuery(anyLong(), anyLong()); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Starting message query"); + Mockito.verify(LoggingService.class, Mockito.never()); + LoggingService.logDebug(MODULE_NAME, "Finishing message query"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test MessageQuery when input parameter to is less than from + */ + @Test + public void testMessageQueryWhenInputParamToIsLessThanFrom() { + try { + assertNull(messageBusUtil.messageQuery("publisher", "receiver", currentTimeMillis(), 100l)); + Mockito.verify(messageBus).getRoutes(); + Mockito.verify(messageBus, Mockito.never()).getPublisher(any()); + Mockito.verify(messagePublisher, Mockito.never()).messageQuery(anyLong(), anyLong()); + Mockito.verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Starting message query"); + Mockito.verify(LoggingService.class, Mockito.never()); + LoggingService.logDebug(MODULE_NAME, "Finishing message query"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test MessageQuery when route doesn't have receiver + */ + @Test + public void testMessageQueryWhenRouteDoseNotHaveReceiver() { + try { + Mockito.when(receivers.contains(eq("receiver"))).thenReturn(false); + assertNull(messageBusUtil.messageQuery("publisher", "receiver", 100l, currentTimeMillis())); + Mockito.verify(messageBus).getRoutes(); + Mockito.verify(route).getReceivers(); + Mockito.verify(messageBus, Mockito.never()).getPublisher(any()); + Mockito.verify(messagePublisher, Mockito.never()).messageQuery(anyLong(), anyLong()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test MessageQuery when route have receiver + * messageBus doesn't have publisher + */ + @Test + public void testMessageQueryWhenRouteHaveReceiverButNotPublisher() { + try { + Mockito.when(messageBus.getPublisher(any())).thenReturn(null); + assertNull(messageBusUtil.messageQuery("publisher", "receiver", 100l, currentTimeMillis())); + Mockito.verify(messageBus).getRoutes(); + Mockito.verify(route).getReceivers(); + Mockito.verify(messageBus).getPublisher(any()); + Mockito.verify(messagePublisher, Mockito.never()).messageQuery(anyLong(), anyLong()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test MessageQuery when route have receiver + * messageBus have publisher + */ + @Test + public void testMessageQueryWhenRouteHaveReceiverAndPublisher() { + try { + Mockito.when(messagePublisher.messageQuery(anyLong(), anyLong())).thenReturn(messages); + assertEquals(messages, messageBusUtil.messageQuery("publisher", "receiver", 100l, currentTimeMillis())); + Mockito.verify(messageBus).getRoutes(); + Mockito.verify(messageBus).getPublisher(any()); + Mockito.verify(messagePublisher).messageQuery(anyLong(), anyLong()); + } 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/message_bus/MessageIdGeneratorTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageIdGeneratorTest.java index 058cbc7d..6f573a16 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,71 +1,68 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.junit.After; -//import org.junit.Before; -//import org.junit.Test; -//import org.junit.runner.RunWith; -//import org.powermock.api.mockito.Mockito; -//import org.powermock.core.classloader.annotations.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import static java.lang.System.currentTimeMillis; -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.*; -//import static org.mockito.Mockito.*; -//import static org.powermock.api.mockito.Mockito.spy; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessageIdGenerator.class}) -//public class MessageIdGeneratorTest { -// private MessageIdGenerator messageIdGenerator; -// -// @Before -// public void setUp() throws Exception { -// messageIdGenerator = spy(new MessageIdGenerator()); -// } -// -// @After -// public void tearDown() throws Exception { -// reset(messageIdGenerator); -// } -// -// /** -// * Test generate -// */ -// @Test -// public void testGenerate() { -// try { -// assertNotNull("Message Id not null", -// messageIdGenerator.generate(currentTimeMillis())); -// Mockito.verifyPrivate(messageIdGenerator, times(2)) -// .invoke("toBase58", anyLong()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getNextId -// */ -// @Test -// public void testGetNextId() { -// assertNotNull("Next Id", messageIdGenerator.getNextId()); -// assertFalse(messageIdGenerator.getNextId().contains("?")); -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.message_bus; + +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.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import static java.lang.System.currentTimeMillis; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class MessageIdGeneratorTest { + private MessageIdGenerator messageIdGenerator; + + @BeforeEach + public void setUp() throws Exception { + messageIdGenerator = spy(new MessageIdGenerator()); + } + + @AfterEach + public void tearDown() throws Exception { + reset(messageIdGenerator); + } + + /** + * Test generate + */ + @Test + public void testGenerate() { + try { + assertNotNull("Message Id not null", + messageIdGenerator.generate(currentTimeMillis())); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getNextId + */ + @Test + public void testGetNextId() { + assertNotNull("Next Id", messageIdGenerator.getNextId()); + assertFalse(messageIdGenerator.getNextId().contains("?")); + } +} \ No newline at end of file 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 a938dd6c..d1c22333 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,193 +1,211 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.eclipse.iofog.microservice.Route; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import jakarta.jms.MessageProducer; -//import jakarta.jms.Session; -//import jakarta.jms.TextMessage; -//import java.util.ArrayList; -//import java.util.List; -// -//import static org.eclipse.iofog.message_bus.MessageBus.MODULE_NAME; -//import static org.eclipse.iofog.utils.logging.LoggingService.logError; -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.*; -//import static org.mockito.Mockito.atLeastOnce; -//import static org.mockito.Mockito.reset; -//import static org.powermock.api.mockito.Mockito.*; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessagePublisher.class, Route.class, MessageProducer.class, Message.class, -// MessageArchive.class, LoggingService.class, MessageBusServer.class, Session.class, -// TextMessage.class}) -//public class MessagePublisherTest { -// private final List messageProducers = new ArrayList<>(); -// private MessagePublisher messagePublisher; -// private String name; -// private Route route; -// private Message message; -// private MessageArchive messageArchive; -// private MessageBusServer messageBusServer; -// private TextMessage textMessage; -// private byte[] bytes; -// private List receivers; -// private List messageList; -// -// @Before -// public void setUp() throws Exception { -// name = "name"; -// bytes = new byte[20]; -// route = mock(Route.class); -// message = mock(Message.class); -// textMessage = mock(TextMessage.class); -// messageArchive = mock(MessageArchive.class); -// messageBusServer = mock(MessageBusServer.class); -// receivers = new ArrayList<>(); -// receivers.add("receivers"); -// messageList = mock(ArrayList.class); -// mockStatic(LoggingService.class); -// mockStatic(MessageBusServer.class); -// Mockito.when(message.getBytes()).thenReturn(bytes); -// Mockito.when(message.getTimestamp()).thenReturn(System.currentTimeMillis()); -// Mockito.when(MessageBusServer.createMessage(anyString())).thenReturn(textMessage); -// Mockito.when(route.getReceivers()).thenReturn(receivers); -// Mockito.whenNew(MessageArchive.class).withArguments(anyString()).thenReturn(messageArchive); -// messagePublisher = spy(new MessagePublisher(name, route, messageProducers)); -// Mockito.doNothing().when(messageArchive).save(Mockito.any(byte[].class), anyLong()); -// Mockito.doNothing().when(messageArchive).close(); -// Mockito.when(messageArchive.messageQuery(anyLong(), anyLong())).thenReturn(messageList); -// } -// -// @After -// public void tearDown() throws Exception { -// reset(messagePublisher); -// reset(route); -// } -// -// /** -// * Test getName -// */ -// @Test -// public void TestGetName() { -// assertEquals(name, messagePublisher.getName()); -// } -// -// /** -// * Test Publish -// */ -// @Test -// public void testPublishWhenMessageIsArchived() { -// try { -// messagePublisher.publish(message); -// Mockito.verify(messageArchive, atLeastOnce()).save(any(byte[].class), anyLong()); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Start publish message :name"); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Finished publish message : name"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test Publish throws exception when messageArchive save is called -// */ -// @Test -// public void throwExceptionWhenArchiveMessageSaveIsCalled() { -// try { -// Mockito.doThrow(mock(Exception.class)).when(messageArchive).save(Mockito.any(byte[].class), anyLong()); -// messagePublisher.publish(message); -// Mockito.verify(messageArchive, atLeastOnce()).save(any(byte[].class), anyLong()); -// verifyStatic(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Message Publisher (name)unable to archive message"), -// any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test updateRoute -// */ -// @Test -// public void testUpdateRoute() { -// try { -// messagePublisher.updateRoute(route, messageProducers); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Updating route"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test close -// */ -// @Test -// public void testClose() { -// try { -// messagePublisher.close(); -// Mockito.verify(messageArchive, atLeastOnce()).close(); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Start closing publish"); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Finished closing publish"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test close throws Exception -// */ -// @Test -// public void throwsExceptionWhenCloseIsCalled() { -// try { -// Mockito.doThrow(mock(RuntimeException.class)).when(messageArchive).close(); -// messagePublisher.close(); -// Mockito.verify(messageArchive, atLeastOnce()).close(); -// verifyStatic(LoggingService.class); -// logError(eq(MODULE_NAME), eq("Error closing message archive"), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test messageQuery -// */ -// @Test -// public void messageQuery() { -// try { -// assertEquals(messageList, messagePublisher.messageQuery(System.currentTimeMillis()-1, System.currentTimeMillis())); -// Mockito.verify(messageArchive, atLeastOnce()).messageQuery(anyLong(), anyLong()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.message_bus; + +import org.eclipse.iofog.microservice.Route; +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import jakarta.jms.MessageProducer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import java.util.ArrayList; +import java.util.List; + +import static org.eclipse.iofog.message_bus.MessageBus.MODULE_NAME; +import static org.eclipse.iofog.utils.logging.LoggingService.logError; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class MessagePublisherTest { + private final List messageProducers = new ArrayList<>(); + private MessagePublisher messagePublisher; + 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; + private MockedConstruction messageArchiveMockedConstruction; + + + @BeforeEach + public void setUp() throws Exception { + name = "name"; + bytes = new byte[20]; + route = mock(Route.class); + message = mock(Message.class); + textMessage = mock(TextMessage.class); + receivers = new ArrayList<>(); + receivers.add("receivers"); + messageList = mock(ArrayList.class); + loggingServiceMockedStatic = mockStatic(LoggingService.class); + messageBusServerMockedStatic = mockStatic(MessageBusServer.class); + Mockito.when(message.getBytes()).thenReturn(bytes); + Mockito.when(message.getTimestamp()).thenReturn(System.currentTimeMillis()); + Mockito.when(MessageBusServer.createMessage(anyString())).thenReturn(textMessage); + Mockito.when(route.getReceivers()).thenReturn(receivers); + messageArchiveMockedConstruction = Mockito.mockConstruction(MessageArchive.class, (mock, context) -> { + Mockito.doNothing().when(mock).save(Mockito.any(byte[].class), anyLong()); + Mockito.doNothing().when(mock).close(); + Mockito.when(mock.messageQuery(anyLong(), anyLong())).thenReturn(messageList); + }); + messagePublisher = spy(new MessagePublisher(name, route, messageProducers)); + + } + + @AfterEach + public void tearDown() throws Exception { + loggingServiceMockedStatic.close(); + messageBusServerMockedStatic.close(); + messageArchiveMockedConstruction.close(); + reset(messagePublisher); + reset(route); + } + + /** + * Test getName + */ + @Test + public void TestGetName() { + assertEquals(name, messagePublisher.getName()); + } + + /** + * Test Publish + */ + @Test + public void testPublishWhenMessageIsArchived() { + try { + messagePublisher.publish(message); + MessageArchive mock = messageArchiveMockedConstruction.constructed().get(0); + Mockito.verify(mock, atLeastOnce()).save(any(byte[].class), anyLong()); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Start publish message :name"); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Finished publish message : name"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test Publish throws exception when messageArchive save is called + */ + @Test + public void throwExceptionWhenArchiveMessageSaveIsCalled() { + try { + messageArchiveMockedConstruction.close(); + messageArchiveMockedConstruction = Mockito.mockConstruction(MessageArchive.class, (mock, context) -> { + Mockito.doThrow(Exception.class).when(mock).save(Mockito.any(byte[].class), anyLong()); + }); + MessagePublisher messagePublisherSpy = spy(new MessagePublisher(name, route, messageProducers)); + messagePublisherSpy.publish(message); + MessageArchive mock = messageArchiveMockedConstruction.constructed().get(0); + Mockito.verify(mock, atLeastOnce()).save(any(byte[].class), anyLong()); + verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Message Publisher (name)unable to archive message"), + any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test updateRoute + */ + @Test + public void testUpdateRoute() { + try { + messagePublisher.updateRoute(route, messageProducers); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Updating route"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test close + */ + @Test + public void testClose() { + try { + messagePublisher.close(); + MessageArchive mock = messageArchiveMockedConstruction.constructed().get(0); + Mockito.verify(mock, atLeastOnce()).close(); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Start closing publish"); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Finished closing publish"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test close throws Exception + */ + @Test + public void throwsExceptionWhenCloseIsCalled() { + try { + messageArchiveMockedConstruction.close(); + messageArchiveMockedConstruction = Mockito.mockConstruction(MessageArchive.class, (mock, context) -> { + Mockito.doThrow(mock(RuntimeException.class)).when(mock).close(); + }); + MessagePublisher messagePublisherSpy = spy(new MessagePublisher(name, route, messageProducers)); + messagePublisherSpy.close(); + MessageArchive mock = messageArchiveMockedConstruction.constructed().get(0); + Mockito.verify(mock, atLeastOnce()).close(); + verify(LoggingService.class); + logError(eq(MODULE_NAME), eq("Error closing message archive"), any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test messageQuery + */ + @Test + public void messageQuery() { + try { + assertEquals(messageList, messagePublisher.messageQuery(System.currentTimeMillis()-1, System.currentTimeMillis())); + MessageArchive mock = messageArchiveMockedConstruction.constructed().get(0); + Mockito.verify(mock, atLeastOnce()).messageQuery(anyLong(), anyLong()); + } 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/message_bus/MessageReceiverTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageReceiverTest.java index 405c3aa8..14eb900a 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,284 +1,284 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//import org.eclipse.iofog.local_api.MessageCallback; -//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.PrepareForTest; -//import org.powermock.modules.junit4.PowerMockRunner; -// -//import jakarta.jms.JMSException; -//import jakarta.jms.MessageConsumer; -//import jakarta.jms.TextMessage; -// -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.*; -//import static org.mockito.Mockito.reset; -//import static org.mockito.Mockito.times; -//import static org.powermock.api.mockito.Mockito.*; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({MessageReceiver.class, MessageConsumer.class, IOMessageListener.class, TextMessage.class, -// LoggingService.class, Message.class, IOMessageListener.class}) -//public class MessageReceiverTest { -// private MessageReceiver messageReceiver; -// private MessageConsumer messageConsumer; -// private IOMessageListener ioMessageListener; -// private TextMessage textMessage; -// private Message message; -// private String name; -// private String MODULE_NAME; -// -// @Before -// public void setUp() throws Exception { -// name = "receiver"; -// MODULE_NAME = "MessageReceiver"; -// mockStatic(LoggingService.class); -// messageConsumer = mock(MessageConsumer.class); -// ioMessageListener = mock(IOMessageListener.class); -// textMessage = mock(TextMessage.class); -// message = mock(Message.class); -// Mockito.whenNew(IOMessageListener.class).withArguments(any(MessageCallback.class)).thenReturn(ioMessageListener); -// Mockito.whenNew(Message.class).withParameterTypes(byte[].class).withArguments(any()).thenReturn(message); -// Mockito.when(messageConsumer.receiveNoWait()).thenReturn(textMessage).thenReturn(null); -// Mockito.when(messageConsumer.getMessageListener()).thenReturn(ioMessageListener); -// Mockito.when(textMessage.getText()).thenReturn("{}"); -// messageReceiver = spy(new MessageReceiver(name, messageConsumer)); -// } -// -// @After -// public void tearDown() throws Exception { -// reset(messageConsumer, messageReceiver, ioMessageListener); -// MODULE_NAME = null; -// } -// -// /** -// * Test getMessages When clientConsumer receive immediate message as null -// */ -// @Test -// public void testGetMessagesWhenClientConsumerReceivesNull() { -// try { -// Mockito.when(messageConsumer.receiveNoWait()).thenReturn(null); -// assertEquals(0, messageReceiver.getMessages().size()); -// Mockito.verify(messageConsumer, times(1)).receiveNoWait(); -// Mockito.verify(textMessage, Mockito.never()).acknowledge(); -// Mockito.verify(messageConsumer, Mockito.never()).setMessageListener(any(IOMessageListener.class)); -// Mockito.verifyPrivate(messageReceiver, times(1)) -// .invoke("getMessage"); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, String.format("Finished getting message \"%s\"", name)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// /** -// * Test getMessages When Listener is null -// */ -// @Test -// public void testGetMessagesWhenListenerIsNull() { -// try { -// assertEquals(message, messageReceiver.getMessages().get(0)); -// Mockito.verify(messageConsumer, times(2)).receiveNoWait(); -// Mockito.verify(textMessage).acknowledge(); -// Mockito.verify(messageConsumer, Mockito.never()).setMessageListener(any(IOMessageListener.class)); -// Mockito.verifyPrivate(messageReceiver, times(2)) -// .invoke("getMessage"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// -// /** -// * Test getMessages When Listener is not null -// */ -// @Test -// public void testGetMessagesWhenListenerIsNotNull() { -// try { -// messageReceiver.enableRealTimeReceiving(); -// assertEquals(0, messageReceiver.getMessages().size()); -// Mockito.verify(messageConsumer, Mockito.never()).receiveNoWait(); -// Mockito.verify(textMessage, Mockito.never()).acknowledge(); -// Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); -// Mockito.verifyPrivate(messageReceiver).invoke("getMessage"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test getName -// */ -// @Test -// public void testGetName() { -// assertEquals(name, messageReceiver.getName()); -// } -// -// /** -// * Test enableRealTimeReceiving when Consumer is Null -// */ -// @Test -// public void testEnableRealTimeReceivingWhenConsumerIsNull() { -// try { -// messageReceiver = spy(new MessageReceiver(name, null)); -// messageReceiver.enableRealTimeReceiving(); -// Mockito.verify(messageConsumer, Mockito.never()).setMessageListener(any(IOMessageListener.class)); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Start enable real time receiving"); -// verifyStatic(LoggingService.class); -// LoggingService.logError(anyString(), anyString(), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test enableRealTimeReceiving when Consumer is not Null -// */ -// @Test -// public void testEnableRealTimeReceivingWhenConsumerIsNotNull() { -// try { -// messageReceiver.enableRealTimeReceiving(); -// Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test enableRealTimeReceiving clientConsumer throws ActiveMQException -// */ -// @Test -// public void throwsExceptionWhenSetHandlerIsCalledWhileEnableRealTimeReceiving() { -// try { -// Mockito.doThrow(mock(JMSException.class)).when(messageConsumer).setMessageListener(any()); -// messageReceiver.enableRealTimeReceiving(); -// Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); -// verifyStatic(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Error in enabling real time listener"), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test disableRealTimeReceiving clientConsumer throws ActiveMQException -// * Listener is not null -// */ -// @Test -// public void throwsActiveMqExceptionWhenSetHandlerIsCalledWhileDisablingRealTimeReceiving() { -// try { -// messageReceiver.enableRealTimeReceiving(); -// Mockito.doThrow(mock(JMSException.class)).when(messageConsumer).setMessageListener(any()); -// messageReceiver.disableRealTimeReceiving(); -// Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); -// verifyStatic(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Error in disabling real time listener"), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test disableRealTimeReceiving clientConsumer is null -// */ -// @Test -// public void testDisablingRealTimeReceivingWhenClientConsumerIsNull() { -// try { -// messageReceiver = spy(new MessageReceiver(name, null)); -// messageReceiver.disableRealTimeReceiving(); -// Mockito.verify(messageConsumer, Mockito.never()).setMessageListener(any(IOMessageListener.class)); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Start disable real time receiving"); -// verifyStatic(LoggingService.class, Mockito.never()); -// LoggingService.logDebug(MODULE_NAME, "Finished disable real time receiving"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test disableRealTimeReceiving clientConsumer is not null -// * Listener is not null -// */ -// @Test -// public void testDisableRealTimeReceiving() { -// try { -// messageReceiver.enableRealTimeReceiving(); -// messageReceiver.disableRealTimeReceiving(); -// Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test close MessageReceiver when clientConsumer is not null -// */ -// @Test -// public void testCloseReceiverWhenConsumerIsNotNull() { -// try { -// messageReceiver.close(); -// Mockito.verify(messageReceiver).disableRealTimeReceiving(); -// Mockito.verify(messageConsumer).close(); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Start closing receiver"); -// verifyStatic(LoggingService.class); -// LoggingService.logDebug(MODULE_NAME, "Finished closing receiver"); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test close MessageReceiver when clientConsumer is null -// */ -// @Test -// public void testCloseReceiverWhenConsumerIsNull() { -// try { -// messageReceiver = spy(new MessageReceiver(name, null)); -// messageReceiver.close(); -// Mockito.verify(messageReceiver, Mockito.never()).disableRealTimeReceiving(); -// Mockito.verify(messageConsumer, Mockito.never()).close(); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -// -// /** -// * Test close MessageReceiver when clientConsumer throws ActiveMQException -// */ -// @Test -// public void throwsExceptionWhenCloseIsCalled() { -// try { -// Mockito.doThrow(mock(JMSException.class)).when(messageConsumer).close(); -// messageReceiver.close(); -// Mockito.verify(messageReceiver).disableRealTimeReceiving(); -// Mockito.verify(messageConsumer).close(); -// verifyStatic(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Error in closing receiver"), any()); -// } catch (Exception e) { -// fail("This should not happen"); -// } -// } -//} \ No newline at end of file +/* + * ******************************************************************************* + * * Copyright (c) 2018-2022 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ +package org.eclipse.iofog.message_bus; + +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import jakarta.jms.JMSException; +import jakarta.jms.MessageConsumer; +import jakarta.jms.TextMessage; +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.fail; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class MessageReceiverTest { + private MessageReceiver messageReceiver; + private MessageConsumer messageConsumer; + private IOMessageListener ioMessageListener; + private TextMessage textMessage; + private String name; + private String MODULE_NAME; + private MockedStatic loggingServiceMockedStatic; + private MockedConstruction ioMessageListenerMockedConstruction; + private MockedConstruction messageMockedConstruction; + + + @BeforeEach + public void setUp() throws Exception { + name = "receiver"; + MODULE_NAME = "MessageReceiver"; + loggingServiceMockedStatic = mockStatic(LoggingService.class); + 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); + }); + messageMockedConstruction = Mockito.mockConstruction(Message.class); + Mockito.when(messageConsumer.receiveNoWait()).thenReturn(textMessage).thenReturn(null); + Mockito.when(textMessage.getText()).thenReturn("{}"); + messageReceiver = spy(new MessageReceiver(name, messageConsumer)); + } + + @AfterEach + public void tearDown() throws Exception { + reset(messageConsumer, messageReceiver, ioMessageListener); + MODULE_NAME = null; + loggingServiceMockedStatic.close(); + messageMockedConstruction.close(); + ioMessageListenerMockedConstruction.close(); + } + + /** + * Test getMessages When clientConsumer receive immediate message as null + */ + @Test + public void testGetMessagesWhenClientConsumerReceivesNull() { + try { + Mockito.when(messageConsumer.receiveNoWait()).thenReturn(null); + assertEquals(0, messageReceiver.getMessages().size()); + Mockito.verify(messageConsumer, times(1)).receiveNoWait(); + Mockito.verify(textMessage, Mockito.never()).acknowledge(); + Mockito.verify(messageConsumer, Mockito.never()).setMessageListener(any(IOMessageListener.class)); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, String.format("Finished getting message \"%s\"", name)); + } catch (Exception e) { + fail("This should not happen"); + } + } + /** + * Test getMessages When Listener is null + */ + @Test + public void testGetMessagesWhenListenerIsNull() { + try { + assertEquals(1, messageReceiver.getMessages().size()); + Mockito.verify(messageConsumer, times(2)).receiveNoWait(); + Mockito.verify(textMessage).acknowledge(); + Mockito.verify(messageConsumer, Mockito.never()).setMessageListener(any(IOMessageListener.class)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + + /** + * Test getMessages When Listener is not null + */ + @Test + public void testGetMessagesWhenListenerIsNotNull() { + try { + messageReceiver.enableRealTimeReceiving(); + assertEquals(0, messageReceiver.getMessages().size()); + Mockito.verify(messageConsumer, Mockito.never()).receiveNoWait(); + Mockito.verify(textMessage, Mockito.never()).acknowledge(); + Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test getName + */ + @Test + public void testGetName() { + assertEquals(name, messageReceiver.getName()); + } + + /** + * Test enableRealTimeReceiving when Consumer is Null + */ + @Test + public void testEnableRealTimeReceivingWhenConsumerIsNull() { + try { + messageReceiver = spy(new MessageReceiver(name, null)); + messageReceiver.enableRealTimeReceiving(); + Mockito.verify(messageConsumer, Mockito.never()).setMessageListener(any(IOMessageListener.class)); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Start enable real time receiving"); + verify(LoggingService.class); + LoggingService.logError(anyString(), anyString(), any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test enableRealTimeReceiving when Consumer is not Null + */ + @Test + public void testEnableRealTimeReceivingWhenConsumerIsNotNull() { + try { + messageReceiver.enableRealTimeReceiving(); + Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test enableRealTimeReceiving clientConsumer throws ActiveMQException + */ + @Test + public void throwsExceptionWhenSetHandlerIsCalledWhileEnableRealTimeReceiving() { + try { + Mockito.doThrow(mock(JMSException.class)).when(messageConsumer).setMessageListener(any()); + messageReceiver.enableRealTimeReceiving(); + Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); + verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Error in enabling real time listener"), any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test disableRealTimeReceiving clientConsumer throws ActiveMQException + * Listener is not null + */ + @Test + public void throwsActiveMqExceptionWhenSetHandlerIsCalledWhileDisablingRealTimeReceiving() { + try { + messageReceiver.enableRealTimeReceiving(); + Mockito.doThrow(mock(JMSException.class)).when(messageConsumer).setMessageListener(any()); + messageReceiver.disableRealTimeReceiving(); + Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); + verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Error in disabling real time listener"), any()); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test disableRealTimeReceiving clientConsumer is null + */ + @Test + public void testDisablingRealTimeReceivingWhenClientConsumerIsNull() { + try { + messageReceiver = spy(new MessageReceiver(name, null)); + messageReceiver.disableRealTimeReceiving(); + Mockito.verify(messageConsumer, Mockito.never()).setMessageListener(any(IOMessageListener.class)); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Start disable real time receiving"); + verify(LoggingService.class, Mockito.never()); + LoggingService.logDebug(MODULE_NAME, "Finished disable real time receiving"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test disableRealTimeReceiving clientConsumer is not null + * Listener is not null + */ + @Test + public void testDisableRealTimeReceiving() { + try { + messageReceiver.enableRealTimeReceiving(); + messageReceiver.disableRealTimeReceiving(); + Mockito.verify(messageConsumer).setMessageListener(any(IOMessageListener.class)); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test close MessageReceiver when clientConsumer is not null + */ + @Test + public void testCloseReceiverWhenConsumerIsNotNull() { + try { + messageReceiver.close(); + Mockito.verify(messageReceiver).disableRealTimeReceiving(); + Mockito.verify(messageConsumer).close(); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Start closing receiver"); + verify(LoggingService.class); + LoggingService.logDebug(MODULE_NAME, "Finished closing receiver"); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test close MessageReceiver when clientConsumer is null + */ + @Test + public void testCloseReceiverWhenConsumerIsNull() { + try { + messageReceiver = spy(new MessageReceiver(name, null)); + messageReceiver.close(); + Mockito.verify(messageReceiver, Mockito.never()).disableRealTimeReceiving(); + Mockito.verify(messageConsumer, Mockito.never()).close(); + } catch (Exception e) { + fail("This should not happen"); + } + } + + /** + * Test close MessageReceiver when clientConsumer throws ActiveMQException + */ + @Test + public void throwsExceptionWhenCloseIsCalled() { + try { + Mockito.doThrow(mock(JMSException.class)).when(messageConsumer).close(); + messageReceiver.close(); + Mockito.verify(messageReceiver).disableRealTimeReceiving(); + Mockito.verify(messageConsumer).close(); + verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Error in closing receiver"), 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/message_bus/MessageTest.java b/iofog-agent-daemon/src/test/java/org/eclipse/iofog/message_bus/MessageTest.java index 404dab27..7c5dee77 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,484 +1,497 @@ -///* -// * ******************************************************************************* -// * * 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.message_bus; -// -//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.powermock.api.mockito.Mockito; -//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 java.io.ByteArrayOutputStream; -//import java.io.IOException; -//import java.util.Base64; -// -//import static java.lang.System.currentTimeMillis; -//import static java.nio.charset.StandardCharsets.UTF_8; -//import static org.junit.Assert.*; -//import static org.mockito.ArgumentMatchers.any; -//import static org.mockito.ArgumentMatchers.eq; -//import static org.powermock.api.mockito.Mockito.*; -// -///** -// * @author nehanaithani -// * -// */ -//@RunWith(PowerMockRunner.class) -//@PrepareForTest({Message.class, Base64.class, LoggingService.class, ByteArrayOutputStream.class}) -//public class MessageTest { -// private short VERSION; -// private String MODULE_NAME; -// private Message message; -// private String id; -// private String tag; -// private String messageGroupId; -// private int sequenceNumber; -// private int sequenceTotal; -// private byte priority; -// private long timestamp; -// private String publisher; -// private String authIdentifier; -// private String authGroup; -// private short version; -// private long chainPosition; -// private String hash; -// private String previousHash; -// private String nonce; -// private int difficultyTarget; -// private String infoType; -// private String infoFormat; -// private byte[] contextData; -// private byte[] contentData; -// private JsonObject jsonObject; -// private JsonObjectBuilder jsonObjectBuilder = null; -// -// -// @Before -// public void setUp() throws Exception { -// mockStatic(LoggingService.class); -// MODULE_NAME = "Message"; -// VERSION = 4; -// byte[] byteArray = new byte[] { (byte)0xe0, (byte)0xf4 }; -// version = 0; -// id = "id"; -// tag = "tag"; -// messageGroupId = "messageGroupId"; -// sequenceNumber = 1; -// sequenceTotal = 10; -// priority = 1; -// timestamp = currentTimeMillis(); -// publisher = "publisher"; -// authIdentifier = "authIdentifier"; -// authGroup = "authGroup"; -// chainPosition = 5; -// hash = "hash"; -// previousHash = "previousHash"; -// nonce = "nonce"; -// difficultyTarget = 2; -// infoType = "infoType"; -// infoFormat = "infoFormat"; -// message = spy(new Message()); -// String content = "contentData"; -// String context = "contextData"; +/* + * ******************************************************************************* + * * 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.message_bus; + +import org.eclipse.iofog.utils.logging.LoggingService; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Base64; + +import static java.lang.System.currentTimeMillis; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + +/** + * @author nehanaithani + * + */ +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +public class MessageTest { + private short VERSION; + private String MODULE_NAME; + private Message message; + private String id; + private String tag; + private String messageGroupId; + private int sequenceNumber; + private int sequenceTotal; + private byte priority; + private long timestamp; + private String publisher; + private String authIdentifier; + private String authGroup; + private short version; + private long chainPosition; + private String hash; + private String previousHash; + private String nonce; + private int difficultyTarget; + private String infoType; + private String infoFormat; + private byte[] contextData; + private byte[] contentData; + private JsonObject jsonObject; + private JsonObjectBuilder jsonObjectBuilder; + private MockedStatic loggingServiceMockedStatic; + + + @BeforeEach + public void setUp() throws Exception { + loggingServiceMockedStatic = mockStatic(LoggingService.class); + MODULE_NAME = "Message"; + VERSION = 4; + byte[] byteArray = new byte[] { (byte)0xe0, (byte)0xf4 }; + version = 0; + id = "id"; + tag = "tag"; + messageGroupId = "messageGroupId"; + sequenceNumber = 1; + sequenceTotal = 10; + priority = 1; + timestamp = currentTimeMillis(); + publisher = "publisher"; + authIdentifier = "authIdentifier"; + authGroup = "authGroup"; + chainPosition = 5; + hash = "hash"; + previousHash = "previousHash"; + nonce = "nonce"; + 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(); -// jsonObject = jsonObjectBuilder.add("id", id) -// .add("tag",tag ) -// .add("groupid", messageGroupId) -// .add("sequencenumber", sequenceNumber) -// .add("sequencetotal", sequenceTotal) -// .add("priority", priority) -// .add("timestamp", timestamp) -// .add("publisher", publisher) -// .add("authid", authIdentifier) -// .add("authgroup", authGroup) -// .add("chainposition", chainPosition) -// .add("hash", hash) -// .add("previoushash", previousHash) -// .add("nonce", nonce) -// .add("difficultytarget", difficultyTarget) -// .add("infotype", infoType) -// .add("infoformat", infoFormat) + jsonObjectBuilder = Json.createObjectBuilder(); + jsonObject = jsonObjectBuilder.add("id", id) + .add("tag",tag ) + .add("groupid", messageGroupId) + .add("sequencenumber", sequenceNumber) + .add("sequencetotal", sequenceTotal) + .add("priority", priority) + .add("timestamp", timestamp) + .add("publisher", publisher) + .add("authid", authIdentifier) + .add("authgroup", authGroup) + .add("chainposition", chainPosition) + .add("hash", hash) + .add("previoushash", previousHash) + .add("nonce", nonce) + .add("difficultytarget", difficultyTarget) + .add("infotype", infoType) + .add("infoformat", infoFormat) // .add("contentdata", content) -// .add("contextdata", context).build(); -// -// } -// -// @After -// public void tearDown() throws Exception { -// MODULE_NAME = null; -// VERSION = 0; -// id = null; -// tag = null; -// messageGroupId = null; -// sequenceNumber = 0; -// sequenceTotal = 0; -// priority = 0; -// timestamp = 0; -// publisher = null; -// authIdentifier = null; -// authGroup = null; -// chainPosition = 0; -// hash = null; -// previousHash = null; -// nonce = null; -// difficultyTarget = 0; -// infoType = null; -// infoFormat = null; -// contentData = null; -// contextData = null; -// } -// -// /** -// * Test Message constructor with Json parameter -// */ -// @Test -// public void constructorWithJsonArgument() { -// message = spy(new Message(jsonObject)); -// assertEquals(id, message.getId()); -// assertEquals(tag, message.getTag()); -// assertEquals(messageGroupId, message.getMessageGroupId()); -// assertEquals(sequenceNumber, message.getSequenceNumber()); -// assertEquals(sequenceTotal, message.getSequenceTotal()); -// assertEquals(priority, message.getPriority()); -// assertEquals(timestamp, message.getTimestamp()); -// assertEquals(publisher, message.getPublisher()); -// assertEquals(authIdentifier, message.getAuthIdentifier()); -// assertEquals(authGroup, message.getAuthGroup()); -// assertEquals(chainPosition, message.getChainPosition()); -// assertEquals(hash, message.getHash()); -// assertEquals(previousHash, message.getPreviousHash()); -// assertEquals(nonce, message.getNonce()); -// assertEquals(difficultyTarget, message.getDifficultyTarget()); -// assertEquals(infoType, message.getInfoType()); -// assertEquals(infoFormat, message.getInfoFormat()); -// } -// -// /** -// * Test getter And Setter of Id -// */ -// @Test -// public void testGetterAndSetterId() { -// message.setId(id); -// assertEquals(id, message.getId()); -// } -// -// /** -// * Test getter And Setter of tag -// */ -// @Test -// public void testGetterAndSetterTag() { -// message.setTag(tag); -// assertEquals(tag, message.getTag()); -// } -// -// /** -// * Test getter And Setter of MessageGroupId -// */ -// @Test -// public void testGetterAndSetterMessageGroupId() { -// message.setMessageGroupId(messageGroupId); -// assertEquals(messageGroupId, message.getMessageGroupId()); -// } -// -// /** -// * Test getter and setter of sequenceNumber -// */ -// @Test -// public void testGetterAndSetterSequenceNumber() { -// message.setSequenceNumber(sequenceNumber); -// assertEquals(sequenceNumber, message.getSequenceNumber()); -// } -// -// /** -// * Test getter and setter of sequenceTotal -// */ -// @Test -// public void testGetterAndSetterSequenceTotal() { -// message.setSequenceTotal(sequenceTotal); -// assertEquals(sequenceTotal, message.getSequenceTotal()); -// } -// -// /** -// * Test getter and setter of priority -// */ -// @Test -// public void testGetterAndSetterPriority() { -// message.setPriority(priority); -// assertEquals(priority, message.getPriority()); -// } -// -// /** -// * Test getter and setter of timeStamp -// */ -// @Test -// public void testGetterAndSetterTimestamp() { -// message.setTimestamp(timestamp); -// assertEquals(timestamp, message.getTimestamp()); -// } -// -// /** -// * Test getter and setter of Publisher -// */ -// @Test -// public void testGetterAndSetterPublisher() { -// message.setPublisher(publisher); -// assertEquals(publisher, message.getPublisher()); -// } -// -// /** -// * Test getter and setter of authIdentifier -// */ -// @Test -// public void testGetterAndSetterAuthIdentifier() { -// message.setAuthIdentifier(authIdentifier); -// assertEquals(authIdentifier, message.getAuthIdentifier()); -// } -// -// /** -// * Test getter and setter of AuthGroup -// */ -// @Test -// public void testGetterAndSetterAuthGroup() { -// message.setAuthGroup(authGroup); -// assertEquals(authGroup, message.getAuthGroup()); -// } -// -// /** -// * Test getter and setter of version -// */ -// @Test -// public void testGetterAndSetterVersion() { -// assertEquals(VERSION, message.getVersion()); -// } -// -// /** -// * Test getter and setter of chainPosition -// */ -// @Test -// public void testGetterAndSetterChainPosition() { -// message.setChainPosition(chainPosition); -// assertEquals(chainPosition, message.getChainPosition()); -// } -// -// /** -// * Test getter and setter of hash -// */ -// @Test -// public void testGetterAndSetterHash() { -// message.setHash(hash); -// assertEquals(hash, message.getHash()); -// } -// -// /** -// * Test getter and setter of previous hash -// */ -// @Test -// public void testGetterAndSetterPreviousHash() { -// message.setPreviousHash(previousHash); -// assertEquals(previousHash, message.getPreviousHash()); -// } -// -// /** -// * Test getter and setter of nonce -// */ -// @Test -// public void testGetterAndSetterNonce() { -// message.setNonce(nonce); -// assertEquals(nonce, message.getNonce()); -// } -// -// /** -// * Test getter and setter of difficultyTarget -// */ -// @Test -// public void testGetterAndSetterDifficultyTarget() { -// message.setDifficultyTarget(difficultyTarget); -// assertEquals(difficultyTarget, message.getDifficultyTarget()); -// } -// -// /** -// * Test getter and setter of infoType -// */ -// @Test -// public void testGetterAndSetterInfoType() { -// message.setInfoType(infoType); -// assertEquals(infoType, message.getInfoType()); -// } -// -// /** -// * Test getter and setter of InfoFormat -// */ -// @Test -// public void testGetterAndSetterInfoFormat() { -// message.setInfoFormat(infoFormat); -// assertEquals(infoFormat, message.getInfoFormat()); -// } -// -// /** -// * Test getter and setter of ContextData -// */ -// @Test -// public void testGetterAndSetterContextData() { -// message.setContextData(contextData); -// assertEquals(contextData, message.getContextData()); -// } -// -// /** -// * Test getter and setter of ContentData -// */ -// @Test -// public void testGetterAndSetterContentData() { -// message.setContentData(contentData); -// assertEquals(contentData, message.getContentData()); -// } -// -// /** -// * Test getter and setter of bytes -// */ -// @Test -// public void testBytes() { -// message = spy(new Message(jsonObject)); -// byte[] rawByte = message.getBytes(); -// message = spy(new Message(rawByte)); -// assertEquals(id, message.getId()); -// assertEquals(tag, message.getTag()); -// assertEquals(messageGroupId, message.getMessageGroupId()); -// assertEquals(sequenceNumber, message.getSequenceNumber()); -// assertEquals(sequenceTotal, message.getSequenceTotal()); -// assertEquals(priority, message.getPriority()); -// assertEquals(timestamp, message.getTimestamp()); -// assertEquals(publisher, message.getPublisher()); -// assertEquals(authIdentifier, message.getAuthIdentifier()); -// assertEquals(authGroup, message.getAuthGroup()); -// assertEquals(chainPosition, message.getChainPosition()); -// assertEquals(hash, message.getHash()); -// assertEquals(previousHash, message.getPreviousHash()); -// assertEquals(nonce, message.getNonce()); -// assertEquals(difficultyTarget, message.getDifficultyTarget()); -// assertEquals(infoType, message.getInfoType()); -// assertEquals(infoFormat, message.getInfoFormat()); -// -// } -// -// /** -// * Test throws exception when ByteArrayOutputStream object is created -// */ -// @Test -// public void throwsExceptionWhenByteArrayOutputStreamIsCreatedInBytes() { -// try { -// whenNew(ByteArrayOutputStream.class).withNoArguments().thenThrow(mock(IOException.class) ); -// message = spy(new Message(jsonObject)); -// byte[] rawByte = message.getBytes(); -// assertTrue(rawByte.length == 0); -// verifyStatic(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Error in getBytes"), any()); -// } catch (Exception e) { -// fail("This should never happen"); -// } -// } -// -// /** -// * Test toJson when Message constructor is without argument -// */ -// @Test -// public void testJsonWithMessageConstructorWithNoArguments() { -// assertTrue(message.toJson().containsKey("version")); -// assertTrue(message.toJson().containsKey("publisher")); -// assertTrue(message.toJson().containsKey("groupid")); -// assertEquals("", message.toJson().getString("groupid")); -// assertEquals(VERSION, message.toJson().getInt("version")); -// assertEquals("", message.toJson().getString("publisher")); -// assertEquals("", message.toJson().getString("infotype")); -// } -// -// /** -// * Test toJson when Message constructor is without argument JsonObject -// */ -// @Test -// public void testJsonWithMessageConstructorWithJsonArgument() { -// message = spy(new Message(jsonObject)); -// assertTrue(message.toJson().containsKey("version")); -// assertTrue(message.toJson().containsKey("publisher")); -// assertTrue(message.toJson().containsKey("groupid")); -// assertEquals(messageGroupId, message.toJson().getString("groupid")); -// assertEquals(version, message.toJson().getInt("version")); -// assertEquals(publisher, message.toJson().getString("publisher")); -// assertEquals(infoFormat, message.toJson().getString("infoformat")); -// assertEquals(previousHash, message.toJson().getString("previoushash")); -// assertEquals(hash, message.toJson().getString("hash")); -// } -// -// /** -// * Test toString -// */ -// @Test -// public void testToString() { -// assertFalse(message.toString().contains("@")); -// message = spy(new Message(jsonObject)); -// assertFalse(message.toString().contains("@")); -// } -// -// /** -// * Test decodeBase64 -// */ -// @Test -// public void testDecodeBase64() { -// message.decodeBase64(message.encodeBase64()); -// assertNotEquals(hash, message.getHash()); -// } -// -// /** -// * Test decodeBase64 throws Exception -// */ -// @Test -// public void throwsExceptionWhenDecodeBase64() { -// mockStatic(Base64.class); -// Base64.Decoder decoder = mock(Base64.Decoder.class); -// when(Base64.getDecoder()).thenReturn(decoder); -// Mockito.doThrow(new RuntimeException()).when(decoder).decode( any(byte[].class)); -// message.decodeBase64(message.encodeBase64()); -// verifyStatic(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Error in decodeBase64"), any()); -// } -// -// /** -// * Test encodeBase64 -// */ -// @Test -// public void testEncodeBase64() { -// assertNotNull(message.encodeBase64()); -// } -// -// /** -// * Test encodeBase64 throws Exception -// */ -// @Test -// public void throwsExceptionWhenEncodeBase64() { -// mockStatic(Base64.class); -// Base64.Encoder encoder = mock(Base64.Encoder.class); -// when(Base64.getEncoder()).thenReturn(encoder); -// Mockito.doThrow(new RuntimeException()).when(encoder).encode( any(byte[].class)); -// message.encodeBase64(); -// verifyStatic(LoggingService.class); -// LoggingService.logError(eq(MODULE_NAME), eq("Error in encodeBase64"), any()); -// } -//} \ No newline at end of file +// .add("contextdata", context) + .build(); + message = spy(new Message()); + } + + @AfterEach + public void tearDown() throws Exception { + MODULE_NAME = null; + VERSION = 0; + id = null; + tag = null; + messageGroupId = null; + sequenceNumber = 0; + sequenceTotal = 0; + priority = 0; + timestamp = 0; + publisher = null; + authIdentifier = null; + authGroup = null; + chainPosition = 0; + hash = null; + previousHash = null; + nonce = null; + difficultyTarget = 0; + infoType = null; + infoFormat = null; + contentData = null; + contextData = null; + loggingServiceMockedStatic.close(); + message = null; + } + + /** + * Test Message constructor with Json parameter + */ + @Test + public void constructorWithJsonArgument() { + message = spy(new Message(jsonObject)); + assertEquals(id, message.getId()); + assertEquals(tag, message.getTag()); + assertEquals(messageGroupId, message.getMessageGroupId()); + assertEquals(sequenceNumber, message.getSequenceNumber()); + assertEquals(sequenceTotal, message.getSequenceTotal()); + assertEquals(priority, message.getPriority()); + assertEquals(timestamp, message.getTimestamp()); + assertEquals(publisher, message.getPublisher()); + assertEquals(authIdentifier, message.getAuthIdentifier()); + assertEquals(authGroup, message.getAuthGroup()); + assertEquals(chainPosition, message.getChainPosition()); + assertEquals(hash, message.getHash()); + assertEquals(previousHash, message.getPreviousHash()); + assertEquals(nonce, message.getNonce()); + assertEquals(difficultyTarget, message.getDifficultyTarget()); + assertEquals(infoType, message.getInfoType()); + assertEquals(infoFormat, message.getInfoFormat()); + } + + /** + * Test getter And Setter of Id + */ + @Test + public void testGetterAndSetterId() { + message.setId(id); + assertEquals(id, message.getId()); + } + + /** + * Test getter And Setter of tag + */ + @Test + public void testGetterAndSetterTag() { + message.setTag(tag); + assertEquals(tag, message.getTag()); + } + + /** + * Test getter And Setter of MessageGroupId + */ + @Test + public void testGetterAndSetterMessageGroupId() { + message.setMessageGroupId(messageGroupId); + assertEquals(messageGroupId, message.getMessageGroupId()); + } + + /** + * Test getter and setter of sequenceNumber + */ + @Test + public void testGetterAndSetterSequenceNumber() { + message.setSequenceNumber(sequenceNumber); + assertEquals(sequenceNumber, message.getSequenceNumber()); + } + + /** + * Test getter and setter of sequenceTotal + */ + @Test + public void testGetterAndSetterSequenceTotal() { + message.setSequenceTotal(sequenceTotal); + assertEquals(sequenceTotal, message.getSequenceTotal()); + } + + /** + * Test getter and setter of priority + */ + @Test + public void testGetterAndSetterPriority() { + message.setPriority(priority); + assertEquals(priority, message.getPriority()); + } + + /** + * Test getter and setter of timeStamp + */ + @Test + public void testGetterAndSetterTimestamp() { +// message = new Message(jsonObject); +// timestamp = currentTimeMillis(); + message.setTimestamp(timestamp); + assertEquals(timestamp, message.getTimestamp()); + } + + /** + * Test getter and setter of Publisher + */ + @Test + public void testGetterAndSetterPublisher() { + message.setPublisher(publisher); + assertEquals(publisher, message.getPublisher()); + } + + /** + * Test getter and setter of authIdentifier + */ + @Test + public void testGetterAndSetterAuthIdentifier() { + message.setAuthIdentifier(authIdentifier); + assertEquals(authIdentifier, message.getAuthIdentifier()); + } + + /** + * Test getter and setter of AuthGroup + */ + @Test + public void testGetterAndSetterAuthGroup() { + message.setAuthGroup(authGroup); + assertEquals(authGroup, message.getAuthGroup()); + } + + /** + * Test getter and setter of version + */ + @Test + public void testGetterAndSetterVersion() { + assertEquals(VERSION, message.getVersion()); + } + + /** + * Test getter and setter of chainPosition + */ + @Test + public void testGetterAndSetterChainPosition() { + message.setChainPosition(chainPosition); + assertEquals(chainPosition, message.getChainPosition()); + } + + /** + * Test getter and setter of hash + */ + @Test + public void testGetterAndSetterHash() { + message.setHash(hash); + assertEquals(hash, message.getHash()); + } + + /** + * Test getter and setter of previous hash + */ + @Test + public void testGetterAndSetterPreviousHash() { + message.setPreviousHash(previousHash); + assertEquals(previousHash, message.getPreviousHash()); + } + + /** + * Test getter and setter of nonce + */ + @Test + public void testGetterAndSetterNonce() { + message.setNonce(nonce); + assertEquals(nonce, message.getNonce()); + } + + /** + * Test getter and setter of difficultyTarget + */ + @Test + public void testGetterAndSetterDifficultyTarget() { + message.setDifficultyTarget(difficultyTarget); + assertEquals(difficultyTarget, message.getDifficultyTarget()); + } + + /** + * Test getter and setter of infoType + */ + @Test + public void testGetterAndSetterInfoType() { + message.setInfoType(infoType); + assertEquals(infoType, message.getInfoType()); + } + + /** + * Test getter and setter of InfoFormat + */ + @Test + public void testGetterAndSetterInfoFormat() { + message.setInfoFormat(infoFormat); + assertEquals(infoFormat, message.getInfoFormat()); + } + + /** + * Test getter and setter of ContextData + */ + @Test + public void testGetterAndSetterContextData() { + message.setContextData(contextData); + assertEquals(contextData, message.getContextData()); + } + + /** + * Test getter and setter of ContentData + */ + @Test + public void testGetterAndSetterContentData() { + message.setContentData(contentData); + assertEquals(contentData, message.getContentData()); + } + + /** + * Test getter and setter of bytes + */ + @Test + public void testBytes() { + message = spy(new Message(jsonObject)); + byte[] rawByte = message.getBytes(); + message = spy(new Message(rawByte)); + assertEquals(id, message.getId()); + assertEquals(tag, message.getTag()); + assertEquals(messageGroupId, message.getMessageGroupId()); + assertEquals(sequenceNumber, message.getSequenceNumber()); + assertEquals(sequenceTotal, message.getSequenceTotal()); + assertEquals(priority, message.getPriority()); + assertEquals(timestamp, message.getTimestamp()); + assertEquals(publisher, message.getPublisher()); + assertEquals(authIdentifier, message.getAuthIdentifier()); + assertEquals(authGroup, message.getAuthGroup()); + assertEquals(chainPosition, message.getChainPosition()); + assertEquals(hash, message.getHash()); + assertEquals(previousHash, message.getPreviousHash()); + assertEquals(nonce, message.getNonce()); + assertEquals(difficultyTarget, message.getDifficultyTarget()); + assertEquals(infoType, message.getInfoType()); + assertEquals(infoFormat, message.getInfoFormat()); + + } + + /** + * Test throws exception when ByteArrayOutputStream object is created + */ + @Test + public void throwsExceptionWhenByteArrayOutputStreamIsCreatedInBytes() { + try { + MockedConstruction byteArrayOutputStreamMockedConstruction = Mockito.mockConstructionWithAnswer(ByteArrayOutputStream.class, invocation -> { + throw new IOException(); + }); + message = spy(new Message(jsonObject)); + byte[] rawByte = message.getBytes(); + assertEquals(0, rawByte.length); + verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Error in getBytes"), any()); + byteArrayOutputStreamMockedConstruction.close(); + } catch (Exception e) { + fail("This should never happen"); + } + } + + /** + * Test toJson when Message constructor is without argument + */ + @Test + public void testJsonWithMessageConstructorWithNoArguments() { + assertTrue(message.toJson().containsKey("version")); + assertTrue(message.toJson().containsKey("publisher")); + assertTrue(message.toJson().containsKey("groupid")); + assertEquals("", message.toJson().getString("groupid")); + assertEquals(VERSION, message.toJson().getInt("version")); + assertEquals("", message.toJson().getString("publisher")); + assertEquals("", message.toJson().getString("infotype")); + } + + /** + * Test toJson when Message constructor is without argument JsonObject + */ + @Test + public void testJsonWithMessageConstructorWithJsonArgument() { + message = spy(new Message(jsonObject)); + assertTrue(message.toJson().containsKey("version")); + assertTrue(message.toJson().containsKey("publisher")); + assertTrue(message.toJson().containsKey("groupid")); + assertEquals(messageGroupId, message.toJson().getString("groupid")); + assertEquals(version, message.toJson().getInt("version")); + assertEquals(publisher, message.toJson().getString("publisher")); + assertEquals(infoFormat, message.toJson().getString("infoformat")); + assertEquals(previousHash, message.toJson().getString("previoushash")); + assertEquals(hash, message.toJson().getString("hash")); + } + + /** + * Test toString + */ + @Test + public void testToString() { + assertFalse(message.toString().contains("@")); + message = spy(new Message(jsonObject)); + assertFalse(message.toString().contains("@")); + } + + /** + * Test decodeBase64 + */ + @Test + public void testDecodeBase64() { + message.decodeBase64(message.encodeBase64()); + assertNotEquals(hash, message.getHash()); + } + + /** + * Test decodeBase64 throws Exception + */ + @Test + public void throwsExceptionWhenDecodeBase64() { + MockedStatic base64 = mockStatic(Base64.class); + Base64.Decoder decoder = mock(Base64.Decoder.class); + when(Base64.getDecoder()).thenReturn(decoder); + Mockito.doThrow(new RuntimeException()).when(decoder).decode( any(byte[].class)); + message.decodeBase64(message.encodeBase64()); + verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Error in decodeBase64"), any()); + base64.close(); + } + + /** + * Test encodeBase64 + */ + @Test + public void testEncodeBase64() { + assertNotNull(message.encodeBase64()); + } + + /** + * Test encodeBase64 throws Exception + */ + @Test + public void throwsExceptionWhenEncodeBase64() { + MockedStatic base64 = mockStatic(Base64.class); + Base64.Encoder encoder = mock(Base64.Encoder.class); + when(Base64.getEncoder()).thenReturn(encoder); + Mockito.doThrow(new RuntimeException()).when(encoder).encode( any(byte[].class)); + message.encodeBase64(); + verify(LoggingService.class); + LoggingService.logError(eq(MODULE_NAME), eq("Error in encodeBase64"), any()); + base64.close(); + } +} \ No newline at end of file