Skip to content

Commit 4a20fff

Browse files
committed
Merge pull request #340 from kaaproject/feature/KAA-661
KAA-661: improve Java unit tests
2 parents dbdbde0 + b8927ad commit 4a20fff

File tree

50 files changed

+2315
-63
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+2315
-63
lines changed

client/client-multi/client-java-core/src/test/java/org/kaaproject/kaa/client/KaaClientTest.java

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,22 +29,31 @@
2929
import org.junit.Test;
3030
import org.kaaproject.kaa.client.bootstrap.DefaultBootstrapManager;
3131
import org.kaaproject.kaa.client.channel.GenericTransportInfo;
32+
import org.kaaproject.kaa.client.channel.KaaInternalChannelManager;
3233
import org.kaaproject.kaa.client.channel.ServerType;
3334
import org.kaaproject.kaa.client.channel.TransportConnectionInfo;
3435
import org.kaaproject.kaa.client.channel.TransportProtocolId;
36+
import org.kaaproject.kaa.client.channel.impl.ChannelRuntimeException;
3537
import org.kaaproject.kaa.client.context.ExecutorContext;
3638
import org.kaaproject.kaa.client.context.SimpleExecutorContext;
3739
import org.kaaproject.kaa.client.context.TransportContext;
3840
import org.kaaproject.kaa.client.exceptions.KaaException;
41+
import org.kaaproject.kaa.client.exceptions.KaaInvalidConfigurationException;
42+
import org.kaaproject.kaa.client.exceptions.KaaRuntimeException;
43+
import org.kaaproject.kaa.client.exceptions.KaaUnsupportedPlatformException;
44+
import org.kaaproject.kaa.client.logging.AbstractLogCollector;
3945
import org.kaaproject.kaa.client.persistence.KaaClientPropertiesState;
4046
import org.kaaproject.kaa.client.persistence.KaaClientState;
4147
import org.kaaproject.kaa.client.persistence.PersistentStorage;
48+
import org.kaaproject.kaa.client.profile.ProfileRuntimeException;
49+
import org.kaaproject.kaa.client.schema.SchemaRuntimeException;
4250
import org.kaaproject.kaa.client.transport.TransportException;
4351
import org.kaaproject.kaa.client.util.CommonsBase64;
4452
import org.kaaproject.kaa.common.endpoint.gen.ProtocolMetaData;
4553
import org.kaaproject.kaa.common.endpoint.gen.ProtocolVersionPair;
4654
import org.kaaproject.kaa.common.endpoint.security.KeyUtil;
4755
import org.mockito.Mockito;
56+
import org.springframework.test.util.ReflectionTestUtils;
4857

4958
public class KaaClientTest {
5059

@@ -77,7 +86,7 @@ public void beforeTest() throws Exception {
7786
client = new AbstractKaaClient(platformContext, stateListener) {
7887
@Override
7988
protected DefaultBootstrapManager buildBootstrapManager(KaaClientProperties properties, KaaClientState kaaClientState,
80-
TransportContext transportContext) {
89+
TransportContext transportContext) {
8190
return bsManagerMock;
8291
}
8392
};
@@ -137,4 +146,53 @@ protected Map<TransportProtocolId, List<TransportConnectionInfo>> buildDummyConn
137146
return connectionInfo;
138147
}
139148

149+
@Test
150+
public void failureOnStartTest() throws TransportException {
151+
Mockito.doThrow(new KaaRuntimeException(new Exception("cause"))).when(bsManagerMock).receiveOperationsServerList();
152+
client.start();
153+
Mockito.verify(stateListener, Mockito.timeout(1000)).onStartFailure(Mockito.any(KaaException.class));
154+
}
155+
156+
@Test
157+
public void failureOnStopTest() {
158+
client.start();
159+
AbstractLogCollector logCollector = Mockito.mock(AbstractLogCollector.class);
160+
Mockito.doThrow(new RuntimeException()).when(logCollector).stop();
161+
ReflectionTestUtils.setField(client, "logCollector", logCollector);
162+
client.stop();
163+
Mockito.verify(stateListener, Mockito.timeout(1000)).onStopFailure(Mockito.any(KaaException.class));
164+
}
165+
166+
@Test
167+
public void failureOnPauseTest() {
168+
client.start();
169+
KaaClientState clientState = Mockito.mock(KaaClientState.class);
170+
Mockito.doThrow(new RuntimeException()).when(clientState).persist();
171+
ReflectionTestUtils.setField(client, "kaaClientState", clientState);
172+
client.pause();
173+
Mockito.verify(stateListener, Mockito.timeout(1000)).onPauseFailure(Mockito.any(KaaException.class));
174+
}
175+
176+
@Test
177+
public void failureOnResumeTest() {
178+
client.start();
179+
KaaInternalChannelManager channelManager = Mockito.mock(KaaInternalChannelManager.class);
180+
Mockito.doThrow(new RuntimeException()).when(channelManager).resume();
181+
ReflectionTestUtils.setField(client, "channelManager", channelManager);
182+
client.resume();
183+
Mockito.verify(stateListener, Mockito.timeout(1000)).onResumeFailure(Mockito.any(KaaException.class));
184+
}
185+
186+
@Test
187+
public void exceptionCreationTest() {
188+
KaaUnsupportedPlatformException kaaUnsupportedPlatformException = new KaaUnsupportedPlatformException(new Exception());
189+
ProfileRuntimeException profileRuntimeException = new ProfileRuntimeException("");
190+
SchemaRuntimeException schemaRuntimeException1 = new SchemaRuntimeException();
191+
SchemaRuntimeException schemaRuntimeException2 = new SchemaRuntimeException("");
192+
KaaInvalidConfigurationException invalidConfigurationException = new KaaInvalidConfigurationException(new Exception());
193+
ChannelRuntimeException channelRuntimeException1 = new ChannelRuntimeException();
194+
ChannelRuntimeException channelRuntimeException2 = new ChannelRuntimeException(new Exception());
195+
ChannelRuntimeException channelRuntimeException3 = new ChannelRuntimeException("", new Exception());
196+
ChannelRuntimeException channelRuntimeException4 = new ChannelRuntimeException("", new Exception(), true, true);
197+
}
140198
}

client/client-multi/client-java-desktop/pom.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,10 @@
9898
<artifactId>sqlite-jdbc</artifactId>
9999
<version>${sqlite.jdbc.version}</version>
100100
</dependency>
101+
<dependency>
102+
<groupId>org.springframework</groupId>
103+
<artifactId>spring-test</artifactId>
104+
</dependency>
101105
</dependencies>
102106

103107
<build>
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* Copyright 2014-2015 CyberVision, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.kaaproject.kaa.client.connectivity;
18+
19+
import org.junit.Assert;
20+
import org.junit.Test;
21+
22+
public class PingConnectivityCheckerTest {
23+
24+
@Test
25+
public void checkConnectivityToWrongHostTest() {
26+
PingConnectivityChecker pingConnectivityChecker = new PingConnectivityChecker("some-wrong-host=with-dashes-in-name");
27+
Assert.assertFalse(pingConnectivityChecker.checkConnectivity());
28+
}
29+
30+
@Test
31+
public void checkConnectivityForLocalHostTest() {
32+
PingConnectivityChecker pingConnectivityChecker = new PingConnectivityChecker("localhost");
33+
Assert.assertTrue(pingConnectivityChecker.checkConnectivity());
34+
}
35+
}
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
/*
2+
* Copyright 2014-2015 CyberVision, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.kaaproject.kaa.client.transport;
18+
19+
import org.apache.http.HttpEntity;
20+
import org.apache.http.client.methods.CloseableHttpResponse;
21+
import org.apache.http.client.methods.HttpPost;
22+
import org.apache.http.impl.client.CloseableHttpClient;
23+
import org.junit.Assert;
24+
import org.junit.BeforeClass;
25+
import org.junit.Test;
26+
import org.mockito.Mockito;
27+
import org.springframework.test.util.ReflectionTestUtils;
28+
29+
import java.io.ByteArrayInputStream;
30+
import java.io.IOException;
31+
import java.security.PrivateKey;
32+
import java.security.PublicKey;
33+
import java.util.LinkedHashMap;
34+
35+
import static org.mockito.Matchers.any;
36+
import static org.mockito.Mockito.*;
37+
38+
public class DesktopHttpClientTest {
39+
private static final String URL = "http://some-url";
40+
private static final String HTTP_CLIENT_FIELD_NAME = "httpClient";
41+
private static final String HTTP_METHOD_FIELD_NAME = "method";
42+
private static final int OK = 200;
43+
private static final int FAILURE = 400;
44+
private static PrivateKey privateKey;
45+
private static PublicKey publicKey;
46+
private static PublicKey remotePublicKey;
47+
private static LinkedHashMap<String, byte[]> entities = new LinkedHashMap<>();
48+
private CloseableHttpResponse httpResponse;
49+
50+
@BeforeClass
51+
public static void setUp() {
52+
entities.put("entity1", new byte[]{1, 2, 3});
53+
entities.put("entity2", new byte[]{53, 1});
54+
privateKey = mock(PrivateKey.class);
55+
publicKey = mock(PublicKey.class);
56+
remotePublicKey = mock(PublicKey.class);
57+
when(privateKey.getEncoded()).thenReturn(new byte[]{1, 2, 3, 4, 5});
58+
when(publicKey.getEncoded()).thenReturn(new byte[]{1, 2, 3, 4, 5, 10});
59+
when(remotePublicKey.getEncoded()).thenReturn(new byte[]{5, 3, 2, 5, 6 , 3, 127});
60+
}
61+
62+
@Test(expected = TransportException.class)
63+
public void executeInvalidHttpRequestTest() throws Exception {
64+
DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey);
65+
CloseableHttpClient httpClientMock = mockForHttpClient(FAILURE, true, null);
66+
ReflectionTestUtils.setField(client, HTTP_CLIENT_FIELD_NAME, httpClientMock);
67+
client.executeHttpRequest(URL, entities, false);
68+
verify(httpResponse).close();
69+
}
70+
71+
@Test
72+
public void executeValidHttpRequest() throws Exception {
73+
byte[] inputData = new byte[]{100, 101, 102};
74+
DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey);
75+
CloseableHttpClient httpClientMock = mockForHttpClient(OK, true, inputData);
76+
ReflectionTestUtils.setField(client, HTTP_CLIENT_FIELD_NAME, httpClientMock);
77+
byte[] body = client.executeHttpRequest(URL, entities, false);
78+
Assert.assertArrayEquals(inputData, body);
79+
verify(httpResponse).close();
80+
}
81+
82+
@Test
83+
public void canAbortTest() throws Throwable {
84+
DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey);
85+
ReflectionTestUtils.setField(client, HTTP_METHOD_FIELD_NAME, null);
86+
Assert.assertFalse(client.canAbort());
87+
HttpPost method = new HttpPost();
88+
method.abort();
89+
ReflectionTestUtils.setField(client, HTTP_METHOD_FIELD_NAME, method);
90+
Assert.assertFalse(client.canAbort());
91+
method = new HttpPost();
92+
ReflectionTestUtils.setField(client, HTTP_METHOD_FIELD_NAME, method);
93+
Assert.assertTrue(client.canAbort());
94+
}
95+
96+
@Test(expected = IOException.class)
97+
public void executeValidHttpRequestWithNoResponseEntityTest() throws Exception {
98+
DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey);
99+
CloseableHttpClient httpClientMock = mockForHttpClient(OK, false, null);
100+
ReflectionTestUtils.setField(client, HTTP_CLIENT_FIELD_NAME, httpClientMock);
101+
client.executeHttpRequest(URL, entities, false);
102+
verify(httpResponse).close();
103+
}
104+
105+
@Test
106+
public void closeTest() throws IOException {
107+
DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey);
108+
CloseableHttpClient httpClientMock = mockForHttpClient(OK, false, null);
109+
ReflectionTestUtils.setField(client, HTTP_CLIENT_FIELD_NAME, httpClientMock);
110+
client.close();
111+
verify(httpClientMock).close();
112+
}
113+
114+
@Test
115+
public void abortTest() throws IOException {
116+
DesktopHttpClient client = new DesktopHttpClient(URL, privateKey, publicKey, remotePublicKey);
117+
HttpPost method = mock(HttpPost.class);
118+
when(method.isAborted()).thenReturn(false);
119+
ReflectionTestUtils.setField(client, HTTP_METHOD_FIELD_NAME, method);
120+
client.abort();
121+
verify(method).abort();
122+
}
123+
124+
private CloseableHttpClient mockForHttpClient(int status, boolean hasEntity, byte[] body) throws IOException {
125+
CloseableHttpClient httpClientMock = mock(CloseableHttpClient.class);
126+
httpResponse = mock(CloseableHttpResponse.class, RETURNS_DEEP_STUBS);
127+
doReturn(httpResponse).when(httpClientMock).execute(any(HttpPost.class));
128+
if (hasEntity) {
129+
HttpEntity entity = mock(HttpEntity.class);
130+
doReturn(entity).when(httpResponse).getEntity();
131+
if (body != null) {
132+
doReturn(new ByteArrayInputStream(body)).when(entity).getContent();
133+
}
134+
} else {
135+
doReturn(null).when(httpResponse).getEntity();
136+
}
137+
when(httpResponse.getStatusLine().getStatusCode()).thenReturn(status);
138+
return httpClientMock;
139+
}
140+
}

common/endpoint-shared/src/test/java/org/kaaproject/kaa/common/kaatcp/KaaTcpMessageTest.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ public class KaaTcpMessageTest {
3535
@Test
3636
public void testSyncResponseMessage() {
3737
final byte kaaSync[] = new byte [] { (byte) 0xF0, 0x0D, 0x00, 0x06, 'K', 'a', 'a', 't', 'c', 'p', 0x01, 0x00, 0x05, 0x14, (byte) 0xFF };
38+
SyncResponse syncResponse = new SyncResponse();
39+
Assert.assertNotNull(syncResponse);
3840
SyncResponse message = new SyncResponse(new byte [] { (byte) 0xFF }, false, true);
3941
message.setMessageId(5);
4042
byte[] actual = message.getFrame().array();

server/appenders/file/appender/src/test/java/org/kaaproject/kaa/server/appenders/file/appender/FileSystemLogAppenderTest.java

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package org.kaaproject.kaa.server.appenders.file.appender;
1818

1919
import static org.mockito.Mockito.mock;
20+
import static org.mockito.Mockito.verify;
2021

2122
import java.io.File;
2223
import java.util.Arrays;
@@ -90,6 +91,15 @@ public void testAppend() throws Exception {
9091
}
9192
}
9293

94+
@Test
95+
public void appendToClosedAppenderTest() {
96+
FileSystemLogAppender appender = new FileSystemLogAppender();
97+
LogDeliveryCallback listener = mock(LogDeliveryCallback.class);
98+
ReflectionTestUtils.setField(appender, "closed", true);
99+
appender.doAppend(null, null, listener);
100+
verify(listener).onInternalError();
101+
}
102+
93103
@Test
94104
public void testAppendWithInternalError() throws Exception {
95105
FileSystemLogAppender appender = new FileSystemLogAppender();
@@ -147,27 +157,27 @@ public void initTest() throws Exception {
147157
appender.close();
148158
}
149159
}
150-
160+
151161
private LogAppenderDto prepareConfig() throws Exception {
152162

153163
LogAppenderDto logAppenderDto = new LogAppenderDto();
154164
logAppenderDto.setApplicationId(APPLICATION_ID);
155165
logAppenderDto.setName("test");
156166
logAppenderDto.setTenantId(TENANT_ID);
157-
167+
158168
RawSchema rawSchema = new RawSchema(FileConfig.getClassSchema().toString());
159-
DefaultRecordGenerationAlgorithm<RawData> algotithm =
160-
new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory());
169+
DefaultRecordGenerationAlgorithm<RawData> algotithm =
170+
new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory());
161171
RawData rawData = algotithm.getRootData();
162-
AvroJsonConverter<FileConfig> converter =
172+
AvroJsonConverter<FileConfig> converter =
163173
new AvroJsonConverter<>(FileConfig.getClassSchema(), FileConfig.class);
164174
FileConfig fileConfig = converter.decodeJson(rawData.getRawData());
165-
175+
166176
fileConfig.setLogsRootPath(System.getProperty("java.io.tmpdir") + File.separator + "tmp_logs_"+System.currentTimeMillis());
167-
177+
168178
AvroByteArrayConverter<FileConfig> byteConverter = new AvroByteArrayConverter<>(FileConfig.class);
169179
byte[] rawConfiguration = byteConverter.toByteArray(fileConfig);
170-
180+
171181
logAppenderDto.setRawConfiguration(rawConfiguration);
172182

173183
return logAppenderDto;

0 commit comments

Comments
 (0)