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