05523da7a6e5d9272e6786fb5806035005491780
[iotivity.git] / cloud / interface / src / test / java / org / iotivity / cloud / ciserver / DeviceServerSystemTest.java
1 /*
2  * //******************************************************************
3  * //
4  * // Copyright 2016 Samsung Electronics All Rights Reserved.
5  * //
6  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
7  * //
8  * // Licensed under the Apache License, Version 2.0 (the "License");
9  * // you may not use this file except in compliance with the License.
10  * // You may obtain a copy of the License at
11  * //
12  * //      http://www.apache.org/licenses/LICENSE-2.0
13  * //
14  * // Unless required by applicable law or agreed to in writing, software
15  * // distributed under the License is distributed on an "AS IS" BASIS,
16  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * // See the License for the specific language governing permissions and
18  * // limitations under the License.
19  * //
20  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21  */
22
23 package org.iotivity.cloud.ciserver;
24
25 import static java.util.concurrent.TimeUnit.SECONDS;
26 import static org.junit.Assert.assertEquals;
27 import static org.junit.Assert.assertTrue;
28 import static org.mockito.Mockito.mock;
29
30 import java.util.HashMap;
31 import java.util.concurrent.CountDownLatch;
32
33 import org.iotivity.cloud.base.OICConstants;
34 import org.iotivity.cloud.base.connector.ConnectorPool;
35 import org.iotivity.cloud.base.device.CoapDevice;
36 import org.iotivity.cloud.base.device.Device;
37 import org.iotivity.cloud.base.device.IRequestChannel;
38 import org.iotivity.cloud.base.protocols.IRequest;
39 import org.iotivity.cloud.base.protocols.IResponse;
40 import org.iotivity.cloud.base.protocols.ISignaling;
41 import org.iotivity.cloud.base.protocols.MessageBuilder;
42 import org.iotivity.cloud.base.protocols.coap.CoapRequest;
43 import org.iotivity.cloud.base.protocols.coap.CoapResponse;
44 import org.iotivity.cloud.base.protocols.coap.CoapSignaling;
45 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
46 import org.iotivity.cloud.base.protocols.enums.RequestMethod;
47 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
48 import org.iotivity.cloud.base.protocols.enums.SignalingMethod;
49 import org.iotivity.cloud.base.server.CoapServer;
50 import org.iotivity.cloud.base.server.HttpServer;
51 import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapDevicePool;
52 import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapSignalingHandler;
53 import org.iotivity.cloud.ciserver.resources.proxy.account.Account;
54 import org.iotivity.cloud.ciserver.resources.proxy.mq.MessageQueue;
55 import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceDirectory;
56 import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourceFind;
57 import org.iotivity.cloud.ciserver.resources.proxy.rd.ResourcePresence;
58 import org.iotivity.cloud.util.Cbor;
59 import org.iotivity.cloud.util.Log;
60 import org.junit.Before;
61 import org.junit.Test;
62 import org.junit.runner.RunWith;
63 import org.mockito.InjectMocks;
64 import org.mockito.Mock;
65 import org.mockito.Mockito;
66 import org.mockito.MockitoAnnotations;
67 import org.mockito.invocation.InvocationOnMock;
68 import org.mockito.stubbing.Answer;
69
70 import io.netty.channel.Channel;
71 import io.netty.channel.ChannelHandlerContext;
72 import io.netty.channel.ChannelId;
73 import io.netty.channel.ChannelPromise;
74 import io.netty.util.Attribute;
75 import org.powermock.api.mockito.PowerMockito;
76 import org.powermock.core.classloader.annotations.PrepareForTest;
77 import org.powermock.modules.junit4.PowerMockRunner;
78
79 @RunWith(PowerMockRunner.class)
80 @PrepareForTest(ConnectorPool.class)
81 public class DeviceServerSystemTest {
82     private ChannelHandlerContext                   mCtx                  = null;
83     private ChannelHandlerContext                   mCtxSignal            = null;
84     private String                                  mDi                   = "B371C481-38E6-4D47-8320-7688D8A5B58C";
85     private String                                  mUserId               = "testuser";
86     private String                                  mAccessToken          = "1689c70ffa245effc563017fee36d250";
87     private Device                                  mDevice               = mock(
88             Device.class);
89     private CoapDevice                              mMockDevice           = mock(
90             CoapDevice.class);
91     private IResponse                               mRes                  = null;
92     private IRequest                                mReq                  = null;
93     private ISignaling                              mSig                  = null;
94     final CountDownLatch                            mLatch                = new CountDownLatch(
95             1);
96     private Cbor<HashMap<Object, Object>>           mCbor                 = new Cbor<>();
97     @Mock
98     private IRequestChannel                         mRequestChannel;
99
100     @InjectMocks
101     private DeviceServerSystem                      mDeviceServerSystem   = new DeviceServerSystem();
102     @InjectMocks
103     private DeviceServerSystem.CoapLifecycleHandler mCoapLifecycleHandler = mDeviceServerSystem.new CoapLifecycleHandler();
104     @InjectMocks
105     private DeviceServerSystem.CoapAuthHandler      mCoapAuthHandler      = mDeviceServerSystem.new CoapAuthHandler();
106     @InjectMocks
107     private CoapSignalingHandler                    mCoapSignalingHandler = mDeviceServerSystem.new CoapSignalingHandler();
108
109     @Before
110     public void setUp() throws Exception {
111         Log.createfile();
112         MockitoAnnotations.initMocks(this);
113         mRes = null;
114         mReq = null;
115         mCtx = mock(ChannelHandlerContext.class);
116         mCtxSignal = mock(ChannelHandlerContext.class);
117         Cbor<HashMap<Object, Object>> cbor = new Cbor<>();
118         Channel channel = mock(Channel.class);
119         Attribute<Device> attribute = mock(Attribute.class);
120         ChannelId channelId = mock(ChannelId.class);
121         Mockito.doReturn(channel).when(mCtx).channel();
122         Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
123         Mockito.doReturn(channelId).when(channel).id();
124         Mockito.doReturn(
125                 "0000000141f3edcfc2c3000000000001d0000000000000000000000000000000000000")
126                 .when(channelId).asLongText();
127         Mockito.doReturn(mMockDevice).when(attribute).get();
128         Mockito.doReturn("sampleDeviceID").when(mMockDevice).getDeviceId();
129         Mockito.doAnswer(new Answer<Object>() {
130             @Override
131             public CoapRequest answer(InvocationOnMock invocation)
132                     throws Throwable {
133                 Object[] args = invocation.getArguments();
134                 CoapRequest request = (CoapRequest) args[0];
135                 System.out.println(
136                         "\t----------payload : " + request.getPayloadString());
137                 System.out.println(
138                         "\t----------uripath : " + request.getUriPath());
139                 System.out.println(
140                         "\t---------uriquery : " + request.getUriQuery());
141                 mReq = request;
142                 mLatch.countDown();
143                 return null;
144             }
145         }).when(mCtx).fireChannelRead(Mockito.any());
146
147         Mockito.doAnswer(new Answer<Object>() {
148             @Override
149             public CoapSignaling answer(InvocationOnMock invocation)
150                     throws Throwable {
151                 Object[] args = invocation.getArguments();
152                 CoapSignaling signaling = (CoapSignaling) args[0];
153                 System.out.println("\t----------payload : "
154                         + signaling.getPayloadString());
155                 System.out.println("\t----------signaling method : "
156                         + signaling.getSignalingMethod());
157                 if (signaling.getSignalingMethod()
158                         .equals(SignalingMethod.CSM)) {
159                     System.out.println("\t----------CSM Blockwise Transfer : "
160                             + signaling.getCsmBlockWiseTransfer());
161                     System.out.println("\t----------CSM Max Message Size : "
162                             + signaling.getCsmMaxMessageSize());
163                     System.out.println("\t----------CSM Server Name : "
164                             + signaling.getCsmServerName());
165                 }
166                 mSig = signaling;
167                 mLatch.countDown();
168                 return null;
169             }
170         }).when(mCtxSignal).fireChannelRead(Mockito.any());
171
172         Mockito.doAnswer(new Answer<Object>() {
173             @Override
174             public CoapResponse answer(InvocationOnMock invocation)
175                     throws Throwable {
176                 Object[] args = invocation.getArguments();
177                 CoapResponse response = (CoapResponse) args[0];
178                 System.out.println(
179                         "\t----------payload : " + response.getPayloadString());
180                 System.out.println(
181                         "\t----------status : " + response.getStatus());
182                 mRes = response;
183                 mLatch.countDown();
184                 return null;
185             }
186         }).when(mCtx).writeAndFlush(Mockito.any());
187
188         PowerMockito.mockStatic(ConnectorPool.class);
189         PowerMockito.when(ConnectorPool.getConnection(Mockito.anyString())).thenReturn(mRequestChannel);
190     }
191
192     @Test
193     public void testAddHttpServer() throws Exception {
194         HttpServer httpServer = new HttpServer(null);
195         mDeviceServerSystem.addServer(httpServer);
196     }
197
198     @Test
199     public void testAddCoapServer() throws Exception {
200         CoapServer coapServer = new CoapServer(null);
201         mDeviceServerSystem.addServer(coapServer);
202     }
203
204     @Test
205     public void testGetDevicePool() throws Exception {
206         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
207         if (devicePool != null) {
208             System.out.println("devicePool returned :" + devicePool);
209         }
210     }
211
212     @Test
213     public void testAddDevice() throws Exception {
214         CoapDevice coapDevice = new CoapDevice(null);
215         coapDevice.updateDevice(mDi, mUserId, mAccessToken);
216         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
217         devicePool.addDevice(coapDevice);
218     }
219
220     @Test
221     public void testRemoveNotRegisteredDevice() throws Exception {
222         CoapDevice coapDevice = new CoapDevice(null);
223         coapDevice.updateDevice(mDi, mUserId, mAccessToken);
224         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
225         devicePool.removeDevice(coapDevice);
226     }
227
228     @Test
229     public void testRemoveDevice() throws Exception {
230         CoapDevice coapDevice = new CoapDevice(null);
231         coapDevice.updateDevice(mDi, mUserId, mAccessToken);
232         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
233         devicePool.addDevice(coapDevice);
234         devicePool.removeDevice(coapDevice);
235     }
236
237     @Test
238     public void testQueryDevice() throws Exception {
239         CoapDevice coapDevice = new CoapDevice(null);
240         coapDevice.updateDevice(mDi, mUserId, mAccessToken);
241         CoapDevicePool devicePool = mDeviceServerSystem.getDevicePool();
242         devicePool.addDevice(coapDevice);
243         devicePool.queryDevice(mDi);
244     }
245
246     @Test
247     public void testStopSystem() throws Exception {
248         mDeviceServerSystem.stopSystem();
249     }
250
251     @Test
252     public void testAddAccountResource() {
253         Account acHandler = new Account();
254         ResourceDirectory rdHandler = new ResourceDirectory();
255         ResourceFind resHandler = new ResourceFind();
256         ResourcePresence adHandler = new ResourcePresence();
257         MessageQueue mqHandler = new MessageQueue();
258         mDeviceServerSystem.addResource(acHandler);
259         mDeviceServerSystem.addResource(rdHandler);
260         mDeviceServerSystem.addResource(resHandler);
261         mDeviceServerSystem.addResource(adHandler);
262         mDeviceServerSystem.addResource(mqHandler);
263     }
264
265     @Test
266     public void coapAuthHandlerAccountCtxNullChannelReadRequest()
267             throws InterruptedException {
268         System.out.println(
269                 "\t--------------coapAuthHandler Account ctx is null ChannelReadRequest Test------------");
270         Channel channel = mock(Channel.class);
271         Attribute<Device> attribute = mock(Attribute.class);
272         Mockito.doReturn(channel).when(mCtx).channel();
273         Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
274         Mockito.doReturn(null).when(attribute).get();
275         HashMap<String, Object> payloadData = new HashMap<>();
276         payloadData.put(Constants.DEVICE_ID, "sampleDevice");
277
278         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
279                 OICConstants.ACCOUNT_FULL_URI, null,
280                 ContentFormat.APPLICATION_CBOR,
281                 mCbor.encodingPayloadToCbor(payloadData));
282         mCoapAuthHandler.channelRead(mCtx, request);
283
284         assertEquals(mReq.getUriPath(), OICConstants.ACCOUNT_FULL_URI);
285         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
286                 .containsKey(Constants.DEVICE_ID));
287     }
288
289     @Test
290     public void coapAuthHandlerPingChannelReadRequest()
291             throws InterruptedException {
292         System.out.println(
293                 "\t--------------coapAuthHandler Ping ChannelReadRequest Test------------");
294
295         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
296                 OICConstants.KEEP_ALIVE_FULL_URI, null, null, null);
297         mCoapAuthHandler.channelRead(mCtx, request);
298
299         assertEquals(mReq.getUriPath(), OICConstants.KEEP_ALIVE_FULL_URI);
300     }
301
302     @Test
303     public void coapAuthHandlerAccountSessionChannelReadRequest()
304             throws InterruptedException {
305         System.out.println(
306                 "\t--------------coapAuthHandler AccountSession ChannelReadRequest Test------------");
307
308         HashMap<String, Object> payloadData = new HashMap<>();
309         payloadData.put(Constants.DEVICE_ID, mDi);
310         payloadData.put(Constants.USER_ID, mAccessToken);
311         payloadData.put(Constants.ACCESS_TOKEN, mAccessToken);
312
313         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
314                 OICConstants.ACCOUNT_SESSION_FULL_URI, null,
315                 ContentFormat.APPLICATION_CBOR,
316                 mCbor.encodingPayloadToCbor(payloadData));
317         mCoapAuthHandler.channelRead(mCtx, request);
318
319         assertEquals(mReq.getUriPath(), OICConstants.ACCOUNT_SESSION_FULL_URI);
320         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
321                 .containsKey(Constants.DEVICE_ID));
322         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
323                 .containsKey(Constants.USER_ID));
324         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
325                 .containsKey(Constants.ACCESS_TOKEN));
326     }
327
328     @Test
329     public void coapAuthHandlerAccountSessionCtxNullChannelReadRequest()
330             throws InterruptedException {
331         System.out.println(
332                 "\t--------------coapAuthHandler AccountSession ctx is null ChannelReadRequest Test------------");
333         Channel channel = mock(Channel.class);
334         Attribute<Device> attribute = mock(Attribute.class);
335         Mockito.doReturn(channel).when(mCtx).channel();
336         Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
337         Mockito.doReturn(null).when(attribute).get();
338         HashMap<String, Object> payloadData = new HashMap<>();
339         payloadData.put(Constants.DEVICE_ID, mDi);
340         payloadData.put(Constants.USER_ID, mAccessToken);
341         payloadData.put(Constants.ACCESS_TOKEN, mAccessToken);
342
343         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
344                 OICConstants.ACCOUNT_SESSION_FULL_URI, null,
345                 ContentFormat.APPLICATION_CBOR,
346                 mCbor.encodingPayloadToCbor(payloadData));
347         mCoapAuthHandler.channelRead(mCtx, request);
348
349         assertEquals(mReq.getUriPath(), OICConstants.ACCOUNT_SESSION_FULL_URI);
350         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
351                 .containsKey(Constants.DEVICE_ID));
352         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
353                 .containsKey(Constants.USER_ID));
354         assertTrue(mCbor.parsePayloadFromCbor(mReq.getPayload(), HashMap.class)
355                 .containsKey(Constants.ACCESS_TOKEN));
356         mLatch.countDown();
357     }
358
359     @Test
360     public void coapAuthHandlerUnAuthorizedExceptionChannelReadRequest()
361             throws Exception {
362
363         System.out.println(
364                 "\t--------------coapAuthHandler UnAuthorizedException ChannelReadRequest Test------------");
365
366         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
367                 OICConstants.ACCOUNT_SESSION_FULL_URI + "/" + "errorURI", null,
368                 null, null);
369         mCoapAuthHandler.channelRead(mCtx, request);
370         assertEquals(mRes.getStatus(), ResponseStatus.UNAUTHORIZED);
371     }
372
373     @Test
374     public void coapAuthHandlerAccountSessionChannelReadResponse()
375             throws Exception {
376         System.out.println(
377                 "\t--------------coapAuthHandler AccountSession ChannelReadResponse Test------------");
378
379         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
380                 OICConstants.ACCOUNT_SESSION_FULL_URI, null, null, null);
381         HashMap<String, Object> payloadData = new HashMap<>();
382         payloadData.put(Constants.EXPIRES_IN, 3300);
383         IResponse response = MessageBuilder.createResponse(request,
384                 ResponseStatus.CHANGED, ContentFormat.APPLICATION_CBOR,
385                 mCbor.encodingPayloadToCbor(payloadData));
386         ChannelPromise channelPromise = null;
387         mCoapAuthHandler.write(mCtx, response, channelPromise);
388         assertEquals(((IRequest) mRes).getUriPath(),
389                 OICConstants.ACCOUNT_SESSION_FULL_URI);
390         assertTrue(mCbor.parsePayloadFromCbor(mRes.getPayload(), HashMap.class)
391                 .containsKey(Constants.EXPIRES_IN));
392     }
393
394     @Test
395     public void coapAuthHandlerUnAuthorizedExceptionChannelReadResponse()
396             throws Exception {
397         System.out.println(
398                 "\t--------------coapAuthHandler UnAuthorizedException ChannelReadResponse Test------------");
399
400         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
401                 OICConstants.ACCOUNT_SESSION_FULL_URI, null, null, null);
402         HashMap<String, Object> payloadData = new HashMap<>();
403         payloadData.put(Constants.EXPIRES_IN, -1);
404         IResponse response = MessageBuilder.createResponse(request,
405                 ResponseStatus.UNAUTHORIZED, ContentFormat.APPLICATION_CBOR,
406                 mCbor.encodingPayloadToCbor(payloadData));
407         ChannelPromise channelPromise = null;
408         mCoapAuthHandler.write(mCtx, response, channelPromise);
409         assertEquals(mRes.getStatus(), ResponseStatus.UNAUTHORIZED);
410     }
411
412     @Test
413     public void coapAuthHandlerCSMSignaling() throws Exception {
414
415         System.out.println(
416                 "\t--------------coapAuthHandler coapAuthHandlerCSMSignaling Test------------");
417         ISignaling signal = MessageBuilder.createSignaling(SignalingMethod.CSM);
418         CoapSignaling signaling = (CoapSignaling) signal;
419         signaling.setCsmBlockWiseTransfer(true);
420         signaling.setCsmMaxMessageSize(1124);
421         signaling.setCsmServerName("default_server_name");
422         mCoapSignalingHandler.channelRead(mCtxSignal, signal);
423         assertEquals(mSig.getSignalingMethod(), SignalingMethod.CSM);
424     }
425
426     @Test
427     public void CoapLifecycleHandlerChannelReadRequest()
428             throws InterruptedException {
429         System.out.println(
430                 "\t--------------CoapLifecycleHandler ChannelReadCoapRequest Test------------");
431
432         mCoapLifecycleHandler.channelRead(mCtx,
433                 MessageBuilder.createRequest(RequestMethod.GET, null, null));
434         assertTrue(mLatch.await(1L, SECONDS));
435     }
436
437     @Test
438     public void CoapLifecycleHandlerUnAuthorizedExceptionChannelReadRequest()
439             throws Exception {
440         System.out.println(
441                 "\t--------------CoapLifecycleHandler ChannelReadCoapRequest Test------------");
442         Channel channel = mock(Channel.class);
443         Attribute<Device> attribute = mock(Attribute.class);
444         Mockito.doReturn(channel).when(mCtx).channel();
445         Mockito.doReturn(attribute).when(channel).attr(Mockito.any());
446         Mockito.doReturn(mMockDevice).when(attribute).get();
447         Mockito.doReturn(true).when(mMockDevice).isExpiredTime();
448         ChannelId channelId = mock(ChannelId.class);
449         Mockito.doReturn(channelId).when(channel).id();
450         Mockito.doReturn(
451                 "0000000141f3edcfc2c3000000000001d0000000000000000000000000000000000000")
452                 .when(channelId).asLongText();
453         mCoapLifecycleHandler.channelRead(mCtx,
454                 MessageBuilder.createRequest(RequestMethod.GET, null, null));
455         assertEquals(mRes.getStatus(), ResponseStatus.UNAUTHORIZED);
456     }
457
458     @Test
459     public void CoapLifecycleHandlerchannelActive() throws Exception {
460         System.out.println(
461                 "\t--------------CoapLifecycleHandler ChannelReadCoapRequest    Test------------");
462         Mockito.doAnswer(new Answer<Object>() {
463             @Override
464             public CoapRequest answer(InvocationOnMock invocation)
465                     throws Throwable {
466
467                 Object[] args = invocation.getArguments();
468                 CoapRequest req = (CoapRequest) args[0];
469                 assertTrue(req.getUriPath().contains(Constants.PREFIX_OIC + "/"
470                         + Constants.DEVICE_PRESENCE_URI));
471                 assertTrue(mCbor
472                         .parsePayloadFromCbor(req.getPayload(), HashMap.class)
473                         .containsKey(Constants.PRESENCE_STATE));
474
475                 mLatch.countDown();
476                 return null;
477             }
478
479         }).when(mRequestChannel).sendRequest(Mockito.any(), Mockito.any());
480         mCoapLifecycleHandler.channelActive(mCtx);
481     }
482
483     @Test
484     public void CoapLifecycleHandlerchannelInActive() throws Exception {
485         System.out.println(
486                 "\t--------------CoapLifecycleHandler ChannelReadCoapRequest    Test------------");
487
488         Mockito.doAnswer(new Answer<Object>() {
489             @Override
490             public CoapRequest answer(InvocationOnMock invocation)
491                     throws Throwable {
492
493                 Object[] args = invocation.getArguments();
494                 CoapRequest req = (CoapRequest) args[0];
495                 assertTrue(req.getUriPath().contains(Constants.PREFIX_OIC + "/"
496                         + Constants.DEVICE_PRESENCE_URI));
497                 assertTrue(mCbor
498                         .parsePayloadFromCbor(req.getPayload(), HashMap.class)
499                         .containsKey(Constants.PRESENCE_STATE));
500
501                 mLatch.countDown();
502                 return null;
503             }
504
505         }).when(mRequestChannel).sendRequest(Mockito.any(), Mockito.any());
506         mCoapLifecycleHandler.channelInactive(mCtx);
507     }
508
509 }