diff --git a/client/client-multi/client-java-core/src/test/java/org/kaaproject/kaa/client/KaaClientTest.java b/client/client-multi/client-java-core/src/test/java/org/kaaproject/kaa/client/KaaClientTest.java index cdda9559dc..2e47e69f9f 100644 --- a/client/client-multi/client-java-core/src/test/java/org/kaaproject/kaa/client/KaaClientTest.java +++ b/client/client-multi/client-java-core/src/test/java/org/kaaproject/kaa/client/KaaClientTest.java @@ -29,22 +29,31 @@ import org.junit.Test; import org.kaaproject.kaa.client.bootstrap.DefaultBootstrapManager; import org.kaaproject.kaa.client.channel.GenericTransportInfo; +import org.kaaproject.kaa.client.channel.KaaInternalChannelManager; import org.kaaproject.kaa.client.channel.ServerType; import org.kaaproject.kaa.client.channel.TransportConnectionInfo; import org.kaaproject.kaa.client.channel.TransportProtocolId; +import org.kaaproject.kaa.client.channel.impl.ChannelRuntimeException; import org.kaaproject.kaa.client.context.ExecutorContext; import org.kaaproject.kaa.client.context.SimpleExecutorContext; import org.kaaproject.kaa.client.context.TransportContext; import org.kaaproject.kaa.client.exceptions.KaaException; +import org.kaaproject.kaa.client.exceptions.KaaInvalidConfigurationException; +import org.kaaproject.kaa.client.exceptions.KaaRuntimeException; +import org.kaaproject.kaa.client.exceptions.KaaUnsupportedPlatformException; +import org.kaaproject.kaa.client.logging.AbstractLogCollector; import org.kaaproject.kaa.client.persistence.KaaClientPropertiesState; import org.kaaproject.kaa.client.persistence.KaaClientState; import org.kaaproject.kaa.client.persistence.PersistentStorage; +import org.kaaproject.kaa.client.profile.ProfileRuntimeException; +import org.kaaproject.kaa.client.schema.SchemaRuntimeException; import org.kaaproject.kaa.client.transport.TransportException; import org.kaaproject.kaa.client.util.CommonsBase64; import org.kaaproject.kaa.common.endpoint.gen.ProtocolMetaData; import org.kaaproject.kaa.common.endpoint.gen.ProtocolVersionPair; import org.kaaproject.kaa.common.endpoint.security.KeyUtil; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; public class KaaClientTest { @@ -77,7 +86,7 @@ public void beforeTest() throws Exception { client = new AbstractKaaClient(platformContext, stateListener) { @Override protected DefaultBootstrapManager buildBootstrapManager(KaaClientProperties properties, KaaClientState kaaClientState, - TransportContext transportContext) { + TransportContext transportContext) { return bsManagerMock; } }; @@ -137,4 +146,53 @@ protected Map> buildDummyConn return connectionInfo; } + @Test + public void failureOnStartTest() throws TransportException { + Mockito.doThrow(new KaaRuntimeException(new Exception("cause"))).when(bsManagerMock).receiveOperationsServerList(); + client.start(); + Mockito.verify(stateListener, Mockito.timeout(1000)).onStartFailure(Mockito.any(KaaException.class)); + } + + @Test + public void failureOnStopTest() { + client.start(); + AbstractLogCollector logCollector = Mockito.mock(AbstractLogCollector.class); + Mockito.doThrow(new RuntimeException()).when(logCollector).stop(); + ReflectionTestUtils.setField(client, "logCollector", logCollector); + client.stop(); + Mockito.verify(stateListener, Mockito.timeout(1000)).onStopFailure(Mockito.any(KaaException.class)); + } + + @Test + public void failureOnPauseTest() { + client.start(); + KaaClientState clientState = Mockito.mock(KaaClientState.class); + Mockito.doThrow(new RuntimeException()).when(clientState).persist(); + ReflectionTestUtils.setField(client, "kaaClientState", clientState); + client.pause(); + Mockito.verify(stateListener, Mockito.timeout(1000)).onPauseFailure(Mockito.any(KaaException.class)); + } + + @Test + public void failureOnResumeTest() { + client.start(); + KaaInternalChannelManager channelManager = Mockito.mock(KaaInternalChannelManager.class); + Mockito.doThrow(new RuntimeException()).when(channelManager).resume(); + ReflectionTestUtils.setField(client, "channelManager", channelManager); + client.resume(); + Mockito.verify(stateListener, Mockito.timeout(1000)).onResumeFailure(Mockito.any(KaaException.class)); + } + + @Test + public void exceptionCreationTest() { + KaaUnsupportedPlatformException kaaUnsupportedPlatformException = new KaaUnsupportedPlatformException(new Exception()); + ProfileRuntimeException profileRuntimeException = new ProfileRuntimeException(""); + SchemaRuntimeException schemaRuntimeException1 = new SchemaRuntimeException(); + SchemaRuntimeException schemaRuntimeException2 = new SchemaRuntimeException(""); + KaaInvalidConfigurationException invalidConfigurationException = new KaaInvalidConfigurationException(new Exception()); + ChannelRuntimeException channelRuntimeException1 = new ChannelRuntimeException(); + ChannelRuntimeException channelRuntimeException2 = new ChannelRuntimeException(new Exception()); + ChannelRuntimeException channelRuntimeException3 = new ChannelRuntimeException("", new Exception()); + ChannelRuntimeException channelRuntimeException4 = new ChannelRuntimeException("", new Exception(), true, true); + } } diff --git a/client/client-multi/client-java-desktop/pom.xml b/client/client-multi/client-java-desktop/pom.xml index 19b8a9fed6..1e594d0a9a 100644 --- a/client/client-multi/client-java-desktop/pom.xml +++ b/client/client-multi/client-java-desktop/pom.xml @@ -98,6 +98,10 @@ sqlite-jdbc ${sqlite.jdbc.version} + + org.springframework + spring-test + diff --git a/client/client-multi/client-java-desktop/src/test/java/org/kaaproject/kaa/client/connectivity/PingConnectivityCheckerTest.java b/client/client-multi/client-java-desktop/src/test/java/org/kaaproject/kaa/client/connectivity/PingConnectivityCheckerTest.java new file mode 100644 index 0000000000..63df9b5acb --- /dev/null +++ b/client/client-multi/client-java-desktop/src/test/java/org/kaaproject/kaa/client/connectivity/PingConnectivityCheckerTest.java @@ -0,0 +1,35 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.client.connectivity; + +import org.junit.Assert; +import org.junit.Test; + +public class PingConnectivityCheckerTest { + + @Test + public void checkConnectivityToWrongHostTest() { + PingConnectivityChecker pingConnectivityChecker = new PingConnectivityChecker("some-wrong-host=with-dashes-in-name"); + Assert.assertFalse(pingConnectivityChecker.checkConnectivity()); + } + + @Test + public void checkConnectivityForLocalHostTest() { + PingConnectivityChecker pingConnectivityChecker = new PingConnectivityChecker("localhost"); + Assert.assertTrue(pingConnectivityChecker.checkConnectivity()); + } +} diff --git a/client/client-multi/client-java-desktop/src/test/java/org/kaaproject/kaa/client/transport/DesktopHttpClientTest.java b/client/client-multi/client-java-desktop/src/test/java/org/kaaproject/kaa/client/transport/DesktopHttpClientTest.java new file mode 100644 index 0000000000..ac445f7ba7 --- /dev/null +++ b/client/client-multi/client-java-desktop/src/test/java/org/kaaproject/kaa/client/transport/DesktopHttpClientTest.java @@ -0,0 +1,140 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.client.transport; + +import org.apache.http.HttpEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.CloseableHttpClient; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.LinkedHashMap; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + +public class DesktopHttpClientTest { + private static final String URL = "http://some-url"; + private static final String HTTP_CLIENT_FIELD_NAME = "httpClient"; + private static final String HTTP_METHOD_FIELD_NAME = "method"; + private static final int OK = 200; + private static final int FAILURE = 400; + private static PrivateKey privateKey; + private static PublicKey publicKey; + private static PublicKey remotePublicKey; + private static LinkedHashMap entities = new LinkedHashMap<>(); + private CloseableHttpResponse httpResponse; + + @BeforeClass + public static void setUp() { + entities.put("entity1", new byte[]{1, 2, 3}); + entities.put("entity2", new byte[]{53, 1}); + privateKey = mock(PrivateKey.class); + publicKey = mock(PublicKey.class); + remotePublicKey = mock(PublicKey.class); + when(privateKey.getEncoded()).thenReturn(new byte[]{1, 2, 3, 4, 5}); + when(publicKey.getEncoded()).thenReturn(new byte[]{1, 2, 3, 4, 5, 10}); + when(remotePublicKey.getEncoded()).thenReturn(new byte[]{5, 3, 2, 5, 6 , 3, 127}); + } + + @Test(expected = TransportException.class) + public void executeInvalidHttpRequestTest() throws Exception { + DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey); + CloseableHttpClient httpClientMock = mockForHttpClient(FAILURE, true, null); + ReflectionTestUtils.setField(client, HTTP_CLIENT_FIELD_NAME, httpClientMock); + client.executeHttpRequest(URL, entities, false); + verify(httpResponse).close(); + } + + @Test + public void executeValidHttpRequest() throws Exception { + byte[] inputData = new byte[]{100, 101, 102}; + DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey); + CloseableHttpClient httpClientMock = mockForHttpClient(OK, true, inputData); + ReflectionTestUtils.setField(client, HTTP_CLIENT_FIELD_NAME, httpClientMock); + byte[] body = client.executeHttpRequest(URL, entities, false); + Assert.assertArrayEquals(inputData, body); + verify(httpResponse).close(); + } + + @Test + public void canAbortTest() throws Throwable { + DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey); + ReflectionTestUtils.setField(client, HTTP_METHOD_FIELD_NAME, null); + Assert.assertFalse(client.canAbort()); + HttpPost method = new HttpPost(); + method.abort(); + ReflectionTestUtils.setField(client, HTTP_METHOD_FIELD_NAME, method); + Assert.assertFalse(client.canAbort()); + method = new HttpPost(); + ReflectionTestUtils.setField(client, HTTP_METHOD_FIELD_NAME, method); + Assert.assertTrue(client.canAbort()); + } + + @Test(expected = IOException.class) + public void executeValidHttpRequestWithNoResponseEntityTest() throws Exception { + DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey); + CloseableHttpClient httpClientMock = mockForHttpClient(OK, false, null); + ReflectionTestUtils.setField(client, HTTP_CLIENT_FIELD_NAME, httpClientMock); + client.executeHttpRequest(URL, entities, false); + verify(httpResponse).close(); + } + + @Test + public void closeTest() throws IOException { + DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey); + CloseableHttpClient httpClientMock = mockForHttpClient(OK, false, null); + ReflectionTestUtils.setField(client, HTTP_CLIENT_FIELD_NAME, httpClientMock); + client.close(); + verify(httpClientMock).close(); + } + + @Test + public void abortTest() throws IOException { + DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey); + HttpPost method = mock(HttpPost.class); + when(method.isAborted()).thenReturn(false); + ReflectionTestUtils.setField(client, HTTP_METHOD_FIELD_NAME, method); + client.abort(); + verify(method).abort(); + } + + private CloseableHttpClient mockForHttpClient(int status, boolean hasEntity, byte[] body) throws IOException { + CloseableHttpClient httpClientMock = mock(CloseableHttpClient.class); + httpResponse = mock(CloseableHttpResponse.class, RETURNS_DEEP_STUBS); + doReturn(httpResponse).when(httpClientMock).execute(any(HttpPost.class)); + if (hasEntity) { + HttpEntity entity = mock(HttpEntity.class); + doReturn(entity).when(httpResponse).getEntity(); + if (body != null) { + doReturn(new ByteArrayInputStream(body)).when(entity).getContent(); + } + } else { + doReturn(null).when(httpResponse).getEntity(); + } + when(httpResponse.getStatusLine().getStatusCode()).thenReturn(status); + return httpClientMock; + } +} diff --git a/common/endpoint-shared/src/test/java/org/kaaproject/kaa/common/kaatcp/KaaTcpMessageTest.java b/common/endpoint-shared/src/test/java/org/kaaproject/kaa/common/kaatcp/KaaTcpMessageTest.java index 6ea79cfe1f..e9adde2827 100644 --- a/common/endpoint-shared/src/test/java/org/kaaproject/kaa/common/kaatcp/KaaTcpMessageTest.java +++ b/common/endpoint-shared/src/test/java/org/kaaproject/kaa/common/kaatcp/KaaTcpMessageTest.java @@ -35,6 +35,8 @@ public class KaaTcpMessageTest { @Test public void testSyncResponseMessage() { final byte kaaSync[] = new byte [] { (byte) 0xF0, 0x0D, 0x00, 0x06, 'K', 'a', 'a', 't', 'c', 'p', 0x01, 0x00, 0x05, 0x14, (byte) 0xFF }; + SyncResponse syncResponse = new SyncResponse(); + Assert.assertNotNull(syncResponse); SyncResponse message = new SyncResponse(new byte [] { (byte) 0xFF }, false, true); message.setMessageId(5); byte[] actual = message.getFrame().array(); diff --git a/server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogAppenderTest.java b/server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogAppenderTest.java index 2fd70d748a..1fd1e77a27 100755 --- a/server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogAppenderTest.java +++ b/server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogAppenderTest.java @@ -17,6 +17,7 @@ package org.kaaproject.kaa.server.appenders.file.appender; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; import java.io.File; import java.util.Arrays; @@ -90,6 +91,15 @@ public void testAppend() throws Exception { } } + @Test + public void appendToClosedAppenderTest() { + FileSystemLogAppender appender = new FileSystemLogAppender(); + LogDeliveryCallback listener = mock(LogDeliveryCallback.class); + ReflectionTestUtils.setField(appender, "closed", true); + appender.doAppend(null, null, listener); + verify(listener).onInternalError(); + } + @Test public void testAppendWithInternalError() throws Exception { FileSystemLogAppender appender = new FileSystemLogAppender(); @@ -147,27 +157,27 @@ public void initTest() throws Exception { appender.close(); } } - + private LogAppenderDto prepareConfig() throws Exception { LogAppenderDto logAppenderDto = new LogAppenderDto(); logAppenderDto.setApplicationId(APPLICATION_ID); logAppenderDto.setName("test"); logAppenderDto.setTenantId(TENANT_ID); - + RawSchema rawSchema = new RawSchema(FileConfig.getClassSchema().toString()); - DefaultRecordGenerationAlgorithm algotithm = - new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory()); + DefaultRecordGenerationAlgorithm algotithm = + new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory()); RawData rawData = algotithm.getRootData(); - AvroJsonConverter converter = + AvroJsonConverter converter = new AvroJsonConverter<>(FileConfig.getClassSchema(), FileConfig.class); FileConfig fileConfig = converter.decodeJson(rawData.getRawData()); - + fileConfig.setLogsRootPath(System.getProperty("java.io.tmpdir") + File.separator + "tmp_logs_"+System.currentTimeMillis()); - + AvroByteArrayConverter byteConverter = new AvroByteArrayConverter<>(FileConfig.class); byte[] rawConfiguration = byteConverter.toByteArray(fileConfig); - + logAppenderDto.setRawConfiguration(rawConfiguration); return logAppenderDto; diff --git a/server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogEventServiceImplTest.java b/server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogEventServiceImplTest.java index 3757aa4539..7b544d7125 100755 --- a/server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogEventServiceImplTest.java +++ b/server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogEventServiceImplTest.java @@ -18,8 +18,11 @@ import java.io.File; import java.io.FileNotFoundException; +import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import org.junit.Assert; @@ -27,6 +30,8 @@ import org.mockito.Mockito; import org.slf4j.Logger; +import javax.swing.filechooser.FileSystemView; + public class FileSystemLogEventServiceImplTest { private static final String TEST_FILE = "/test"; @@ -88,4 +93,31 @@ public void createDirectoryAlreadyExistsTest() throws NoSuchFieldException, Secu logEventService.removeAll(tempDir); } } + + @Test + public void executeCommandNullWorkingDirTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException { + String homeDir = System.getProperty("user.home"); + String testDir = "testdir"; + FileSystemLogEventServiceImpl service = new FileSystemLogEventServiceImpl(); + Method executeCommand = FileSystemLogEventServiceImpl.class.getDeclaredMethod("executeCommand", File.class, String[].class); + executeCommand.setAccessible(true); + executeCommand.invoke(service, null, new String[]{"mkdir", testDir}); + File created = new File(homeDir, testDir); + Assert.assertTrue(created.exists()); + created.delete(); + } + + @Test(expected = RuntimeException.class) + public void executeCommandFailureTest() throws Throwable { + String testDir = "testdir"; + File rootDir = FileSystemView.getFileSystemView().getRoots()[0]; + FileSystemLogEventServiceImpl service = new FileSystemLogEventServiceImpl(); + Method executeCommand = FileSystemLogEventServiceImpl.class.getDeclaredMethod("executeCommand", File.class, String[].class); + executeCommand.setAccessible(true); + try { + executeCommand.invoke(service, rootDir, new String[]{"mkdir", testDir}); + } catch (InvocationTargetException e){ + throw e.getCause(); + } + } } diff --git a/server/appenders/flume/appender/src/test/java/org/kaaproject/kaa/server/appenders/flume/appender/FlumeLogAppenderTest.java b/server/appenders/flume/appender/src/test/java/org/kaaproject/kaa/server/appenders/flume/appender/FlumeLogAppenderTest.java index 7457037c41..7b35382913 100755 --- a/server/appenders/flume/appender/src/test/java/org/kaaproject/kaa/server/appenders/flume/appender/FlumeLogAppenderTest.java +++ b/server/appenders/flume/appender/src/test/java/org/kaaproject/kaa/server/appenders/flume/appender/FlumeLogAppenderTest.java @@ -138,6 +138,15 @@ public AppendBatchAsyncResultPojo call() throws Exception { Assert.assertTrue(callback.success); } + @Test + public void appendWhenClosedTest() { + appender.close(); + LogEventPack eventPack = new LogEventPack(); + TestLogDeliveryCallback callback = new TestLogDeliveryCallback(); + appender.doAppend(eventPack, callback); + Assert.assertTrue(callback.internallError); + } + @Test public void appendWithEmptyClientManagerTest() throws EventDeliveryException { LogEventPack eventPack = new LogEventPack(); diff --git a/server/appenders/flume/appender/src/test/java/org/kaaproject/kaa/server/appenders/flume/appender/client/BalancingFlumeClientManagerTest.java b/server/appenders/flume/appender/src/test/java/org/kaaproject/kaa/server/appenders/flume/appender/client/BalancingFlumeClientManagerTest.java index 6f92de8175..58c34736ba 100755 --- a/server/appenders/flume/appender/src/test/java/org/kaaproject/kaa/server/appenders/flume/appender/client/BalancingFlumeClientManagerTest.java +++ b/server/appenders/flume/appender/src/test/java/org/kaaproject/kaa/server/appenders/flume/appender/client/BalancingFlumeClientManagerTest.java @@ -33,8 +33,8 @@ public final void before() { flumeNodes = FlumeNodes .newBuilder() .setFlumeNodes( - Arrays.asList(new FlumeNode("localhost", 12121), - new FlumeNode("localhost", 12122))).build(); + Arrays.asList(new FlumeNode("localhost", 12121), + new FlumeNode("localhost", 12122))).build(); configuration.setHostsBalancing(flumeNodes); configuration.setCallbackThreadPoolSize(2); configuration.setClientsThreadPoolSize(2); @@ -47,7 +47,7 @@ public void initFlumeClientWithFlumeAgentTest() throws Exception { clientManager = FlumeClientManager.getInstance(configuration); clientManager.sendEventToFlume(EventBuilder.withBody(testEventBody)); } - + @Test public void initFlumeClientWithFlumeAgentAsyncTest() throws Exception { flumeSourceRunner.startFlumeSource("agent", "localhost", 12121); @@ -74,4 +74,8 @@ public void initFlumeClientWithFlumeAgentAndOneHostTest() throws Exception { clientManager.sendEventToFlume(EventBuilder.withBody(testEventBody)); } + @Test(expected = RuntimeException.class) + public void currentClientNullTest() { + clientManager.init(null); + } } diff --git a/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/DefaultOperationsServerListServiceTest.java b/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/DefaultOperationsServerListServiceTest.java index 967d7ae84d..98893a4c91 100644 --- a/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/DefaultOperationsServerListServiceTest.java +++ b/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/DefaultOperationsServerListServiceTest.java @@ -20,6 +20,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.Set; import org.junit.Assert; @@ -33,15 +34,16 @@ import org.kaaproject.kaa.server.sync.bootstrap.ProtocolConnectionData; import org.kaaproject.kaa.server.sync.bootstrap.ProtocolVersionId; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; /** - * + * * @author Andrew Shvayka * */ public class DefaultOperationsServerListServiceTest { - OperationsServerListService service; + private DefaultOperationsServerListService service; @Before public void before() { @@ -96,4 +98,41 @@ public void testFilterNoResults() { Assert.assertNotNull(result); Assert.assertEquals(0, result.size()); } + + @Test(expected = RuntimeException.class) + public void filterInterrupted() throws InterruptedException { + DefaultOperationsServerListService.Memorizer memorizer = Mockito.mock(DefaultOperationsServerListService.Memorizer.class); + Mockito.doThrow(new InterruptedException()).when(memorizer).compute(Mockito.any(Object.class)); + ReflectionTestUtils.setField(service, "cache", memorizer); + service.filter(Collections.EMPTY_LIST); + } + + @Test + public void testOnNodeAddedAndUpdated() { + OperationsNodeInfo nodeInfo = Mockito.mock(OperationsNodeInfo.class); + ConnectionInfo connectionInfo = Mockito.mock(ConnectionInfo.class); + Mockito.when(nodeInfo.getConnectionInfo()).thenReturn(connectionInfo); + Map opsMap = Mockito.mock(Map.class); + ReflectionTestUtils.setField(service, "opsMap", opsMap); + DefaultOperationsServerListService.Memorizer memorizer = Mockito.mock(DefaultOperationsServerListService.Memorizer.class); + ReflectionTestUtils.setField(service, "cache", memorizer); + service.onNodeUpdated(nodeInfo); + service.onNodeAdded(nodeInfo); + Mockito.verify(opsMap, Mockito.times(2)).put(Mockito.anyString(), Mockito.eq(nodeInfo)); + Mockito.verify(memorizer, Mockito.times(2)).clear(); + } + + @Test + public void testOnNodeRemoved() { + OperationsNodeInfo nodeInfo = Mockito.mock(OperationsNodeInfo.class); + ConnectionInfo connectionInfo = Mockito.mock(ConnectionInfo.class); + Mockito.when(nodeInfo.getConnectionInfo()).thenReturn(connectionInfo); + Map opsMap = Mockito.mock(Map.class); + ReflectionTestUtils.setField(service, "opsMap", opsMap); + DefaultOperationsServerListService.Memorizer memorizer = Mockito.mock(DefaultOperationsServerListService.Memorizer.class); + ReflectionTestUtils.setField(service, "cache", memorizer); + service.onNodeRemoved(nodeInfo); + Mockito.verify(opsMap, Mockito.only()).remove(Mockito.anyString()); + Mockito.verify(memorizer, Mockito.only()).clear(); + } } diff --git a/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/security/FileKeyStoreServiceTest.java b/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/security/FileKeyStoreServiceTest.java index 75011762f3..7358de6515 100644 --- a/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/security/FileKeyStoreServiceTest.java +++ b/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/security/FileKeyStoreServiceTest.java @@ -15,7 +15,7 @@ */ /** - * + * */ package org.kaaproject.kaa.server.bootstrap.service.security; @@ -31,7 +31,6 @@ /** * @author Andrey Panasenko - * */ public class FileKeyStoreServiceTest { @@ -40,7 +39,7 @@ public class FileKeyStoreServiceTest { private static final String PUBLIC_KEY_LOCATION = "publicKey"; private static final String PRIVATE_KEY_PATH = SERVER_HOME_DIR + "/" + PRIVATE_KEY_LOCATION; private static final String PUBLIC_KEY_PATH = SERVER_HOME_DIR + "/" + PUBLIC_KEY_LOCATION; - + /** * @throws java.lang.Exception */ @@ -76,18 +75,18 @@ public void testLoadKeys() { if (pub.exists()) { pub.delete(); } - + ks.loadKeys(); - + if (!pri.exists() || !pri.canRead()) { fail("Private key file create failed."); } if (!pub.exists() || !pub.canRead()) { fail("Public key file create failed."); } - + //Test load incorrect files. - + if (pub.exists()) { pub.delete(); FileWriter pubfw; @@ -102,9 +101,9 @@ public void testLoadKeys() { try { ks.loadKeys(); } catch (Exception e) { - assertNotNull(e.toString(),e); + assertNotNull(e.toString(), e); } - + if (pri.exists()) { pri.delete(); FileWriter prifw; @@ -119,10 +118,10 @@ public void testLoadKeys() { try { ks.loadKeys(); } catch (Exception e) { - assertNotNull(e.toString(),e); + assertNotNull(e.toString(), e); } - - + + } /** @@ -138,7 +137,7 @@ public void testGetPrivateKey() { if (pub.exists()) { pub.delete(); } - + FileKeyStoreService ks = new FileKeyStoreService(); assertNotNull(ks); ks.setPrivateKeyLocation(PRIVATE_KEY_LOCATION); @@ -168,4 +167,41 @@ public void testGetPublicKey() { assertNotNull(ks.getPublicKey()); } + @Test(expected = RuntimeException.class) + public void testIncorrectPublicKey() throws IOException { + FileKeyStoreService ks = new FileKeyStoreService(); + assertNotNull(ks); + ks.setPublicKeyLocation(PUBLIC_KEY_LOCATION); + + File pub = new File(PUBLIC_KEY_PATH); + if (pub.exists()) { + pub.delete(); + } + + FileWriter pubfw; + pubfw = new FileWriter(pub); + pubfw.write("ascasdca42314*&^*$@^#5$^&sdcasdc"); + pubfw.close(); + + ks.loadKeys(); + } + + @Test(expected = RuntimeException.class) + public void testIncorrectPrivateKey() throws IOException { + FileKeyStoreService ks = new FileKeyStoreService(); + assertNotNull(ks); + ks.setPrivateKeyLocation(PRIVATE_KEY_LOCATION); + + File pub = new File(PRIVATE_KEY_PATH); + if (pub.exists()) { + pub.delete(); + } + + FileWriter privfw; + privfw = new FileWriter(pub); + privfw.write("ascasdca42314*&^*$@^#5$^&sdcasdc"); + privfw.close(); + + ks.loadKeys(); + } } diff --git a/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/transport/BootstrapTransportServiceTest.java b/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/transport/BootstrapTransportServiceTest.java new file mode 100644 index 0000000000..5416f98906 --- /dev/null +++ b/server/bootstrap/src/test/java/org/kaaproject/kaa/server/bootstrap/service/transport/BootstrapTransportServiceTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2014 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.kaaproject.kaa.server.bootstrap.service.transport; + +import org.junit.Before; +import org.junit.Test; +import org.kaaproject.kaa.server.bootstrap.service.security.KeyStoreService; +import org.kaaproject.kaa.server.transport.channel.ChannelContext; +import org.kaaproject.kaa.server.transport.message.ErrorBuilder; +import org.kaaproject.kaa.server.transport.message.MessageHandler; +import org.kaaproject.kaa.server.transport.message.SessionInitMessage; +import org.springframework.test.util.ReflectionTestUtils; + +import javax.crypto.NoSuchPaddingException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.Properties; + +import static org.mockito.Mockito.*; + +public class BootstrapTransportServiceTest { + private KeyPairGenerator keyPairGenerator; + private static final String RSA = "RSA"; + + @Before + public void before() throws NoSuchProviderException, NoSuchAlgorithmException, NoSuchPaddingException { + keyPairGenerator = KeyPairGenerator.getInstance(RSA); + } + + @Test + public void messageHandlerProcessTest() { + BootstrapTransportService bService = new BootstrapTransportService(); + KeyStoreService keyStoreService = mock(KeyStoreService.class); + KeyPair keyPair = keyPairGenerator.generateKeyPair(); + PublicKey publicKey = keyPair.getPublic(); + PrivateKey privateKey = keyPair.getPrivate(); + when(keyStoreService.getPublicKey()).thenReturn(publicKey); + when(keyStoreService.getPrivateKey()).thenReturn(privateKey); + ReflectionTestUtils.setField(bService, "supportUnencryptedConnection", true); + ReflectionTestUtils.setField(bService, "keyStoreService", keyStoreService); + ReflectionTestUtils.setField(bService, "properties", new Properties()); + bService.lookupAndInit(); + MessageHandler handler = (BootstrapTransportService.BootstrapMessageHandler) ReflectionTestUtils.getField(bService, "handler"); + SessionInitMessage encryptedSessionInitMessage = mockForSessionInitMessage(true); + SessionInitMessage nonEncryptedSessionInitMessage = mockForSessionInitMessage(false); + handler.process(encryptedSessionInitMessage); + handler.process(nonEncryptedSessionInitMessage); + verify(encryptedSessionInitMessage, timeout(1000)).getEncodedMessageData(); + verify(nonEncryptedSessionInitMessage, timeout(1000)).getEncodedMessageData(); + } + + private SessionInitMessage mockForSessionInitMessage(boolean isEncrypted) { + SessionInitMessage message = mock(SessionInitMessage.class); + when(message.isEncrypted()).thenReturn(isEncrypted); + when(message.getEncodedMessageData()).thenReturn(new byte[]{2, 3, 4, 5}); + when(message.getEncodedSessionKey()).thenReturn(new byte[]{10, 11, 12, 13}); + when(message.getChannelContext()).thenReturn(mock(ChannelContext.class)); + when(message.getErrorBuilder()).thenReturn(mock(ErrorBuilder.class)); + return message; + } +} diff --git a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/AbstractTest.java b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/AbstractTest.java index 48459a31e6..962e7ae6dd 100644 --- a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/AbstractTest.java +++ b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/AbstractTest.java @@ -70,6 +70,7 @@ import org.kaaproject.kaa.common.dto.logs.LogAppenderDto; import org.kaaproject.kaa.common.dto.logs.LogHeaderStructureDto; import org.kaaproject.kaa.common.dto.logs.LogSchemaDto; +import org.kaaproject.kaa.common.dto.user.UserVerifierDto; import org.kaaproject.kaa.server.common.core.algorithms.generation.DefaultRecordGenerationAlgorithmImpl; import org.kaaproject.kaa.server.common.core.configuration.BaseDataFactory; import org.kaaproject.kaa.server.common.core.configuration.OverrideDataFactory; @@ -126,6 +127,8 @@ public class AbstractTest { @Autowired protected UserService userService; @Autowired + protected UserVerifierService verifierService; + @Autowired protected UserConfigurationService userConfigurationService; @Autowired protected ConfigurationDao configurationDao; @@ -184,11 +187,9 @@ protected void clearDBData() { /** * Gets the resource as string. * - * @param path - * the path + * @param path the path * @return the resource as string - * @throws java.io.IOException - * Signals that an I/O exception has occurred. + * @throws java.io.IOException Signals that an I/O exception has occurred. */ protected static String getResourceAsString(String path) throws IOException { URL url = Thread.currentThread().getContextClassLoader().getResource(path); @@ -293,7 +294,7 @@ protected List generateConfSchema(String appId, int coun } protected List generateConfiguration(String schemaId, String groupId, int count, boolean activate, - boolean useBaseSchema) { + boolean useBaseSchema) { List ids = Collections.emptyList(); try { ConfigurationSchemaDto schemaDto; @@ -449,6 +450,21 @@ protected TenantAdminDto generateTenantAdmin(TenantDto tenantDto, String userId) return tenant; } + + protected UserVerifierDto generateUserVerifier(String appId, String verifierToken) { + UserVerifierDto verifier = new UserVerifierDto(); + verifier.setName("GENERATED test Verifier"); + if (isBlank(appId)) { + appId = generateApplication().getId(); + } + verifier.setApplicationId(appId); + if (verifierToken == null) { + verifierToken = "token"; + } + verifier.setVerifierToken(verifierToken); + return verifierService.saveUserVerifier(verifier); + } + protected List generateUsers(String tenantId, KaaAuthorityDto authority, int count) { List users = new ArrayList<>(count); UserDto userDto = null; @@ -596,26 +612,38 @@ protected LogAppenderDto generateLogAppender(String appId, String schemaId) { } protected EndpointUserConfigurationDto generateEndpointUserConfiguration(EndpointUserDto endpointUser, ApplicationDto applicationDto, - ConfigurationSchemaDto configurationSchema) { + ConfigurationSchemaDto configurationSchema) { return generateEndpointUserConfiguration(endpointUser, applicationDto, configurationSchema, UUID.randomUUID().toString()); } protected EndpointUserConfigurationDto generateEndpointUserConfiguration(EndpointUserDto endpointUser, ApplicationDto applicationDto, - ConfigurationSchemaDto configurationSchema, String body) { + ConfigurationSchemaDto configurationSchema, String body) { + return generateEndpointUserConfiguration(endpointUser, applicationDto, configurationSchema, body, false); + } + + protected EndpointUserConfigurationDto generateEndpointUserConfiguration(EndpointUserDto endpointUser, ApplicationDto applicationDto, + ConfigurationSchemaDto configurationSchema, String body, boolean isNullAppDto) { EndpointUserConfigurationDto configurationDto = new EndpointUserConfigurationDto(); + configurationDto.setBody(body); + if (endpointUser == null) { endpointUser = generateEndpointUser(null); } - if (applicationDto == null) { - applicationDto = generateApplication(); + if (!isNullAppDto) { + if (applicationDto == null) { + applicationDto = generateApplication(); + } + configurationDto.setAppToken(applicationDto.getApplicationToken()); + } else { + return userConfigurationService.saveUserConfiguration(configurationDto); } configurationDto.setUserId(endpointUser.getId()); + if (configurationSchema == null) { configurationSchema = generateConfSchema(applicationDto.getId(), 1).get(0); } configurationDto.setSchemaVersion(configurationSchema.getMajorVersion()); - configurationDto.setBody(body); - configurationDto.setAppToken(applicationDto.getApplicationToken()); + return userConfigurationService.saveUserConfiguration(configurationDto); } } diff --git a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateAbstractTest.java b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateAbstractTest.java index 240ef0d4bf..c9cb6a9f3d 100644 --- a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateAbstractTest.java +++ b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateAbstractTest.java @@ -54,6 +54,7 @@ import org.kaaproject.kaa.server.common.dao.impl.TopicDao; import org.kaaproject.kaa.server.common.dao.impl.UserDao; import org.kaaproject.kaa.server.common.dao.impl.UserVerifierDao; +import org.kaaproject.kaa.server.common.dao.impl.LogAppenderDao; import org.kaaproject.kaa.server.common.dao.model.sql.Application; import org.kaaproject.kaa.server.common.dao.model.sql.ApplicationEventFamilyMap; import org.kaaproject.kaa.server.common.dao.model.sql.ApplicationEventMap; @@ -74,6 +75,7 @@ import org.kaaproject.kaa.server.common.dao.model.sql.Topic; import org.kaaproject.kaa.server.common.dao.model.sql.User; import org.kaaproject.kaa.server.common.dao.model.sql.UserVerifier; +import org.kaaproject.kaa.server.common.dao.model.sql.LogAppender; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -84,6 +86,8 @@ public abstract class HibernateAbstractTest { public static final Random RANDOM = new Random(); + @Autowired + protected LogAppenderDao appenderDao; @Autowired protected UserDao userDao; @Autowired @@ -353,6 +357,17 @@ protected Topic generateTopic(Application app, TopicTypeDto type, String topicNa return topicDao.save(topic); } + protected LogAppender generateLogAppender(Application app){ + LogAppender appender = new LogAppender(); + if (app == null) { + app = generateApplication(null); + } + appender.setApplication(app); + appender.setMinLogSchemaVersion(1); + appender.setMaxLogSchemaVersion(2); + return appenderDao.save(appender); + } + protected List generateEventClassFamily(Tenant tenant, int count) { int eventSchemaVersionsCount = 2; if (tenant == null) { @@ -487,9 +502,9 @@ protected String readSchemaFileAsString(String filePath) throws IOException { return null; } - protected UserVerifier generateUserVerifier(Application app, String verifierToken) { + protected UserVerifier generateUserVerifier(Application app, String verifierToken){ UserVerifier verifier = new UserVerifier(); - verifier.setName("GENERATED test Verifier" + UUID.randomUUID().toString()); + verifier.setName("GENERATED test Verifier"); if (app == null) { app = generateApplication(null); } @@ -517,5 +532,4 @@ protected SdkKey generateSdkKey(Application app, String token, byte[] key) { sdkKey.setData(key); return sdkKeyDao.save(sdkKey); } - } diff --git a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateLogAppenderTest.java b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateLogAppenderTest.java new file mode 100644 index 0000000000..e1de79aec6 --- /dev/null +++ b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateLogAppenderTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.kaaproject.kaa.server.common.dao.impl.sql; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.kaaproject.kaa.server.common.dao.model.sql.Application; +import org.kaaproject.kaa.server.common.dao.model.sql.LogAppender; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = "/common-dao-test-context.xml") +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +@Transactional +public class HibernateLogAppenderTest extends HibernateAbstractTest { + private static final Logger LOG = LoggerFactory.getLogger(HibernateLogAppenderTest.class); + + @Test + public void findByAppIdTest() { + LogAppender appender = generateLogAppender(null); + Application app = appender.getApplication(); + List result = appenderDao.findByAppId(app.getId().toString()); + System.out.println(result.get(0)); + Assert.assertEquals(result.size(), 1); + } + + @Test + public void findByAppIdBlankIdTest() { + List result = appenderDao.findByAppId(""); + Assert.assertTrue(result.isEmpty()); + } + + @Test + public void findByAppIdAndSchemaVersionBlankIdTest() { + LogAppender appender = generateLogAppender(null); + List result = appenderDao.findByAppIdAndSchemaVersion("", appender.getMinLogSchemaVersion()); + Assert.assertTrue(result.isEmpty()); + } + +} diff --git a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateUserVerifierTest.java b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateUserVerifierTest.java new file mode 100644 index 0000000000..c737b31202 --- /dev/null +++ b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/impl/sql/HibernateUserVerifierTest.java @@ -0,0 +1,71 @@ +/* + * Copyright 2014 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.common.dao.impl.sql; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.kaaproject.kaa.server.common.dao.model.sql.Application; +import org.kaaproject.kaa.server.common.dao.model.sql.UserVerifier; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = "/common-dao-test-context.xml") +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +@Transactional +public class HibernateUserVerifierTest extends HibernateAbstractTest{ + + private static final Logger LOG = LoggerFactory.getLogger(HibernateUserVerifierTest.class); + + @Test + public void findByAppIdTest() { + UserVerifier verifier = generateUserVerifier(null, null); + Application app = verifier.getApplication(); + List result = verifierDao.findByAppId(app.getId().toString()); + Assert.assertEquals(result.size(), 1); + } + + @Test + public void findByAppIdBlankIdTest() { + UserVerifier verifier = generateUserVerifier(null, null); + List result = verifierDao.findByAppId(""); + Assert.assertTrue(result.isEmpty()); + } + + @Test + public void findByAppIdAndVerifierTokenTest() { + UserVerifier verifier = generateUserVerifier(null, null); + Application app = verifier.getApplication(); + UserVerifier result = verifierDao.findByAppIdAndVerifierToken(app.getId().toString(), verifier.getVerifierToken()); + Assert.assertEquals(result, verifier); + } + + @Test + public void findByAppIdAndVerifierTokenBlankIdTest() { + UserVerifier verifier = generateUserVerifier(null, null); + UserVerifier result = verifierDao.findByAppIdAndVerifierToken("", verifier.getVerifierToken()); + Assert.assertNull(result); + } + +} diff --git a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/ProfileServiceImplTest.java b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/ProfileServiceImplTest.java index 4f501faa7f..2aecee9f4d 100644 --- a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/ProfileServiceImplTest.java +++ b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/ProfileServiceImplTest.java @@ -16,6 +16,8 @@ package org.kaaproject.kaa.server.common.dao.service; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.HashSet; import java.util.List; import java.util.Set; @@ -123,6 +125,18 @@ public void activateProfileFilterTest() { Assert.assertNotEquals(filterDto.getSequenceNumber(), profileFilterDto.getSequenceNumber()); } + @Test(expected = UpdateStatusConflictException.class) + public void activateProfileFilterActiveStatusTest() { + List filters = generateFilter(null, null, 1, true); + ProfileFilterDto filterDto = filters.get(0); + ChangeProfileFilterNotification activated = profileService.activateProfileFilter(filterDto.getId(), null); + } + + @Test(expected = IncorrectParameterException.class) + public void activateProfileFilterNoProfileFilterTest() { + ChangeProfileFilterNotification activated = profileService.activateProfileFilter("13232", null); + } + @Test public void removeProfileFiltersByProfileSchemaIdTest() { List schemas = generateProfSchema(null, 1); @@ -401,4 +415,44 @@ public void updateExistingProfileSchemaWithIncorrectIdTest() { profileService.saveProfileSchema(profileSchema); } + @Test(expected = IncorrectParameterException.class) + public void validateFilterNullDtoTest() throws Throwable { + ProfileServiceImpl profileServiceImpl = new ProfileServiceImpl(); + Method validateMethod = profileServiceImpl.getClass().getDeclaredMethod("validateFilter", ProfileFilterDto.class); + validateMethod.setAccessible(true); + try { + validateMethod.invoke(profileServiceImpl, new ProfileFilterDto[]{null}); + } catch (InvocationTargetException e) { + throw e.getCause(); + } + } + + @Test(expected = IncorrectParameterException.class) + public void validateFilterBlankSchemaIdTest() throws Throwable { + ProfileServiceImpl profileServiceImpl = new ProfileServiceImpl(); + Method validateMethod = profileServiceImpl.getClass().getDeclaredMethod("validateFilter", ProfileFilterDto.class); + validateMethod.setAccessible(true); + ProfileFilterDto filterDto = new ProfileFilterDto(); + filterDto.setSchemaId(""); + try { + validateMethod.invoke(profileServiceImpl, filterDto); + } catch (InvocationTargetException e){ + throw e.getCause(); + } + } + + @Test(expected = IncorrectParameterException.class) + public void validateFilterBlankEndpoinGroupIdTest() throws Throwable { + ProfileServiceImpl profileServiceImpl = new ProfileServiceImpl(); + Method validateMethod = profileServiceImpl.getClass().getDeclaredMethod("validateFilter", ProfileFilterDto.class); + validateMethod.setAccessible(true); + ProfileFilterDto filterDto = new ProfileFilterDto(); + filterDto.setEndpointGroupId(""); + try { + validateMethod.invoke(profileServiceImpl, filterDto); + } catch (InvocationTargetException e){ + throw e.getCause(); + } + } + } diff --git a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/UserConfigurationServiceImplTest.java b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/UserConfigurationServiceImplTest.java index aa1b2ee52d..53ab42714d 100644 --- a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/UserConfigurationServiceImplTest.java +++ b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/UserConfigurationServiceImplTest.java @@ -24,6 +24,7 @@ import org.kaaproject.kaa.common.dto.EndpointUserConfigurationDto; import org.kaaproject.kaa.common.dto.EndpointUserDto; import org.kaaproject.kaa.server.common.dao.AbstractTest; +import org.kaaproject.kaa.server.common.dao.exception.IncorrectParameterException; import java.io.IOException; import java.util.ArrayList; @@ -85,4 +86,31 @@ public void saveUserConfigurationTest() throws IOException { EndpointUserConfigurationDto configurationDto = generateEndpointUserConfiguration(null, null, null, readSchemaFileAsString(OVERRIDE_USER_DATA_JSON)); Assert.assertNotNull(configurationDto); } + + @Test + public void userConfigNullTest() { + EndpointUserConfigurationDto dto = null; + EndpointUserConfigurationDto result = userConfigurationService.saveUserConfiguration(dto); + Assert.assertNull(result); + } + + @Test + public void userConfigNotNullTest() throws IOException { + EndpointUserConfigurationDto configurationDto = generateEndpointUserConfiguration(null, null, null, readSchemaFileAsString(OVERRIDE_USER_DATA_JSON)); + EndpointUserConfigurationDto result = userConfigurationService.saveUserConfiguration(configurationDto); + Assert.assertEquals(configurationDto, result); + } + + @Test(expected = IncorrectParameterException.class) + public void saveUserConfigBlankTest() { + EndpointUserConfigurationDto configurationDto = generateEndpointUserConfiguration(null, null, null, ""); + userConfigurationService.saveUserConfiguration(configurationDto); + } + + @Test(expected = IncorrectParameterException.class) + public void appDtoNullTest() throws IOException { + EndpointUserConfigurationDto configurationDto = generateEndpointUserConfiguration(null, null, null, readSchemaFileAsString(OVERRIDE_USER_DATA_JSON),true); + EndpointUserConfigurationDto result = userConfigurationService.saveUserConfiguration(configurationDto); + Assert.assertEquals(configurationDto, result); + } } diff --git a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/UserVerifierServiceImplTest.java b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/UserVerifierServiceImplTest.java new file mode 100644 index 0000000000..2d7e10eb29 --- /dev/null +++ b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/UserVerifierServiceImplTest.java @@ -0,0 +1,78 @@ +/* + * Copyright 2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.common.dao.service; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.kaaproject.kaa.common.dto.user.UserVerifierDto; +import org.kaaproject.kaa.server.common.dao.AbstractTest; + +import java.util.List; + + +@Ignore("This test should be extended and initialized with proper context in each NoSQL submodule") +public class UserVerifierServiceImplTest extends AbstractTest { + + @Before + public void beforeTest() throws Exception { + clearDBData(); + } + + @Test + public void findUserVerifiersByAppIdTest(){ + UserVerifierDto verifierDto1 = generateUserVerifier(null, null); + List found = verifierService.findUserVerifiersByAppId(verifierDto1.getApplicationId()); + Assert.assertEquals(2, found.size()); + } + + @Test + public void findUserVerifiersByAppIdAndVerifierTokenTest(){ + UserVerifierDto verifierDto = generateUserVerifier(null, null); + UserVerifierDto found = verifierService.findUserVerifiersByAppIdAndVerifierToken(verifierDto.getApplicationId(), verifierDto.getVerifierToken()); + Assert.assertEquals(verifierDto, found); + } + + @Test + public void findUserVerifierByIdTest(){ + UserVerifierDto verifierDto = generateUserVerifier(null, null); + UserVerifierDto found = verifierService.findUserVerifierById(verifierDto.getId()); + Assert.assertEquals(verifierDto, found); + } + + @Test + public void saveUserVerifierTest(){ + UserVerifierDto verifierDto = generateUserVerifier(null, null); + UserVerifierDto found = verifierService.saveUserVerifier(verifierDto); + Assert.assertEquals(verifierDto, found); + } + + @Test + public void saveUserVerifierNullVerifierDtoTest(){ + UserVerifierDto found = verifierService.saveUserVerifier(null); + Assert.assertNull(found); + } + + @Test + public void removeUserVerifierByIdTest(){ + UserVerifierDto verifierDto = generateUserVerifier(null, null); + verifierService.removeUserVerifierById(verifierDto.getId()); + UserVerifierDto found = verifierService.findUserVerifierById(verifierDto.getId()); + Assert.assertNull(found); + } +} diff --git a/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/ValidatorTest.java b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/ValidatorTest.java new file mode 100644 index 0000000000..61f7a04d1b --- /dev/null +++ b/server/common/dao/src/test/java/org/kaaproject/kaa/server/common/dao/service/ValidatorTest.java @@ -0,0 +1,70 @@ +/* + * Copyright 2014 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.common.dao.service; + +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.common.dto.HasId; +import org.kaaproject.kaa.server.common.dao.exception.IncorrectParameterException; + +public class ValidatorTest { + + @Test + public void isValidSqlObjectTest() { + HasId hasId = new HasId() { + private String id; + + @Override + public String getId() { + return id; + } + + @Override + public void setId(String id) { + this.id = id; + } + }; + hasId.setId("not number"); + boolean valid = Validator.isValidSqlObject(hasId); + Assert.assertFalse(valid); + } + + @Test(expected = IncorrectParameterException.class) + public void validateSqlIdTest() { + Validator.validateSqlId("", "err msg"); + } + + @Test(expected = IncorrectParameterException.class) + public void validateStringTest() { + Validator.validateString(null, "err msg"); + } + + @Test(expected = IncorrectParameterException.class) + public void validateObjectTest() { + Validator.validateObject(null, "err msg"); + } + + @Test(expected = IncorrectParameterException.class) + public void validateSqlObjectTest() { + Validator.validateSqlObject(null, "err msg"); + } + + @Test(expected = IncorrectParameterException.class) + public void validateHashTest() { + Validator.validateHash(null, "err msg"); + } +} diff --git a/server/common/netty-server/src/test/java/org/netty/http/server/common/server/NettyChannelContextTest.java b/server/common/netty-server/src/test/java/org/netty/http/server/common/server/NettyChannelContextTest.java new file mode 100644 index 0000000000..d06b75d3aa --- /dev/null +++ b/server/common/netty-server/src/test/java/org/netty/http/server/common/server/NettyChannelContextTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.netty.http.server.common.server; + +import io.netty.channel.ChannelHandlerContext; +import org.junit.Test; +import org.kaaproject.kaa.server.common.server.NettyChannelContext; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class NettyChannelContextTest { + @Test + public void getSetTest() { + ChannelHandlerContext context = mock(ChannelHandlerContext.class); + NettyChannelContext nettyChannelContext = new NettyChannelContext(context); + Object o1 = new Object(); + nettyChannelContext.writeAndFlush(o1); + verify(context).writeAndFlush(o1); + Exception e = new Exception(); + nettyChannelContext.fireExceptionCaught(e); + verify(context).fireExceptionCaught(e); + Object o2 = new Object(); + nettyChannelContext.writeAndFlush(o2); + verify(context).writeAndFlush(o2); + nettyChannelContext.flush(); + verify(context).flush(); + } +} diff --git a/server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/EndpointConfigurationCassandraDaoTest.java b/server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/EndpointConfigurationCassandraDaoTest.java index aa0a158745..9406bdcb07 100644 --- a/server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/EndpointConfigurationCassandraDaoTest.java +++ b/server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/EndpointConfigurationCassandraDaoTest.java @@ -32,6 +32,20 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class EndpointConfigurationCassandraDaoTest extends AbstractCassandraTest { + @Test + public void testFindById() throws Exception { + List configs = generateConfiguration(3); + CassandraEndpointConfiguration expected = configs.get(0); + CassandraEndpointConfiguration found = endpointConfigurationDao.findById(expected.getConfigurationHash()); + Assert.assertEquals(expected, found); + } + + @Test + public void testFindByIdNullKey() throws Exception { + CassandraEndpointConfiguration found = endpointConfigurationDao.findById(null); + Assert.assertNull(found); + } + @Test public void testFindByHash() throws Exception { List configs = generateConfiguration(3); @@ -40,6 +54,15 @@ public void testFindByHash() throws Exception { Assert.assertEquals(expected, found); } + @Test + public void testRemoveByIdNullKey() throws Exception { + List configs = generateConfiguration(3); + CassandraEndpointConfiguration expected = configs.get(0); + endpointConfigurationDao.removeById(null); + CassandraEndpointConfiguration found = endpointConfigurationDao.findByHash(expected.getConfigurationHash().array()); + Assert.assertEquals(expected, found); + } + @Test public void testRemoveByHash() throws Exception { List configs = generateConfiguration(3); @@ -49,4 +72,12 @@ public void testRemoveByHash() throws Exception { Assert.assertNull(found); } -} \ No newline at end of file + @Test + public void testRemoveById() throws Exception { + List configs = generateConfiguration(3); + CassandraEndpointConfiguration expected = configs.get(0); + endpointConfigurationDao.removeById(expected.getConfigurationHash()); + CassandraEndpointConfiguration found = endpointConfigurationDao.findByHash(expected.getConfigurationHash().array()); + Assert.assertNull(found); + } +} diff --git a/server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/EndpointProfileCassandraDaoTest.java b/server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/EndpointProfileCassandraDaoTest.java index 2bf9140f93..7384b3e931 100644 --- a/server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/EndpointProfileCassandraDaoTest.java +++ b/server/common/nosql/cassandra-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/cassandra/dao/EndpointProfileCassandraDaoTest.java @@ -27,6 +27,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import java.nio.ByteBuffer; import java.util.Arrays; import java.util.List; @@ -65,8 +66,32 @@ public void testRemoveByKeyHash() throws Exception { } @Test - public void testRemoveByAppId() throws Exception { + public void testRemoveById() throws Exception { + EndpointProfileDto expected = generateEndpointProfile(null, null, null); + endpointProfileDao.removeById(ByteBuffer.wrap(expected.getEndpointKeyHash())); + EndpointProfile found = endpointProfileDao.findByKeyHash(expected.getEndpointKeyHash()); + Assert.assertNull(found); + } + + @Test + public void testRemoveByIdNullKey() throws Exception { + EndpointProfileDto expected = generateEndpointProfile(null, null, null); + EndpointProfile found = endpointProfileDao.findByKeyHash(expected.getEndpointKeyHash()); + Assert.assertNotNull(found); + } + @Test + public void testFindById() throws Exception { + EndpointProfileDto expected = generateEndpointProfile(null, null, null); + EndpointProfile found = endpointProfileDao.findById(ByteBuffer.wrap(expected.getEndpointKeyHash())); + Assert.assertEquals(expected, found.toDto()); + } + + @Test + public void testFindByIdNullKey() throws Exception { + EndpointProfileDto expected = generateEndpointProfile(null, null, null); + EndpointProfile found = endpointProfileDao.findById(null); + Assert.assertNull(found); } @Test @@ -84,4 +109,4 @@ public void testFindByEndpointUserId() throws Exception { Assert.assertFalse(found.isEmpty()); Assert.assertEquals(endpointProfileDto, found.get(0).toDto()); } -} \ No newline at end of file +} diff --git a/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/EndpointProfileTest.java b/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/EndpointProfileTest.java index 5c659b46f4..7c11a01438 100644 --- a/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/EndpointProfileTest.java +++ b/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/EndpointProfileTest.java @@ -19,6 +19,7 @@ import nl.jqno.equalsverifier.EqualsVerifier; import nl.jqno.equalsverifier.Warning; +import org.junit.Assert; import org.junit.Test; public class EndpointProfileTest { @@ -27,5 +28,63 @@ public class EndpointProfileTest { public void hashCodeEqualsTest(){ EqualsVerifier.forClass(MongoEndpointProfile.class).suppress(Warning.NONFINAL_FIELDS).verify(); } - + + @Test + public void getSetTest(){ + MongoEndpointProfile profile = new MongoEndpointProfile(); + + profile.setAccessToken(null); + profile.setCfGroupState(null); + profile.setChangedFlag(null); + profile.setConfigurationHash(null); + profile.setEcfVersionStates(null); + profile.setEndpointKey(null); + profile.setEndpointKeyHash(null); + profile.setEndpointUserId(null); + profile.setEcfVersionStates(null); + profile.setId(null); + profile.setNfGroupState(null); + profile.setNtHash(null); + profile.setProfile(null); + profile.setProfileHash(null); + profile.setServerHash(null); + profile.setSubscriptions(null); + profile.setUserConfigurationHash(null); + + profile.setCfSequenceNumber(1); + profile.setConfigurationVersion(1); + profile.setLogSchemaVersion(1); + profile.setNfSequenceNumber(1); + profile.setNotificationVersion(1); + profile.setProfileVersion(1); + profile.setSystemNfVersion(1); + profile.setUserNfVersion(1); + + Assert.assertNull(profile.getAccessToken()); + Assert.assertNull(profile.getCfGroupState()); + Assert.assertNull(profile.getChangedFlag()); + Assert.assertNull(profile.getConfigurationHash()); + Assert.assertNull(profile.getEcfVersionStates()); + Assert.assertNull(profile.getEndpointKey()); + Assert.assertNull(profile.getEndpointKeyHash()); + Assert.assertNull(profile.getEndpointUserId()); + Assert.assertNull(profile.getEcfVersionStates()); + Assert.assertNull(profile.getId()); + Assert.assertNull(profile.getNfGroupState()); + Assert.assertNull(profile.getNtHash()); + Assert.assertNull(profile.getProfile()); + Assert.assertNull(profile.getProfileHash()); + Assert.assertNull(profile.getServerHash()); + Assert.assertNull(profile.getSubscriptions()); + Assert.assertNull(profile.getUserConfigurationHash()); + + Assert.assertEquals(1,profile.getCfSequenceNumber()); + Assert.assertEquals(1,profile.getConfigurationVersion()); + Assert.assertEquals(1,profile.getLogSchemaVersion()); + Assert.assertEquals(1,profile.getNfSequenceNumber()); + Assert.assertEquals(1,profile.getNotificationVersion()); + Assert.assertEquals(1,profile.getProfileVersion()); + Assert.assertEquals(1,profile.getSystemNfVersion()); + Assert.assertEquals(1,profile.getUserNfVersion()); + } } diff --git a/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/MongoDaoUtilTest.java b/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/MongoDaoUtilTest.java new file mode 100644 index 0000000000..a313735f5f --- /dev/null +++ b/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/MongoDaoUtilTest.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.common.nosql.mongo.dao.model; + +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.common.dto.EndpointGroupStateDto; +import org.kaaproject.kaa.common.dto.NotificationDto; + +import java.util.Collections; +import java.util.List; + +public class MongoDaoUtilTest { + + @Test + public void convertToModelListNullArgsListTest() { + List list = MongoDaoUtil.convertDtoToModelList(null); + Assert.assertNull(list); + } + + @Test + public void convertToModelListEmptyArgsListTest() { + List list = MongoDaoUtil.convertDtoToModelList(Collections.emptyList()); + Assert.assertNull(list); + } + + @Test + public void convertToModelListNullListTest(){ + Assert.assertNull(MongoDaoUtil.convertToModelList(null)); + } + + @Test + public void convertToModelListEmptyListTest(){ + Assert.assertNull(MongoDaoUtil.convertToModelList(Collections.emptyList())); + } + +} diff --git a/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/MongoEndpointUserConfigurationTest.java b/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/MongoEndpointUserConfigurationTest.java new file mode 100644 index 0000000000..b06beefedf --- /dev/null +++ b/server/common/nosql/mongo-dao/src/test/java/org/kaaproject/kaa/server/common/nosql/mongo/dao/model/MongoEndpointUserConfigurationTest.java @@ -0,0 +1,46 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.common.nosql.mongo.dao.model; + +import nl.jqno.equalsverifier.EqualsVerifier; +import nl.jqno.equalsverifier.Warning; +import org.junit.Assert; +import org.junit.Test; + +public class MongoEndpointUserConfigurationTest { + @Test + public void hashCodeEqualsTest() { + EqualsVerifier.forClass(MongoEndpointConfiguration.class).suppress(Warning.NONFINAL_FIELDS).verify(); + } + + @Test + public void getSetTest() { + MongoEndpointUserConfiguration mongoEndpointUserConfiguration = new MongoEndpointUserConfiguration(); + String appToken = "appToken"; + String body = "body"; + int schemaVersion = 2; + String userId = "userId"; + mongoEndpointUserConfiguration.setAppToken(appToken); + mongoEndpointUserConfiguration.setBody(body); + mongoEndpointUserConfiguration.setSchemaVersion(schemaVersion); + mongoEndpointUserConfiguration.setUserId(userId); + Assert.assertEquals(appToken, mongoEndpointUserConfiguration.getAppToken()); + Assert.assertEquals(body, mongoEndpointUserConfiguration.getBody()); + Assert.assertTrue(schemaVersion == mongoEndpointUserConfiguration.getSchemaVersion()); + Assert.assertEquals(userId, mongoEndpointUserConfiguration.getUserId()); + } +} diff --git a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/ClientSyncTest.java b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/ClientSyncTest.java index 284b4ef824..6ec1cdc497 100644 --- a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/ClientSyncTest.java +++ b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/ClientSyncTest.java @@ -24,6 +24,7 @@ import static org.mockito.Mockito.when; public class ClientSyncTest { + @Test public void isValidProfileHashExistsTest() { ClientSyncMetaData clientSyncMetaData = mock(ClientSyncMetaData.class); @@ -47,5 +48,6 @@ public void isValidProfileHashNullEndpointKeyNullTest() { when(clientSyncMetaData.getProfileHash()).thenReturn(null); ClientSync clientSync = new ClientSync(0, clientSyncMetaData, profileClientSync, null, null, null, null, null); Assert.assertEquals(clientSync.isValid(), false); + Assert.assertNotNull(new ClientSyncMetaData().toString()); } } diff --git a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/EventSequenceNumberResponseTest.java b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/EventSequenceNumberResponseTest.java new file mode 100644 index 0000000000..866b0dd4a8 --- /dev/null +++ b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/EventSequenceNumberResponseTest.java @@ -0,0 +1,32 @@ +/* + * Copyright 2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.sync; + +import org.junit.Assert; +import org.junit.Test; + +public class EventSequenceNumberResponseTest { + + @Test + public void eventSequenceNumberResponseTest() { + EventSequenceNumberResponse sequenceNumberResponse = new EventSequenceNumberResponse(); + Integer num = 1; + sequenceNumberResponse.setSeqNum(num); + Assert.assertEquals(num, sequenceNumberResponse.getSeqNum()); + Assert.assertNotNull(sequenceNumberResponse.toString()); + } +} diff --git a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/ProfileServerSyncTest.java b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/ProfileServerSyncTest.java new file mode 100644 index 0000000000..6d13807946 --- /dev/null +++ b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/ProfileServerSyncTest.java @@ -0,0 +1,31 @@ +/* + * Copyright 2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.sync; + +import org.junit.Assert; +import org.junit.Test; + +public class ProfileServerSyncTest { + + @Test + public void profileServerSyncTest(){ + SyncResponseStatus status = SyncResponseStatus.DELTA; + ProfileServerSync serverSync = new ProfileServerSync(); + serverSync.setResponseStatus(status); + Assert.assertEquals(status, serverSync.getResponseStatus()); + } +} diff --git a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/SyncEqualsHashCodeTest.java b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/SyncEqualsHashCodeTest.java index 2c8a642fb9..08ca4fff69 100644 --- a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/SyncEqualsHashCodeTest.java +++ b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/SyncEqualsHashCodeTest.java @@ -47,6 +47,9 @@ public void clientSyncMetaDataEqualsHashCodeTest() { Assert.assertNotEquals(null, clientSyncMetaData1); Assert.assertEquals(clientSyncMetaData1, clientSyncMetaData2); Assert.assertNotEquals(clientSyncMetaData1, new Object()); + Assert.assertEquals(clientSyncMetaData1.hashCode(), clientSyncMetaData2.hashCode()); + Assert.assertEquals(clientSyncMetaData1.hashCode(), clientSyncMetaData1.hashCode()); + Assert.assertNotEquals(clientSyncMetaData1.hashCode(), clientSyncMetaData3.hashCode()); } @Test @@ -130,10 +133,14 @@ public void profileClientSyncEqualsHashCodeTest() { ProfileClientSync profileClientSync2 = new ProfileClientSync(null, null, null, "token1"); ProfileClientSync profileClientSync3 = new ProfileClientSync(null, null, null, "token3"); Assert.assertEquals(profileClientSync1, profileClientSync1); - Assert.assertNotEquals(profileClientSync1, null); Assert.assertEquals(profileClientSync1, profileClientSync2); + Assert.assertNotEquals(profileClientSync1, null); + Assert.assertNotEquals(null, profileClientSync1); Assert.assertNotEquals(profileClientSync1, profileClientSync3); Assert.assertNotEquals(profileClientSync1, new Object()); + Assert.assertEquals(profileClientSync1.hashCode(), profileClientSync2.hashCode()); + Assert.assertEquals(profileClientSync1.hashCode(), profileClientSync1.hashCode()); + Assert.assertNotEquals(profileClientSync1.hashCode(), profileClientSync3.hashCode()); } @Test diff --git a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/bootstrap/ProtocolConnectionDataTest.java b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/bootstrap/ProtocolConnectionDataTest.java new file mode 100644 index 0000000000..33d9ddc131 --- /dev/null +++ b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/bootstrap/ProtocolConnectionDataTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.sync.bootstrap; + +import org.junit.Assert; +import org.junit.Test; + +public class ProtocolConnectionDataTest { + + @Test + public void protocolConnectionDataTest() { + int accessPointId = 1; + int protocolId = 1; + int protocolVersion = 1; + ProtocolVersionId protocolVersionId = new ProtocolVersionId(protocolId, protocolVersion); + byte[] connectionData = new byte[10]; + ProtocolConnectionData protocolConnectionData = new ProtocolConnectionData(accessPointId, protocolVersionId, connectionData); + Assert.assertEquals(accessPointId, protocolConnectionData.getAccessPointId()); + Assert.assertEquals(connectionData, protocolConnectionData.getConnectionData()); + Assert.assertEquals(protocolId, protocolConnectionData.getProtocolId()); + Assert.assertEquals(protocolVersion, protocolConnectionData.getProtocolVersion()); + Assert.assertNotNull(protocolConnectionData.toString()); + } +} diff --git a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/platform/AvroEncDecTest.java b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/platform/AvroEncDecTest.java new file mode 100644 index 0000000000..2e83168a3b --- /dev/null +++ b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/sync/platform/AvroEncDecTest.java @@ -0,0 +1,382 @@ +/* + * Copyright 2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.sync.platform; + +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.common.Constants; +import org.kaaproject.kaa.common.endpoint.gen.BootstrapSyncRequest; +import org.kaaproject.kaa.common.endpoint.gen.ConfigurationSyncRequest; +import org.kaaproject.kaa.common.endpoint.gen.EventSyncRequest; +import org.kaaproject.kaa.common.endpoint.gen.LogDeliveryErrorCode; +import org.kaaproject.kaa.common.endpoint.gen.LogSyncRequest; +import org.kaaproject.kaa.common.endpoint.gen.NotificationSyncRequest; +import org.kaaproject.kaa.common.endpoint.gen.NotificationType; +import org.kaaproject.kaa.common.endpoint.gen.ProfileSyncRequest; +import org.kaaproject.kaa.common.endpoint.gen.SyncRequest; +import org.kaaproject.kaa.common.endpoint.gen.SyncRequestMetaData; +import org.kaaproject.kaa.common.endpoint.gen.SyncResponse; +import org.kaaproject.kaa.common.endpoint.gen.SyncResponseResultType; +import org.kaaproject.kaa.common.endpoint.gen.SyncResponseStatus; +import org.kaaproject.kaa.common.endpoint.gen.UserAttachErrorCode; +import org.kaaproject.kaa.common.endpoint.gen.UserAttachResponse; +import org.kaaproject.kaa.common.endpoint.gen.UserSyncRequest; +import org.kaaproject.kaa.server.sync.ClientSync; +import org.kaaproject.kaa.server.sync.ConfigurationServerSync; +import org.kaaproject.kaa.server.sync.Event; +import org.kaaproject.kaa.server.sync.EventServerSync; +import org.kaaproject.kaa.server.sync.LogDeliveryStatus; +import org.kaaproject.kaa.server.sync.LogServerSync; +import org.kaaproject.kaa.server.sync.NotificationServerSync; +import org.kaaproject.kaa.server.sync.ProfileServerSync; +import org.kaaproject.kaa.server.sync.RedirectServerSync; +import org.kaaproject.kaa.server.sync.ServerSync; +import org.kaaproject.kaa.server.sync.SyncStatus; +import org.kaaproject.kaa.server.sync.UserServerSync; +import org.kaaproject.kaa.server.sync.UserVerifierErrorCode; +import org.kaaproject.kaa.server.sync.bootstrap.BootstrapServerSync; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +public class AvroEncDecTest { + + private static final String CONVER_METHOD = "convert"; + + @Test + public void encodeTest() throws PlatformEncDecException { + AvroEncDec encDec = new AvroEncDec(); + Assert.assertNull(encDec.encode(null)); + } + + @Test + public void getIdTest() { + Assert.assertEquals(Constants.KAA_PLATFORM_PROTOCOL_AVRO_ID, new AvroEncDec().getId()); + } + + @Test + public void convertSyncRequestTest() { + ClientSync clientSync = new ClientSync(); + Assert.assertEquals(clientSync, AvroEncDec.convert(new SyncRequest())); + } + + @Test + public void convertServerSyncTest() { + SyncResponse syncResponse = new SyncResponse(); + Assert.assertEquals(syncResponse, AvroEncDec.convert(new ServerSync())); + } + + @Test + public void convertNullTest() { + Event event = null; + Assert.assertNull(AvroEncDec.convert(event)); + } + + @Test + public void convertEventTest() { + Event event = new Event(); + org.kaaproject.kaa.common.endpoint.gen.Event genEvent = new org.kaaproject.kaa.common.endpoint.gen.Event(event.getSeqNum(), event.getEventClassFQN(), event.getEventData(), event.getSource(), event.getTarget()); + org.kaaproject.kaa.common.endpoint.gen.Event nullGenEvent = null; + Assert.assertEquals(event, AvroEncDec.convert(genEvent)); + Assert.assertNull(AvroEncDec.convert(nullGenEvent)); + } + + @Test(expected = PlatformEncDecException.class) + public void decodeNullSourceTest() throws PlatformEncDecException { + AvroEncDec encDec = new AvroEncDec(); + byte[] bytes = new byte[0]; + Assert.assertNull(encDec.decode(bytes)); + } + + @Test + public void convertSyncStatusTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, SyncStatus.class); + method.setAccessible(true); + SyncStatus syncStatus = null; + Assert.assertNull(method.invoke(avroEncDec, syncStatus)); + Assert.assertEquals(SyncResponseResultType.SUCCESS, method.invoke(avroEncDec, SyncStatus.SUCCESS)); + Assert.assertEquals(SyncResponseResultType.FAILURE, method.invoke(avroEncDec, SyncStatus.FAILURE)); + Assert.assertEquals(SyncResponseResultType.PROFILE_RESYNC, method.invoke(avroEncDec, SyncStatus.PROFILE_RESYNC)); + Assert.assertEquals(SyncResponseResultType.REDIRECT, method.invoke(avroEncDec, SyncStatus.REDIRECT)); + } + + + @Test + public void convertBootstrapServerSyncTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, BootstrapServerSync.class); + method.setAccessible(true); + BootstrapServerSync serverSync = null; + Assert.assertNull(method.invoke(avroEncDec, serverSync)); + BootstrapServerSync bootstrapServerSync = new BootstrapServerSync(1, Collections.EMPTY_SET); + method.invoke(avroEncDec, bootstrapServerSync); + } + + + @Test + public void convertProtocolConnectionDataSetTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, Set.class); + method.setAccessible(true); + Set set = null; + Assert.assertEquals(Collections.emptyList(), method.invoke(avroEncDec, set)); + method.invoke(avroEncDec, new HashSet<>()); + } + + @Test + public void convertRedirectServerSyncTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, RedirectServerSync.class); + method.setAccessible(true); + RedirectServerSync serverSync = null; + Assert.assertNull(method.invoke(avroEncDec, serverSync)); + method.invoke(avroEncDec, new RedirectServerSync()); + } + + @Test + public void convertProfileServerSyncTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, ProfileServerSync.class); + method.setAccessible(true); + ProfileServerSync serverSync = null; + Assert.assertNull(method.invoke(avroEncDec, serverSync)); + method.invoke(avroEncDec, new ProfileServerSync()); + } + + @Test + public void convertSyncResponseStatusTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, org.kaaproject.kaa.server.sync.SyncResponseStatus.class); + method.setAccessible(true); + org.kaaproject.kaa.server.sync.SyncResponseStatus responseStatus = null; + Assert.assertNull(method.invoke(avroEncDec, responseStatus)); + Assert.assertEquals(SyncResponseStatus.DELTA, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.SyncResponseStatus.DELTA)); + Assert.assertEquals(SyncResponseStatus.NO_DELTA, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.SyncResponseStatus.NO_DELTA)); + Assert.assertEquals(SyncResponseStatus.RESYNC, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.SyncResponseStatus.RESYNC)); + } + + @Test + public void convertConfigurationServerSyncTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, ConfigurationServerSync.class); + method.setAccessible(true); + ConfigurationServerSync serverSync = null; + Assert.assertNull(method.invoke(avroEncDec, serverSync)); + method.invoke(avroEncDec, new ConfigurationServerSync()); + } + + @Test + public void convertNotificationServerSyncTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, NotificationServerSync.class); + method.setAccessible(true); + NotificationServerSync serverSync = null; + Assert.assertNull(method.invoke(avroEncDec, serverSync)); + method.invoke(avroEncDec, new NotificationServerSync()); + } + + @Test + public void convertEventServerSyncTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, EventServerSync.class); + method.setAccessible(true); + EventServerSync serverSync = null; + Assert.assertNull(method.invoke(avroEncDec, serverSync)); + method.invoke(avroEncDec, new EventServerSync()); + } + + @Test + public void convertUserServerSyncTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, UserServerSync.class); + method.setAccessible(true); + UserServerSync serverSync = null; + Assert.assertNull(method.invoke(avroEncDec, serverSync)); + method.invoke(avroEncDec, new UserServerSync()); + } + + @Test + public void convertUserVerifierErrorCodeTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, UserVerifierErrorCode.class); + method.setAccessible(true); + UserVerifierErrorCode errorCode = null; + Assert.assertNull(method.invoke(avroEncDec, errorCode)); + Assert.assertEquals(UserAttachErrorCode.CONNECTION_ERROR, method.invoke(avroEncDec, UserVerifierErrorCode.CONNECTION_ERROR)); + Assert.assertEquals(UserAttachErrorCode.INTERNAL_ERROR, method.invoke(avroEncDec, UserVerifierErrorCode.INTERNAL_ERROR)); + Assert.assertEquals(UserAttachErrorCode.NO_VERIFIER_CONFIGURED, method.invoke(avroEncDec, UserVerifierErrorCode.NO_VERIFIER_CONFIGURED)); + Assert.assertEquals(UserAttachErrorCode.REMOTE_ERROR, method.invoke(avroEncDec, UserVerifierErrorCode.REMOTE_ERROR)); + Assert.assertEquals(UserAttachErrorCode.TOKEN_EXPIRED, method.invoke(avroEncDec, UserVerifierErrorCode.TOKEN_EXPIRED)); + Assert.assertEquals(UserAttachErrorCode.TOKEN_INVALID, method.invoke(avroEncDec, UserVerifierErrorCode.TOKEN_INVALID)); + } + + + @Test + public void convertNotificationTypeTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, org.kaaproject.kaa.server.sync.NotificationType.class); + method.setAccessible(true); + org.kaaproject.kaa.server.sync.NotificationType notificationType = null; + Assert.assertNull(method.invoke(avroEncDec, notificationType)); + Assert.assertEquals(NotificationType.CUSTOM, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.NotificationType.CUSTOM)); + Assert.assertEquals(NotificationType.SYSTEM, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.NotificationType.SYSTEM)); + } + + @Test + public void convertUserAttachResponseTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, org.kaaproject.kaa.server.sync.UserAttachResponse.class); + method.setAccessible(true); + org.kaaproject.kaa.server.sync.UserAttachResponse failure = new org.kaaproject.kaa.server.sync.UserAttachResponse(SyncStatus.FAILURE, null, null); + Assert.assertEquals(new UserAttachResponse(SyncResponseResultType.FAILURE, null, null), method.invoke(avroEncDec, failure)); + org.kaaproject.kaa.server.sync.UserAttachResponse success = new org.kaaproject.kaa.server.sync.UserAttachResponse(SyncStatus.SUCCESS, null, null); + Assert.assertEquals(new UserAttachResponse(SyncResponseResultType.SUCCESS, null, null), method.invoke(avroEncDec, success)); + + } + + @Test + public void convertLogServerSyncTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, LogServerSync.class); + method.setAccessible(true); + LogServerSync serverSync = null; + Assert.assertNull(method.invoke(avroEncDec, serverSync)); + method.invoke(avroEncDec, new LogServerSync()); + } + + @Test + public void convertLogDeliveryStatusTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, LogDeliveryStatus.class); + method.setAccessible(true); + LogDeliveryStatus deliveryStatus = null; + Assert.assertNull(method.invoke(avroEncDec, deliveryStatus)); + method.invoke(avroEncDec, new LogDeliveryStatus(1, SyncStatus.SUCCESS, null)); + } + + @Test + public void convertLogDeliveryErrorCodeTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, org.kaaproject.kaa.server.sync.LogDeliveryErrorCode.class); + method.setAccessible(true); + org.kaaproject.kaa.server.sync.LogDeliveryErrorCode deliveryErrorCode = null; + Assert.assertNull(method.invoke(avroEncDec, deliveryErrorCode)); + Assert.assertEquals(LogDeliveryErrorCode.NO_APPENDERS_CONFIGURED, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.LogDeliveryErrorCode.NO_APPENDERS_CONFIGURED)); + Assert.assertEquals(LogDeliveryErrorCode.APPENDER_INTERNAL_ERROR, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.LogDeliveryErrorCode.APPENDER_INTERNAL_ERROR)); + Assert.assertEquals(LogDeliveryErrorCode.REMOTE_CONNECTION_ERROR, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.LogDeliveryErrorCode.REMOTE_CONNECTION_ERROR)); + Assert.assertEquals(LogDeliveryErrorCode.REMOTE_INTERNAL_ERROR, method.invoke(avroEncDec, org.kaaproject.kaa.server.sync.LogDeliveryErrorCode.REMOTE_INTERNAL_ERROR)); + } + + @Test + public void convertSyncRequestMetaDataTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, SyncRequestMetaData.class); + method.setAccessible(true); + SyncRequestMetaData requestMetaData = null; + Assert.assertNull(method.invoke(avroEncDec, requestMetaData)); + method.invoke(avroEncDec, new SyncRequestMetaData()); + } + + @Test + public void convertBootstrapSyncRequestTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, BootstrapSyncRequest.class); + method.setAccessible(true); + BootstrapSyncRequest syncRequest = null; + Assert.assertNull(method.invoke(avroEncDec, syncRequest)); + method.invoke(avroEncDec, new BootstrapSyncRequest()); + } + + @Test + public void convertProtocolVersionPairListTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, List.class); + method.setAccessible(true); + List list = null; + Assert.assertEquals(Collections.emptyList(), method.invoke(avroEncDec, list)); + method.invoke(avroEncDec, new LinkedList<>()); + } + + @Test + public void convertProfileSyncRequestTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, ProfileSyncRequest.class); + method.setAccessible(true); + ProfileSyncRequest syncRequest = null; + Assert.assertNull(method.invoke(avroEncDec, syncRequest)); + method.invoke(avroEncDec, new ProfileSyncRequest()); + } + + @Test + public void convertConfigurationSyncRequestTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, ConfigurationSyncRequest.class); + method.setAccessible(true); + ConfigurationSyncRequest syncRequest = null; + Assert.assertNull(method.invoke(avroEncDec, syncRequest)); + method.invoke(avroEncDec, new ConfigurationSyncRequest()); + } + + + @Test + public void convertNotificationSyncRequestTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, NotificationSyncRequest.class); + method.setAccessible(true); + NotificationSyncRequest syncRequest = null; + Assert.assertNull(method.invoke(avroEncDec, syncRequest)); + method.invoke(avroEncDec, new NotificationSyncRequest()); + } + + @Test + public void convertEventSyncRequestTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, EventSyncRequest.class); + method.setAccessible(true); + EventSyncRequest syncRequest = null; + Assert.assertNull(method.invoke(avroEncDec, syncRequest)); + method.invoke(avroEncDec, new EventSyncRequest()); + } + + @Test + public void convertLogSyncRequestTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, LogSyncRequest.class); + method.setAccessible(true); + LogSyncRequest syncRequest = null; + Assert.assertNull(method.invoke(avroEncDec, syncRequest)); + method.invoke(avroEncDec, new LogSyncRequest()); + } + + @Test + public void convertUserSyncRequestTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + AvroEncDec avroEncDec = new AvroEncDec(); + Method method = AvroEncDec.class.getDeclaredMethod(CONVER_METHOD, UserSyncRequest.class); + method.setAccessible(true); + UserSyncRequest syncRequest = null; + Assert.assertNull(method.invoke(avroEncDec, syncRequest)); + method.invoke(avroEncDec, new UserSyncRequest()); + } + + +} diff --git a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/thrift/NeighborConnectionTest.java b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/thrift/NeighborConnectionTest.java new file mode 100644 index 0000000000..5b49a1f740 --- /dev/null +++ b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/thrift/NeighborConnectionTest.java @@ -0,0 +1,95 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.thrift; + +import org.apache.thrift.TException; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.kaaproject.kaa.server.common.thrift.gen.operations.OperationsThriftService; +import org.kaaproject.kaa.server.common.zk.gen.ConnectionInfo; +import org.kaaproject.kaa.server.sync.Event; +import org.springframework.test.util.ReflectionTestUtils; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.ExecutorService; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyList; +import static org.mockito.Mockito.*; + +public class NeighborConnectionTest { + private NeighborConnection, Event> neighborConnection; + private NeighborTemplate template = (NeighborTemplate) mock(NeighborTemplate.class); + + @Before + public void before() throws InterruptedException { + ConnectionInfo connectionInfo = new ConnectionInfo("thriftHost", 10101, ByteBuffer.allocate(10)); + neighborConnection = new NeighborConnection<>(connectionInfo, 1, template); + } + + @SuppressWarnings("unchecked") + @Test + public void startTest() throws TException, InterruptedException { + neighborConnection.start(); + ExecutorService executorSpy = getSpyOnExecutorAndInjectIt(); + neighborConnection.sendMessages(Collections.singleton(new Event())); + verify(template, timeout(1000)).process(any(OperationsThriftService.Iface.class), anyList()); + neighborConnection.shutdown(); + verify(executorSpy, timeout(1000)).shutdown(); + } + + @Test + public void startTExceptionThrownTest() throws InterruptedException, TException { + TException tException = new TException(); + doThrow(tException).when(template).process(any(OperationsThriftService.Iface.class), anyList()); + neighborConnection.start(); + ExecutorService executorSpy = getSpyOnExecutorAndInjectIt(); + neighborConnection.sendMessages(Arrays.asList(new Event())); + verify(template, timeout(1000)).onServerError(anyString(), eq(tException)); + neighborConnection.shutdown(); + verify(executorSpy, timeout(1000)).shutdown(); + } + + private ExecutorService getSpyOnExecutorAndInjectIt() { + ExecutorService executorSpy = spy((ExecutorService) ReflectionTestUtils.getField(neighborConnection, "executor")); + ReflectionTestUtils.setField(neighborConnection, "executor", executorSpy); + return executorSpy; + } + + @Test + public void equalsHashCodeTest() { + ConnectionInfo connectionInfo1 = new ConnectionInfo("thriftHost1", 9991, null); + ConnectionInfo connectionInfo2 = new ConnectionInfo("thriftHost1", 9991, null); + ConnectionInfo connectionInfo3 = new ConnectionInfo("thriftHost1", 9993, null); + + NeighborConnection, Event> neighborConnection1 = new NeighborConnection<>(connectionInfo1, 10, null); + NeighborConnection, Event> neighborConnection2 = new NeighborConnection<>(connectionInfo2, 8, null); + NeighborConnection, Event> neighborConnection3 = new NeighborConnection<>(connectionInfo3, 7, null); + + Assert.assertEquals(neighborConnection1.hashCode(), neighborConnection2.hashCode()); + Assert.assertNotEquals(neighborConnection1.hashCode(), neighborConnection3.hashCode()); + + Assert.assertEquals(neighborConnection1, neighborConnection1); + Assert.assertNotEquals(neighborConnection1, null); + Assert.assertNotEquals(neighborConnection1, new Object()); + Assert.assertEquals(neighborConnection1, neighborConnection2); + Assert.assertNotEquals(neighborConnection1, neighborConnection3); + } +} diff --git a/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/thrift/NeighborsTest.java b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/thrift/NeighborsTest.java new file mode 100644 index 0000000000..3ee712c9a1 --- /dev/null +++ b/server/common/server-shared/src/test/java/org/kaaproject/kaa/server/thrift/NeighborsTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.thrift; + +import org.junit.Test; +import org.kaaproject.kaa.server.common.zk.gen.ConnectionInfo; +import org.kaaproject.kaa.server.sync.Event; +import org.springframework.test.util.ReflectionTestUtils; + +import java.lang.reflect.InvocationTargetException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.*; + +public class NeighborsTest { + @SuppressWarnings("unchecked") + @Test + public void sendMessageTest() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InterruptedException { + ConnectionInfo connectionInfo1 = new ConnectionInfo("thriftHost", 9999, ByteBuffer.allocate(10)); + NeighborTemplate template = (NeighborTemplate) mock(NeighborTemplate.class); + Neighbors, Event> neighbors = new Neighbors<>(template, 1); + ReflectionTestUtils.setField(neighbors, "zkId", "someZkId"); + NeighborConnection, Event> neighborConnection = new NeighborConnection<>(connectionInfo1, 1, null); + LinkedBlockingQueue eventQueue = spy(new LinkedBlockingQueue()); + ReflectionTestUtils.setField(neighborConnection, "messageQueue", eventQueue); + ConcurrentMap, Event>> neighborMap = + spy((ConcurrentMap, Event>>) ReflectionTestUtils.getField(neighbors, "neigbors")); + ReflectionTestUtils.setField(neighbors, "neigbors", neighborMap); + when(neighborMap.get(anyString())).thenReturn(neighborConnection); + Collection messages = new ArrayList<>(); + Event e = new Event(10, "FQN", null, null, null); + messages.add(e); + Collection messagesSpy = spy(messages); + neighbors.sendMessages(connectionInfo1, messagesSpy); + verify(messagesSpy, timeout(1000)).iterator(); + verify(eventQueue, timeout(1000)).offer(eq(e), anyLong(), any(TimeUnit.class)); + neighbors.shutdown(); + } +} diff --git a/server/common/transport-shared/src/test/java/org/kaaproject/kaa/server/transport/session/SessionInfoTest.java b/server/common/transport-shared/src/test/java/org/kaaproject/kaa/server/transport/session/SessionInfoTest.java index c75eeecb26..4133c7e5fa 100644 --- a/server/common/transport-shared/src/test/java/org/kaaproject/kaa/server/transport/session/SessionInfoTest.java +++ b/server/common/transport-shared/src/test/java/org/kaaproject/kaa/server/transport/session/SessionInfoTest.java @@ -20,16 +20,23 @@ import org.junit.Assert; import org.junit.Test; import org.kaaproject.kaa.common.Constants; +import org.kaaproject.kaa.common.endpoint.security.MessageEncoderDecoder; +import org.kaaproject.kaa.common.hash.EndpointObjectHash; +import org.kaaproject.kaa.server.transport.channel.ChannelContext; +import org.kaaproject.kaa.server.transport.channel.ChannelType; import org.kaaproject.kaa.server.transport.session.SessionInfo; +import static org.mockito.Matchers.endsWith; +import static org.mockito.Mockito.mock; + /** - * + * * @author Andrew Shvayka * */ public class SessionInfoTest { @Test - public void equalsHashCode() { + public void equalsHashCodeTest() { UUID uuid1 = UUID.randomUUID(); UUID uuid2 = UUID.randomUUID(); SessionInfo info1 = new SessionInfo(uuid1, Constants.KAA_PLATFORM_PROTOCOL_AVRO_ID, null, null, null, null, null, null, 0, false); @@ -45,4 +52,29 @@ public void equalsHashCode() { Assert.assertNotEquals(info1, new Object()); Assert.assertNotEquals(info4, info1); } + + @Test + public void getSetTest() { + UUID uuid = UUID.randomUUID(); + int platformId = 1; + ChannelContext channelContext = mock(ChannelContext.class); + ChannelType channelType = ChannelType.ASYNC; + MessageEncoderDecoder.CipherPair cipherPair = mock(MessageEncoderDecoder.CipherPair.class); + EndpointObjectHash objectHash = EndpointObjectHash.fromString("Some str"); + String appToken = "12423521"; + String sdkToken ="85121532"; + int keepAlive = 100; + boolean isEncrypted = true; + SessionInfo info = new SessionInfo(uuid, platformId, channelContext, channelType, cipherPair, objectHash, appToken, sdkToken, keepAlive, isEncrypted); + Assert.assertEquals(uuid, info.getUuid()); + Assert.assertEquals(platformId, info.getPlatformId()); + Assert.assertEquals(channelContext, info.getCtx()); + Assert.assertEquals(channelType, info.getChannelType()); + Assert.assertEquals(cipherPair, info.getCipherPair()); + Assert.assertEquals(objectHash, info.getKey()); + Assert.assertEquals(appToken, info.getApplicationToken()); + Assert.assertEquals(keepAlive, info.getKeepAlive()); + Assert.assertEquals(isEncrypted, info.isEncrypted()); + Assert.assertNotNull(info.toString()); + } } diff --git a/server/operations/src/main/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/endpoint/EndpointStopMessage.java b/server/operations/src/main/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/endpoint/EndpointStopMessage.java index 623392a3d5..a26ab63144 100644 --- a/server/operations/src/main/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/endpoint/EndpointStopMessage.java +++ b/server/operations/src/main/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/endpoint/EndpointStopMessage.java @@ -20,7 +20,7 @@ import akka.actor.ActorRef; -public class EndpointStopMessage{ +public class EndpointStopMessage { private final EndpointObjectHash endpointKey; private final String actorKey; private final ActorRef originator; diff --git a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/user/EndpointUserConfigurationUpdateTest.java b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/user/EndpointUserConfigurationUpdateTest.java new file mode 100644 index 0000000000..5f20e0edd5 --- /dev/null +++ b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/user/EndpointUserConfigurationUpdateTest.java @@ -0,0 +1,59 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.operations.service.akka.actors.core.user; + + +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.common.hash.EndpointObjectHash; +import org.kaaproject.kaa.server.operations.service.akka.messages.core.user.EndpointUserConfigurationUpdate; + +import java.util.Arrays; + +public class EndpointUserConfigurationUpdateTest { + + @Test + public void testEndpointUserConfigurationUpdate() { + String tenantId = "tid"; + String userId = "uid"; + String applicationToken = "token"; + byte[] hash = "hash".getBytes(); + EndpointObjectHash key = EndpointObjectHash.fromBytes(hash); + + StringBuilder builder = new StringBuilder(); + builder.append("EndpointUserConfigurationUpdate [tenantId="); + builder.append(tenantId); + builder.append(", userId="); + builder.append(userId); + builder.append(", applicationToken="); + builder.append(applicationToken); + builder.append(", key="); + builder.append(key); + builder.append(", hash="); + builder.append(Arrays.toString(hash)); + builder.append("]"); + + EndpointUserConfigurationUpdate update = new EndpointUserConfigurationUpdate(tenantId, userId, applicationToken, key, hash); + + Assert.assertEquals(tenantId, update.getTenantId()); + Assert.assertEquals(userId, update.getUserId()); + Assert.assertEquals(applicationToken, update.getApplicationToken()); + Assert.assertEquals(hash, update.getHash()); + Assert.assertEquals(key, update.getKey()); + Assert.assertEquals(builder.toString(), update.toString()); + } +} diff --git a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/logs/CallbacksTest.java b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/logs/CallbacksTest.java new file mode 100644 index 0000000000..995e04a9ac --- /dev/null +++ b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/logs/CallbacksTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.operations.service.akka.messages.core.logs; + +import akka.actor.ActorRef; +import akka.actor.ActorSystem; +import akka.actor.Props; +import akka.actor.UntypedActor; +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.server.common.log.shared.appender.LogDeliveryErrorCode; + +public class CallbacksTest { + + @Test + public void multiLogDeliveryCallbackTest() { + MultiLogDeliveryCallback callback; + ActorSystem system = ActorSystem.create("actorSystem"); + ActorRef actorRef = system.actorOf(Props.create(TestActor.class)); + callback = new MultiLogDeliveryCallback(actorRef, 1, 1); + Assert.assertNotNull(callback); + callback.onSuccess(); + callback = new MultiLogDeliveryCallback(actorRef, 1, 3); + callback.onSuccess(); + callback.sendSuccessToEndpoint(); + callback.sendFailureToEndpoint(LogDeliveryErrorCode.APPENDER_INTERNAL_ERROR); + callback.onInternalError(); + callback.onRemoteError(); + callback.onConnectionError(); + } + + @Test + public void singleLogDeliveryCallbackTest() { + SingleLogDeliveryCallback callback; + ActorSystem system = ActorSystem.create("actorSystem"); + ActorRef actorRef = system.actorOf(Props.create(TestActor.class)); + callback = new SingleLogDeliveryCallback(actorRef, 1); + Assert.assertNotNull(callback); + } + + private static class TestActor extends UntypedActor { + @Override + public void onReceive(Object arg0) throws Exception { + unhandled(arg0); + } + } + +} diff --git a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/messages/io/NettySessionResponseMessageTest.java b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/messages/io/NettySessionResponseMessageTest.java new file mode 100644 index 0000000000..4a4b4c0d61 --- /dev/null +++ b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/messages/io/NettySessionResponseMessageTest.java @@ -0,0 +1,49 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.operations.service.akka.messages.io; + +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.server.common.server.NettyChannelContext; +import org.kaaproject.kaa.server.operations.service.akka.messages.io.response.NettySessionResponseMessage; +import org.kaaproject.kaa.server.transport.channel.ChannelContext; +import org.kaaproject.kaa.server.transport.channel.ChannelType; +import org.kaaproject.kaa.server.transport.message.ErrorBuilder; +import org.kaaproject.kaa.server.transport.session.SessionInfo; + +import java.util.UUID; + +public class NettySessionResponseMessageTest { + + @Test + public void testNettySessionResponseMessage() { + UUID uuid = UUID.randomUUID(); + ChannelContext channelContext = new NettyChannelContext(null); + ErrorBuilder errorBuilder = new ErrorBuilder() { + @Override + public Object[] build(Exception e) { + return new Object[0]; + } + }; + SessionInfo sessionInfo = new SessionInfo(uuid, 1, channelContext, ChannelType.SYNC, null, null, null, null, 1, true); + NettySessionResponseMessage responseMessage = new NettySessionResponseMessage(sessionInfo, null, null, null, errorBuilder); + Assert.assertEquals(uuid, responseMessage.getChannelUuid()); + Assert.assertEquals(errorBuilder, responseMessage.getErrorBuilder()); + Assert.assertEquals(ChannelType.SYNC, responseMessage.getChannelType()); + Assert.assertEquals(channelContext, responseMessage.getChannelContext()); + } +} diff --git a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/utils/EntityConvertUtilsTest.java b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/utils/EntityConvertUtilsTest.java index ec0b70d880..4ce28eefdb 100644 --- a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/utils/EntityConvertUtilsTest.java +++ b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/akka/utils/EntityConvertUtilsTest.java @@ -20,9 +20,20 @@ import org.junit.Test; import org.kaaproject.kaa.server.common.log.shared.appender.LogDeliveryErrorCode; import org.kaaproject.kaa.server.common.verifier.UserVerifierErrorCode; +import org.kaaproject.kaa.server.operations.service.akka.messages.core.logs.LogDeliveryMessage; +import org.kaaproject.kaa.server.operations.service.akka.messages.core.user.verification.UserVerificationResponseMessage; +import org.kaaproject.kaa.server.sync.LogServerSync; +import org.kaaproject.kaa.server.sync.SyncStatus; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class EntityConvertUtilsTest { + @Test public void toUserVerifierErrorCodeTest() { Assert.assertEquals(EntityConvertUtils.toErrorCode((UserVerifierErrorCode) null), null); @@ -54,4 +65,34 @@ public void toLogDeliveryErrorCodeTest() { Assert.assertEquals(EntityConvertUtils.toErrorCode(LogDeliveryErrorCode.REMOTE_INTERNAL_ERROR), org.kaaproject.kaa.server.sync.LogDeliveryErrorCode.REMOTE_INTERNAL_ERROR); } + + @Test + public void convertTest() { + UserVerificationResponseMessage successMessage = getUserVerificationResponseMessage(true, null); + UserVerificationResponseMessage failureMessage = getUserVerificationResponseMessage(false, null); + Assert.assertEquals(EntityConvertUtils.convert(successMessage).getResult(), SyncStatus.SUCCESS); + Assert.assertEquals(EntityConvertUtils.convert(failureMessage).getResult(), SyncStatus.FAILURE); + Map responseMap = new HashMap<>(); + LogDeliveryMessage successLogDeliveryMessage = getLogDeliveryMessage(true, null); + LogDeliveryMessage failureLogDeliveryMessage = getLogDeliveryMessage(false, + LogDeliveryErrorCode.APPENDER_INTERNAL_ERROR); + responseMap.put(1, successLogDeliveryMessage); + responseMap.put(2, failureLogDeliveryMessage); + LogServerSync sync = EntityConvertUtils.convert(responseMap); + Assert.assertNull(sync.getDeliveryStatuses().get(0).getErrorCode()); + Assert.assertEquals(sync.getDeliveryStatuses().get(1).getErrorCode(), + org.kaaproject.kaa.server.sync.LogDeliveryErrorCode.APPENDER_INTERNAL_ERROR); + } + + private UserVerificationResponseMessage getUserVerificationResponseMessage(boolean status, + UserVerifierErrorCode errorCode) { + UserVerificationResponseMessage responseMessage = mock(UserVerificationResponseMessage.class); + when(responseMessage.isSuccess()).thenReturn(status); + when(responseMessage.getErrorCode()).thenReturn(errorCode); + return responseMessage; + } + + private LogDeliveryMessage getLogDeliveryMessage(boolean status, LogDeliveryErrorCode errorCode) { + return new LogDeliveryMessage(1, status, errorCode); + } } diff --git a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/event/RouteInfoTest.java b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/event/RouteInfoTest.java new file mode 100644 index 0000000000..8f21fd5df1 --- /dev/null +++ b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/event/RouteInfoTest.java @@ -0,0 +1,29 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.operations.service.event; + +import nl.jqno.equalsverifier.EqualsVerifier; +import nl.jqno.equalsverifier.Warning; +import org.junit.Test; + +public class RouteInfoTest { + + @Test + public void hashCodeEqualsTest(){ + EqualsVerifier.forClass(RouteInfo.class).usingGetClass().suppress(Warning.NONFINAL_FIELDS).verify(); + } +} diff --git a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/filter/GenericRecordPropertyAccessorTest.java b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/filter/GenericRecordPropertyAccessorTest.java new file mode 100644 index 0000000000..66e11a676f --- /dev/null +++ b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/filter/GenericRecordPropertyAccessorTest.java @@ -0,0 +1,37 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.operations.service.filter; + +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.server.operations.service.filter.el.GenericRecordPropertyAccessor; +import org.springframework.expression.AccessException; + +public class GenericRecordPropertyAccessorTest { + + @Test + public void canWriteTest() throws AccessException { + GenericRecordPropertyAccessor accessor = new GenericRecordPropertyAccessor(); + Assert.assertFalse(accessor.canWrite(null, null, null)); + } + + @Test(expected = UnsupportedOperationException.class) + public void writeTest() throws AccessException { + GenericRecordPropertyAccessor accessor = new GenericRecordPropertyAccessor(); + accessor.write(null, null, null, null); + } +} diff --git a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/thrift/OperationsThriftServiceTest.java b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/thrift/OperationsThriftServiceTest.java index 0f5ec35bcf..7bb6329093 100644 --- a/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/thrift/OperationsThriftServiceTest.java +++ b/server/operations/src/test/java/org/kaaproject/kaa/server/operations/service/thrift/OperationsThriftServiceTest.java @@ -16,6 +16,7 @@ package org.kaaproject.kaa.server.operations.service.thrift; +import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import org.apache.thrift.TException; @@ -27,11 +28,11 @@ import org.kaaproject.kaa.server.common.dao.ApplicationService; import org.kaaproject.kaa.server.common.thrift.gen.operations.Notification; import org.kaaproject.kaa.server.common.thrift.gen.operations.OperationsThriftService; +import org.kaaproject.kaa.server.common.thrift.gen.operations.RedirectionRule; import org.kaaproject.kaa.server.operations.service.akka.AkkaService; import org.kaaproject.kaa.server.operations.service.cache.AppSeqNumber; import org.kaaproject.kaa.server.operations.service.cache.AppVersionKey; import org.kaaproject.kaa.server.operations.service.cache.CacheService; -import org.kaaproject.kaa.server.operations.service.thrift.OperationsThriftServiceImpl; import org.mockito.Mockito; import org.springframework.test.util.ReflectionTestUtils; @@ -138,4 +139,11 @@ public void testAppNotFound() throws TException{ public void testServerName() throws TException{ Assert.assertEquals("operations", operationsThriftService.serverName()); } + + @Test + public void testSetRedirectionRule() throws TException{ + RedirectionRule redirectionRule = new RedirectionRule(); + operationsThriftService.setRedirectionRule(redirectionRule); + Mockito.verify(akkaService, atLeastOnce()).onRedirectionRule(redirectionRule); + } } diff --git a/server/transports/http/transport/pom.xml b/server/transports/http/transport/pom.xml index 4443fbeacf..e7d8696639 100644 --- a/server/transports/http/transport/pom.xml +++ b/server/transports/http/transport/pom.xml @@ -62,6 +62,10 @@ mockito-all test + + org.springframework + spring-test + diff --git a/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/HttpHandlerTest.java b/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/HttpHandlerTest.java index 522e73ea86..24a62405d3 100644 --- a/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/HttpHandlerTest.java +++ b/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/HttpHandlerTest.java @@ -18,12 +18,14 @@ import java.util.UUID; +import org.junit.Assert; import org.junit.Test; import org.kaaproject.kaa.server.transport.channel.ChannelType; import org.kaaproject.kaa.server.transport.message.MessageHandler; import org.kaaproject.kaa.server.transports.http.transport.commands.AbstractHttpSyncCommand; import org.kaaproject.kaa.server.transports.http.transport.messages.NettyHttpSyncMessage; import org.mockito.Mockito; +import org.springframework.test.util.ReflectionTestUtils; public class HttpHandlerTest { @@ -37,4 +39,15 @@ public void testFlow() throws Exception{ handler.channelRead0(null, commandMock); Mockito.verify(messageHandler).process(Mockito.any(NettyHttpSyncMessage.class)); } + + @Test + public void buildTest() { + HttpHandler httpHandler = new HttpHandler(null, null); + Assert.assertNull(httpHandler.build(new Exception("Some exception"))); + AbstractHttpSyncCommand commandMock = Mockito.mock(AbstractHttpSyncCommand.class); + ReflectionTestUtils.setField(httpHandler, "command", commandMock); + Assert.assertArrayEquals(new Object[]{commandMock}, httpHandler.build(null, null, false)); + Assert.assertArrayEquals(new Object[]{commandMock}, httpHandler.build(null, new byte[1], false)); + Assert.assertArrayEquals(new Object[]{commandMock}, httpHandler.build(null, false)); + } } diff --git a/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/commands/HttpCommandsTest.java b/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/commands/HttpCommandsTest.java new file mode 100644 index 0000000000..8a06fae5d0 --- /dev/null +++ b/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/commands/HttpCommandsTest.java @@ -0,0 +1,72 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.kaaproject.kaa.server.transports.http.transport.commands; + +import io.netty.handler.codec.http.HttpRequest; +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.common.endpoint.CommonEPConstans; +import org.kaaproject.kaa.server.transports.http.transport.messages.NettyHttpSyncMessage; +import org.kaaproject.kaa.server.transports.http.transport.netty.AbstractCommand; +import org.mockito.Mockito; + +import java.util.UUID; + +import static org.mockito.Mockito.mock; + +public class HttpCommandsTest { + @Test + public void abstractHttpSyncCommandGetSetTest() { + AbstractHttpSyncCommand abstractHttpSyncCommand = mock(AbstractHttpSyncCommand.class, Mockito.CALLS_REAL_METHODS); + + byte[] responseBody = new byte[] {1, 2, 3, 4, 5}; + byte[] responseSignature = new byte[] {5, 6, 8, 9, 10}; + abstractHttpSyncCommand.setResponseBody(responseBody); + Assert.assertArrayEquals(responseBody, abstractHttpSyncCommand.getResponseBody()); + abstractHttpSyncCommand.setResponseSignature(responseSignature); + Assert.assertArrayEquals(responseSignature, abstractHttpSyncCommand.getResponseSignature()); + } + + @Test + public void abstractCommandGetSetTest() { + AbstractCommand abstractCommand = mock(AbstractCommand.class, Mockito.CALLS_REAL_METHODS); + UUID uuid = UUID.randomUUID(); + abstractCommand.setSessionUuid(uuid); + Assert.assertEquals(uuid, abstractCommand.getSessionUuid()); + long syncTime = 100342L; + abstractCommand.setSyncTime(syncTime); + Assert.assertEquals(syncTime, abstractCommand.getSyncTime()); + int commandId = 1; + abstractCommand.setCommandId(commandId); + Assert.assertEquals(commandId, abstractCommand.getCommandId()); + HttpRequest httpRequest = mock(HttpRequest.class); + abstractCommand.setRequest(httpRequest); + Assert.assertEquals(httpRequest, abstractCommand.getRequest()); + } + + @Test + public void nettyHttpSyncMessageTest() { + NettyHttpSyncMessage nettyHttpSyncMessage = mock(NettyHttpSyncMessage.class, Mockito.CALLS_REAL_METHODS); + Assert.assertEquals(0, nettyHttpSyncMessage.getKeepAlive()); + Assert.assertTrue(nettyHttpSyncMessage.isEncrypted()); + } + + @Test + public void longSyncCommandTest() { + Assert.assertEquals(CommonEPConstans.LONG_SYNC_COMMAND, LongSyncCommand.getCommandName()); + } +} diff --git a/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/commands/SyncCommandTest.java b/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/commands/SyncCommandTest.java index 22f42cf2a3..a3226f3419 100644 --- a/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/commands/SyncCommandTest.java +++ b/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/commands/SyncCommandTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 CyberVision, Inc. + * Copyright 2015 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.kaaproject.kaa.server.transports.http.transport.commands; import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; @@ -22,16 +23,12 @@ import org.junit.Assert; import org.junit.Test; import org.kaaproject.kaa.server.transport.channel.ChannelType; -import org.kaaproject.kaa.server.transports.http.transport.commands.LongSyncCommand; -import org.kaaproject.kaa.server.transports.http.transport.commands.LongSyncCommandFactory; -import org.kaaproject.kaa.server.transports.http.transport.commands.SyncCommand; -import org.kaaproject.kaa.server.transports.http.transport.commands.SyncCommandFactory; +import org.kaaproject.kaa.server.transports.http.transport.netty.AbstractCommand; public class SyncCommandTest { - @Test - public void testSyncCommand(){ + public void testSyncCommand() throws Exception { SyncCommandFactory commandFactory = new SyncCommandFactory(); SyncCommand command = (SyncCommand)commandFactory.createCommandProcessor(); command.setResponseBody("responseBody".getBytes()); @@ -39,6 +36,9 @@ public void testSyncCommand(){ Assert.assertNotNull(response); Assert.assertEquals(RESPONSE_CONTENT_TYPE, response.headers().get(CONTENT_TYPE)); Assert.assertEquals(ChannelType.SYNC, command.getChannelType()); + Assert.assertEquals("", command.getName()); + Assert.assertEquals("", AbstractCommand.getCommandName()); + command.call(); } @Test diff --git a/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/netty/ResponseEncoderTest.java b/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/netty/ResponseEncoderTest.java index c12f0c85ef..a81a42dadb 100644 --- a/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/netty/ResponseEncoderTest.java +++ b/server/transports/http/transport/src/test/java/org/kaaproject/kaa/server/transports/http/transport/netty/ResponseEncoderTest.java @@ -17,9 +17,10 @@ package org.kaaproject.kaa.server.transports.http.transport.netty; import io.netty.channel.Channel; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; -import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.Attribute; @@ -31,30 +32,41 @@ import static org.mockito.Mockito.*; public class ResponseEncoderTest { + public static final String CONNECTION = "close"; private ResponseEncoder responseEncoder = new ResponseEncoder(); private ChannelHandlerContext channelHandlerContext = mock(ChannelHandlerContext.class); private AbstractCommand abstractCommand = mock(AbstractCommand.class); private ChannelPromise promise = mock(ChannelPromise.class); - private HttpResponse response = mock(HttpResponse.class); + private HttpResponse response = mock(HttpResponse.class, RETURNS_DEEP_STUBS); + private ChannelFuture future = mock(ChannelFuture.class); @SuppressWarnings("unchecked") @Before public void before() { Channel channel = mock(Channel.class); Attribute attribute = mock(Attribute.class); - HttpHeaders headers = mock(HttpHeaders.class); - when(response.headers()).thenReturn(headers); when(response.getProtocolVersion()).thenReturn(new HttpVersion("HTTP/1.1", true)); when(channelHandlerContext.channel()).thenReturn(channel); - when(headers.get(any(CharSequence.class))).thenReturn(null); + when(channelHandlerContext.writeAndFlush(any(Object.class))).thenReturn(future); when(channel.attr(AbstractNettyServer.UUID_KEY)).thenReturn(attribute); when(abstractCommand.getResponse()).thenReturn(response); } @Test public void validHttpResponseWriteTest() throws Exception { + when(response.headers().get(isA(CharSequence.class))).thenReturn(null); responseEncoder.write(channelHandlerContext, abstractCommand, promise); verify(channelHandlerContext).writeAndFlush(response, promise); + verify(future, never()).addListener(ChannelFutureListener.CLOSE); + } + + @Test + public void validHttpResponseAddListenerTest() throws Exception { + when(response.headers().get(isA(CharSequence.class))).thenReturn(CONNECTION); + when(channelHandlerContext.writeAndFlush(response, promise)).thenReturn(future); + responseEncoder.write(channelHandlerContext, abstractCommand, promise); + verify(channelHandlerContext).writeAndFlush(response, promise); + verify(future).addListener(ChannelFutureListener.CLOSE); } @Test diff --git a/server/transports/tcp/transport/src/test/java/org/kaaproject/kaa/server/transports/tcp/transport/commands/TcpCommandsTest.java b/server/transports/tcp/transport/src/test/java/org/kaaproject/kaa/server/transports/tcp/transport/commands/TcpCommandsTest.java new file mode 100644 index 0000000000..a64b09cfb6 --- /dev/null +++ b/server/transports/tcp/transport/src/test/java/org/kaaproject/kaa/server/transports/tcp/transport/commands/TcpCommandsTest.java @@ -0,0 +1,80 @@ +/* + * Copyright 2014-2015 CyberVision, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.kaaproject.kaa.server.transports.tcp.transport.commands; + +import org.junit.Assert; +import org.junit.Test; +import org.kaaproject.kaa.common.channels.protocols.kaatcp.messages.Connect; +import org.kaaproject.kaa.common.channels.protocols.kaatcp.messages.MqttFrame; +import org.kaaproject.kaa.common.channels.protocols.kaatcp.messages.SyncRequest; +import org.kaaproject.kaa.common.endpoint.security.MessageEncoderDecoder; +import org.kaaproject.kaa.common.hash.EndpointObjectHash; +import org.kaaproject.kaa.server.transport.channel.ChannelContext; +import org.kaaproject.kaa.server.transport.channel.ChannelType; +import org.kaaproject.kaa.server.transport.session.SessionInfo; +import org.kaaproject.kaa.server.transports.tcp.transport.messages.NettyTcpConnectMessage; +import org.kaaproject.kaa.server.transports.tcp.transport.messages.NettyTcpSyncMessage; + +import java.util.UUID; + +import static org.mockito.Mockito.mock; + +public class TcpCommandsTest { + @Test + public void kaaTcpCommandTest() { + KaaTcpCommandFactory commandFactory = new KaaTcpCommandFactory(); + KaaTcpCommand command = (KaaTcpCommand)commandFactory.createCommandProcessor(); + Assert.assertNotNull(command); + Assert.assertEquals(KaaTcpCommand.KAA_TCP, command.getName()); + } + + @Test + public void kaaTcpCommandGetSetTest() { + int id = 1; + long syncTime = 1; + MqttFrame mqttFrame = new Connect(); + KaaTcpCommand kaaTcpCommand = new KaaTcpCommand(); + kaaTcpCommand.setCommandId(id); + kaaTcpCommand.setResponse(mqttFrame); + kaaTcpCommand.setSyncTime(syncTime); + Assert.assertEquals(id, kaaTcpCommand.getCommandId()); + Assert.assertEquals(mqttFrame, kaaTcpCommand.getResponse()); + Assert.assertEquals(syncTime, kaaTcpCommand.getSyncTime()); + } + + @Test + public void kaaTcpCommandFactoryGetSetTest() { + KaaTcpCommandFactory kaaTcpCommandFactory = new KaaTcpCommandFactory(); + Assert.assertEquals(KaaTcpCommand.KAA_TCP, kaaTcpCommandFactory.getCommandName()); + } + + @Test + public void nettyKaaTcpSyncMessageGetSetTest() { + Connect connect = new Connect(10, 10, new byte[10], null, null); + NettyTcpConnectMessage nettyTcpConnectMessage = new NettyTcpConnectMessage(null, null, connect, null, null, null, null); + Assert.assertEquals(connect.isEncrypted(), nettyTcpConnectMessage.isEncrypted()); + Assert.assertEquals(connect.getKeepAlive(), nettyTcpConnectMessage.getKeepAlive()); + } + + @Test + public void nettyTcpSyncMessageGetSetTest() { + SyncRequest command = new SyncRequest(new byte[10], true, true); + SessionInfo sessionInfo = new SessionInfo(UUID.randomUUID(), 10, mock(ChannelContext.class), ChannelType.ASYNC, + mock(MessageEncoderDecoder.CipherPair.class), EndpointObjectHash.fromString("hash"), "appToken", "sdkToken", 100, true); + NettyTcpSyncMessage nettyTcpSyncMessage = new NettyTcpSyncMessage(command, sessionInfo, null, null); + Assert.assertEquals(command.isEncrypted(), nettyTcpSyncMessage.isEncrypted()); + } +} diff --git a/server/transports/tcp/transport/src/test/java/org/kaaproject/kaa/server/transports/tcp/transport/messages/NettyTcpMessageTest.java b/server/transports/tcp/transport/src/test/java/org/kaaproject/kaa/server/transports/tcp/transport/messages/NettyTcpMessageTest.java index 857d929921..45cbe765e1 100644 --- a/server/transports/tcp/transport/src/test/java/org/kaaproject/kaa/server/transports/tcp/transport/messages/NettyTcpMessageTest.java +++ b/server/transports/tcp/transport/src/test/java/org/kaaproject/kaa/server/transports/tcp/transport/messages/NettyTcpMessageTest.java @@ -73,6 +73,8 @@ public void connectTest() { @Test public void syncTest() { + SyncRequest syncRequest = new SyncRequest(); + Assert.assertNotNull(syncRequest); UUID channelId = UUID.randomUUID(); ChannelContext ctx = Mockito.mock(ChannelContext.class); ChannelType channelType = ChannelType.ASYNC; @@ -137,5 +139,4 @@ public void pingTest() { Assert.assertEquals(ctx, message.getChannelContext()); Assert.assertEquals(session, message.getSessionInfo()); } - }