[IOT-1604] Fix cloud routing code
[iotivity.git] / cloud / interface / src / test / java / org / iotivity / cloud / ciserver / resources / RouteResourceTest.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.resources;
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.ArrayList;
31 import java.util.HashMap;
32 import java.util.concurrent.CountDownLatch;
33
34 import org.iotivity.cloud.base.device.CoapDevice;
35 import org.iotivity.cloud.base.device.IRequestChannel;
36 import org.iotivity.cloud.base.protocols.IRequest;
37 import org.iotivity.cloud.base.protocols.IResponse;
38 import org.iotivity.cloud.base.protocols.MessageBuilder;
39 import org.iotivity.cloud.base.protocols.coap.CoapRequest;
40 import org.iotivity.cloud.base.protocols.coap.CoapResponse;
41 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
42 import org.iotivity.cloud.base.protocols.enums.RequestMethod;
43 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
44 import org.iotivity.cloud.ciserver.Constants;
45 import org.iotivity.cloud.ciserver.DeviceServerSystem;
46 import org.iotivity.cloud.ciserver.DeviceServerSystem.CoapDevicePool;
47 import org.iotivity.cloud.ciserver.resources.RouteResource.AccountReceiveHandler;
48 import org.iotivity.cloud.ciserver.resources.RouteResource.DefaultResponseHandler;
49 import org.iotivity.cloud.ciserver.resources.RouteResource.LinkInterfaceHandler;
50 import org.iotivity.cloud.util.Cbor;
51 import org.junit.Before;
52 import org.junit.Test;
53 import org.mockito.InjectMocks;
54 import org.mockito.Mock;
55 import org.mockito.Mockito;
56 import org.mockito.MockitoAnnotations;
57 import org.mockito.invocation.InvocationOnMock;
58 import org.mockito.stubbing.Answer;
59
60 public class RouteResourceTest {
61     private static final String           RELAY_URI                          = "/di";
62     private static final String           RESOURCE_URI                       = "/a/light/0";
63     private static final String           VERIFY_URI                         = "/oic/acl/verify";
64     private String                        mDiServer                          = "resourceServerId";
65     private CoapDevice                    mSourceDevice                      = mock(
66             CoapDevice.class);
67     private CoapDevice                    mTargetDevice                      = mock(
68             CoapDevice.class);
69     private IResponse                     mRes                               = null;
70     private IRequest                      mReq                               = null;
71     private DeviceServerSystem            mDeviceServerSystem                = new DeviceServerSystem();
72     private final CountDownLatch          mLatch                             = new CountDownLatch(
73             1);
74     private Cbor<HashMap<String, Object>> mCbor                              = new Cbor<>();
75     private IRequestChannel               mTargetChannel                     = mock(
76             IRequestChannel.class);
77
78     @Mock(name = "mASServer")
79     IRequestChannel                       mRequestChannelASServer;
80
81     @Mock
82     CoapDevicePool                        coapDevicePool;
83
84     @Mock
85     IRequestChannel                       requestChannel;
86
87     @InjectMocks
88     RouteResource                            diHandler                          = new RouteResource(
89             coapDevicePool);
90
91     IRequest                              requestDefault                     = makePutRequest();
92     IRequest                              requestLinkInterface               = makePutLinkInterfaceRequest();
93
94     @InjectMocks
95     LinkInterfaceHandler                  linkInterfaceHandler               = diHandler.new LinkInterfaceHandler(
96             "targetDeviceId", mSourceDevice, requestLinkInterface);
97
98     @InjectMocks
99     DefaultResponseHandler                defaultResponseHandler             = diHandler.new DefaultResponseHandler(
100             "targetDeviceId", mSourceDevice);
101
102     @InjectMocks
103     AccountReceiveHandler                 accountDefaultReceiveHandler       = diHandler.new AccountReceiveHandler(
104             mSourceDevice, requestDefault);
105
106     @InjectMocks
107     AccountReceiveHandler                 accountLinkInterfaceReceiveHandler = diHandler.new AccountReceiveHandler(
108             mSourceDevice, requestLinkInterface);
109
110     @Before
111     public void setUp() throws Exception {
112         mRes = null;
113         mReq = null;
114         Mockito.doReturn("sourceDeviceId").when(mSourceDevice).getDeviceId();
115         Mockito.doReturn("targetDeviceId").when(mTargetDevice).getDeviceId();
116         MockitoAnnotations.initMocks(this);
117         mDeviceServerSystem.addResource(diHandler);
118         Mockito.doReturn(mTargetDevice).when(coapDevicePool)
119                 .queryDevice(Mockito.anyString());
120         Mockito.doReturn(mTargetChannel).when(mTargetDevice)
121                 .getRequestChannel();
122
123         // callback mock
124         Mockito.doAnswer(new Answer<Object>() {
125             @Override
126             public CoapResponse answer(InvocationOnMock invocation)
127                     throws Throwable {
128                 Object[] args = invocation.getArguments();
129                 CoapResponse resp = (CoapResponse) args[0];
130                 mRes = resp;
131                 mLatch.countDown();
132                 return null;
133             }
134         }).when(mSourceDevice).sendResponse(Mockito.anyObject());
135         Mockito.doAnswer(new Answer<Object>() {
136             @Override
137             public CoapRequest answer(InvocationOnMock invocation)
138                     throws Throwable {
139                 Object[] args = invocation.getArguments();
140                 CoapRequest request = (CoapRequest) args[0];
141                 System.out.println(
142                         "\t----------payload : " + request.getPayloadString());
143                 System.out.println(
144                         "\t----------uripath : " + request.getUriPath());
145                 System.out.println(
146                         "\t---------uriquery : " + request.getUriQuery());
147                 mReq = request;
148                 mLatch.countDown();
149                 return null;
150             }
151         }).when(mTargetChannel).sendRequest(Mockito.any(IRequest.class),
152                 Mockito.any(CoapDevice.class));
153         Mockito.doAnswer(new Answer<Object>() {
154             @Override
155             public CoapRequest answer(InvocationOnMock invocation)
156                     throws Throwable {
157                 Object[] args = invocation.getArguments();
158                 CoapRequest request = (CoapRequest) args[0];
159                 System.out.println(
160                         "\t----------payload : " + request.getPayloadString());
161                 System.out.println(
162                         "\t----------uripath : " + request.getUriPath());
163                 System.out.println(
164                         "\t---------uriquery : " + request.getUriQuery());
165                 mReq = request;
166                 mLatch.countDown();
167                 return null;
168             }
169         }).when(mRequestChannelASServer).sendRequest(
170                 Mockito.any(IRequest.class), Mockito.any(CoapDevice.class));
171     }
172
173     @Test
174     public void testOnDefaultRequestReceived() throws InterruptedException {
175         IRequest request = makePutRequest();
176         diHandler.onDefaultRequestReceived(mSourceDevice, request);
177         assertTrue(mReq.getMethod().equals(RequestMethod.GET));
178         assertTrue(mReq.getUriPath().equals(VERIFY_URI));
179         assertTrue(mLatch.await(1L, SECONDS));
180     }
181
182     @Test
183     public void testOnDefaultResponseHandleronResponseReceived()
184             throws InterruptedException {
185         IResponse response = makeContentResponse();
186         defaultResponseHandler.onResponseReceived(response);
187         assertEquals(mRes, response);
188         assertTrue(mLatch.await(1L, SECONDS));
189     }
190
191     @Test
192     public void testOnAccountReceiveHandlerDeniedonResponseReceived()
193             throws InterruptedException {
194         IResponse response = makeVerifyDeniedContentResponse();
195         accountDefaultReceiveHandler.onResponseReceived(response);
196     }
197
198     @Test
199     public void testOnAccountReceiveHandlerDefaultonResponseReceived()
200             throws InterruptedException {
201         IResponse response = makeVerifyAllowedContentResponse();
202         accountDefaultReceiveHandler.onResponseReceived(response);
203         assertEquals(mReq, requestDefault);
204         assertTrue(mLatch.await(1L, SECONDS));
205     }
206
207     @Test
208     public void testOnLinkInterfaceResponseHandleronResponseReceived()
209             throws InterruptedException {
210         IResponse response = makeVerifyAllowedContentResponse();
211         accountLinkInterfaceReceiveHandler.onResponseReceived(response);
212         assertEquals(mReq, requestLinkInterface);
213         assertTrue(mLatch.await(1L, SECONDS));
214     }
215
216     @Test
217     public void testOnAccountReceiveHandlerLinkInterfaceonResponseReceived()
218             throws InterruptedException {
219         IResponse response = makeContentLinkResponse();
220         linkInterfaceHandler.onResponseReceived(response);
221         assertEquals(mRes, response);
222         assertTrue(mLatch.await(1L, SECONDS));
223     }
224
225     private IRequest makePutRequest() {
226         HashMap<String, Object> payloadData = new HashMap<>();
227         payloadData.put("state", true);
228         payloadData.put("power", 6);
229         IRequest request = MessageBuilder.createRequest(RequestMethod.PUT,
230                 RELAY_URI + "/" + mDiServer + RESOURCE_URI, null,
231                 ContentFormat.APPLICATION_CBOR,
232                 mCbor.encodingPayloadToCbor(payloadData));
233         return request;
234     }
235
236     private IRequest makePutLinkInterfaceRequest() {
237         HashMap<String, Object> payloadData = new HashMap<>();
238         payloadData.put("state", true);
239         payloadData.put("power", 6);
240         IRequest request = MessageBuilder.createRequest(RequestMethod.PUT,
241                 RELAY_URI + "/" + mDiServer + RESOURCE_URI,
242                 Constants.RS_INTERFACE + "=" + Constants.LINK_INTERFACE,
243                 ContentFormat.APPLICATION_CBOR,
244                 mCbor.encodingPayloadToCbor(payloadData));
245         return request;
246     }
247
248     private IResponse makeContentResponse() {
249
250         HashMap<String, Object> payloadData = new HashMap<>();
251         payloadData.put("state", true);
252         payloadData.put("power", 6);
253         IResponse response = MessageBuilder.createResponse(makeGetRequest(),
254                 ResponseStatus.CONTENT, ContentFormat.APPLICATION_CBOR,
255                 mCbor.encodingPayloadToCbor(payloadData));
256         return response;
257     }
258
259     private IResponse makeVerifyAllowedContentResponse() {
260
261         HashMap<String, Object> payloadData = new HashMap<>();
262         payloadData.put("gp", "Allowed");
263         IResponse response = MessageBuilder.createResponse(makeGetRequest(),
264                 ResponseStatus.CONTENT, ContentFormat.APPLICATION_CBOR,
265                 mCbor.encodingPayloadToCbor(payloadData));
266         return response;
267     }
268
269     private IResponse makeVerifyDeniedContentResponse() {
270
271         HashMap<String, Object> payloadData = new HashMap<>();
272         payloadData.put("gp", "Denied");
273         IResponse response = MessageBuilder.createResponse(makeGetRequest(),
274                 ResponseStatus.CONTENT, ContentFormat.APPLICATION_CBOR,
275                 mCbor.encodingPayloadToCbor(payloadData));
276         return response;
277     }
278
279     private IResponse makeContentLinkResponse() {
280         HashMap<String, Object> payloadData = new HashMap<>();
281         ArrayList<HashMap<String, Object>> linkPayload = new ArrayList<>();
282
283         payloadData.put("href", "hrefsample1");
284         linkPayload.add(payloadData);
285         linkPayload.add(payloadData);
286         linkPayload.add(payloadData);
287
288         IResponse response = MessageBuilder.createResponse(makeGetRequest(),
289                 ResponseStatus.CONTENT, ContentFormat.APPLICATION_CBOR,
290                 mCbor.encodingPayloadToCbor(linkPayload));
291         return response;
292     }
293
294     private IRequest makeGetRequest() {
295         IRequest request = MessageBuilder.createRequest(RequestMethod.PUT,
296                 RELAY_URI + "/" + mDiServer + RESOURCE_URI, null);
297         return request;
298     }
299
300 }