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