Skip to content

Commit

Permalink
Merge pull request #340 from kaaproject/feature/KAA-661
Browse files Browse the repository at this point in the history
KAA-661: improve Java unit tests
  • Loading branch information
ashvayka committed Oct 21, 2015
2 parents dbdbde0 + b8927ad commit 4a20fff
Show file tree
Hide file tree
Showing 50 changed files with 2,315 additions and 63 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -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;
}
};
Expand Down Expand Up @@ -137,4 +146,53 @@ protected Map<TransportProtocolId, List<TransportConnectionInfo>> 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);
}
}
4 changes: 4 additions & 0 deletions client/client-multi/client-java-desktop/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@
<artifactId>sqlite-jdbc</artifactId>
<version>${sqlite.jdbc.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -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());
}
}
Original file line number Diff line number Diff line change
@@ -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<String, byte[]> 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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<RawData> algotithm =
new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory());
DefaultRecordGenerationAlgorithm<RawData> algotithm =
new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory());
RawData rawData = algotithm.getRootData();
AvroJsonConverter<FileConfig> converter =
AvroJsonConverter<FileConfig> 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<FileConfig> byteConverter = new AvroByteArrayConverter<>(FileConfig.class);
byte[] rawConfiguration = byteConverter.toByteArray(fileConfig);

logAppenderDto.setRawConfiguration(rawConfiguration);

return logAppenderDto;
Expand Down
Loading

0 comments on commit 4a20fff

Please sign in to comment.