[IOT-1604] Fix cloud routing code
[iotivity.git] / cloud / interface / src / test / java / org / iotivity / cloud / ciserver / resources / proxy / rd / ResourceFindTest.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.proxy.rd;
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.List;
33 import java.util.concurrent.CountDownLatch;
34
35 import org.iotivity.cloud.base.device.CoapDevice;
36 import org.iotivity.cloud.base.device.IRequestChannel;
37 import org.iotivity.cloud.base.exception.ClientException;
38 import org.iotivity.cloud.base.protocols.IRequest;
39 import org.iotivity.cloud.base.protocols.IResponse;
40 import org.iotivity.cloud.base.protocols.MessageBuilder;
41 import org.iotivity.cloud.base.protocols.coap.CoapRequest;
42 import org.iotivity.cloud.base.protocols.coap.CoapResponse;
43 import org.iotivity.cloud.base.protocols.enums.ContentFormat;
44 import org.iotivity.cloud.base.protocols.enums.RequestMethod;
45 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
46 import org.iotivity.cloud.ciserver.Constants;
47 import org.iotivity.cloud.ciserver.DeviceServerSystem;
48 import org.iotivity.cloud.util.Cbor;
49 import org.junit.Before;
50 import org.junit.Test;
51 import org.mockito.InjectMocks;
52 import org.mockito.Mock;
53 import org.mockito.Mockito;
54 import org.mockito.MockitoAnnotations;
55 import org.mockito.invocation.InvocationOnMock;
56 import org.mockito.stubbing.Answer;
57
58 public class ResourceFindTest {
59     private static final String TEST_RESOURCE_FIND_URI = Constants.WELL_KNOWN_FULL_URI;
60     private String              di                     = "B371C481-38E6-4D47-8320-7688D8A5B58C";
61     private CoapDevice          mMockDevice            = mock(CoapDevice.class);
62     private IResponse           mRes                   = null;
63     private IRequest            mReq                   = null;
64     private DeviceServerSystem  mDeviceServerSystem    = new DeviceServerSystem();
65     final CountDownLatch        mLatch                 = new CountDownLatch(1);
66
67     @Mock(name = "mRDServer")
68     IRequestChannel             mRequestChannelRDServer;
69     @Mock(name = "mASServer")
70     IRequestChannel             mRequestChannelASServer;
71
72     @InjectMocks
73     private ResourceFind        mResHandler            = new ResourceFind();
74
75     @Before
76     public void setUp() throws Exception {
77         mRes = null;
78         mReq = null;
79         Mockito.doReturn("mockDeviceId").when(mMockDevice).getDeviceId();
80         Mockito.doReturn("mockUserId").when(mMockDevice).getUserId();
81         MockitoAnnotations.initMocks(this);
82         mDeviceServerSystem.addResource(mResHandler);
83         // callback mock
84         Mockito.doAnswer(new Answer<Object>() {
85             @Override
86             public CoapResponse answer(InvocationOnMock invocation)
87                     throws Throwable {
88                 Object[] args = invocation.getArguments();
89                 CoapResponse resp = (CoapResponse) args[0];
90                 mRes = resp;
91                 return resp;
92             }
93         }).when(mMockDevice).sendResponse(Mockito.anyObject());
94         Mockito.doAnswer(new Answer<Object>() {
95             @Override
96             public CoapRequest answer(InvocationOnMock invocation)
97                     throws Throwable {
98                 Object[] args = invocation.getArguments();
99                 CoapRequest request = (CoapRequest) args[0];
100                 System.out.println(
101                         "\t----------payload : " + request.getPayloadString());
102                 System.out.println(
103                         "\t----------uripath : " + request.getUriPath());
104                 System.out.println(
105                         "\t---------uriquery : " + request.getUriQuery());
106                 mReq = request;
107                 mLatch.countDown();
108                 return null;
109             }
110         }).when(mRequestChannelRDServer).sendRequest(
111                 Mockito.any(IRequest.class), Mockito.any(CoapDevice.class));
112
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(mRequestChannelASServer).sendRequest(
130                 Mockito.any(IRequest.class), Mockito.any(CoapDevice.class));
131     }
132
133     // @InjectMocks for testSpecificDeviceonResponseReceived
134     IRequest                           requestSpecificDevice = MessageBuilder
135             .createRequest(RequestMethod.GET, TEST_RESOURCE_FIND_URI,
136                     "rt=core.light;di=" + "device1");
137     @InjectMocks
138     ResourceFind.AccountReceiveHandler specificDeviceHandler = mResHandler.new AccountReceiveHandler(
139             requestSpecificDevice, mMockDevice);
140
141     @Test
142     public void testSpecificDeviceonResponseReceived()
143             throws ClientException, InterruptedException {
144         System.out.println(
145                 "\t--------------onResponseReceived(RD) Resource Find (specific deivce) Test------------");
146         IResponse response = responseFromAccountServer();
147         specificDeviceHandler.onResponseReceived(response);
148         HashMap<String, List<String>> queryMap = mReq.getUriQueryMap();
149         assertTrue(mReq.getMethod() == RequestMethod.GET);
150         assertTrue(queryMap.get("rt").contains("core.light"));
151         assertTrue(queryMap.get("di").contains("device1"));
152     }
153
154     // @InjectMocks for testEntireDeviceonResponseReceived
155     IRequest                           requestEntireDevices = MessageBuilder
156             .createRequest(RequestMethod.GET, TEST_RESOURCE_FIND_URI,
157                     "rt=core.light");
158     @InjectMocks
159     ResourceFind.AccountReceiveHandler entireDevicehandler  = mResHandler.new AccountReceiveHandler(
160             requestEntireDevices, mMockDevice);
161
162     @Test
163     public void testEntireDeviceonResponseReceived() throws ClientException {
164         System.out.println(
165                 "\t--------------onResponseReceived(RD) Resource Find (entire deivces) Test------------");
166         IResponse response = responseFromAccountServer();
167         entireDevicehandler.onResponseReceived(response);
168         HashMap<String, List<String>> queryMap = mReq.getUriQueryMap();
169         assertTrue(mReq.getMethod() == RequestMethod.GET);
170         assertTrue(queryMap.get("rt").contains("core.light"));
171         assertTrue(queryMap.get("di").contains("device1"));
172         assertTrue(queryMap.get("di").contains("device2"));
173         assertTrue(queryMap.get("di").contains("device3"));
174     }
175
176     // @InjectMocks for testEntireDeviceonResponseReceived
177     IRequest                           requestEntireDevicesNoQuery = MessageBuilder
178             .createRequest(RequestMethod.GET, TEST_RESOURCE_FIND_URI, null);
179     @InjectMocks
180     ResourceFind.AccountReceiveHandler entireDevicesNoQueryHandler = mResHandler.new AccountReceiveHandler(
181             requestEntireDevicesNoQuery, mMockDevice);
182
183     @Test
184     public void testEntireDeviceNoQueryonResponseReceived()
185             throws ClientException {
186         System.out.println(
187                 "\t--------------onResponseReceived(RD) Resource Find (entire deivces, No Query) Test------------");
188         IResponse response = responseFromAccountServer();
189         entireDevicesNoQueryHandler.onResponseReceived(response);
190         HashMap<String, List<String>> queryMap = mReq.getUriQueryMap();
191         assertTrue(mReq.getMethod() == RequestMethod.GET);
192         assertTrue(queryMap.get("di").contains("device1"));
193         assertTrue(queryMap.get("di").contains("device2"));
194         assertTrue(queryMap.get("di").contains("device3"));
195     }
196
197     @Test
198     public void testResourceFindEntireDevicesOnRequestReceived()
199             throws Exception {
200         System.out.println(
201                 "\t--------------OnRequestReceived(RD) Resource Find (entire deivces) Test------------");
202         IRequest request = MessageBuilder.createRequest(RequestMethod.GET,
203                 TEST_RESOURCE_FIND_URI, "rt=core.light");
204         mResHandler.onRequestReceived(mMockDevice, request);
205         HashMap<String, List<String>> queryMap = mReq.getUriQueryMap();
206         assertTrue(mLatch.await(1L, SECONDS));
207         assertTrue(queryMap.containsKey("uid"));
208         assertTrue(queryMap.containsKey("members"));
209         assertEquals(mReq.getUriPath(),
210                 Constants.GROUP_FULL_URI + "/mockUserId");
211     }
212
213     @Test
214     public void testResourceFindSpecificDeviceOnRequestReceived()
215             throws Exception {
216         System.out.println(
217                 "\t--------------OnRequestReceived(RD) Resource Find (specific deivce) Test------------");
218         IRequest request = MessageBuilder.createRequest(RequestMethod.GET,
219                 TEST_RESOURCE_FIND_URI, "rt=core.light;di=" + di);
220         mResHandler.onRequestReceived(mMockDevice, request);
221         HashMap<String, List<String>> queryMap = mReq.getUriQueryMap();
222         // assertion: if the request packet from the CI contains the query
223         // which includes device ID and the accesstoken
224         assertTrue(mLatch.await(1L, SECONDS));
225         assertTrue(queryMap.containsKey("di"));
226         assertEquals(mReq.getUriPath(), Constants.WELL_KNOWN_FULL_URI);
227     }
228
229     private IResponse responseFromAccountServer() {
230         // make response which has "CONTENT" status
231         Cbor<HashMap<String, Object>> cbor = new Cbor<>();
232         HashMap<String, Object> responsePayload = new HashMap<String, Object>();
233         ArrayList<String> deviceList = new ArrayList<String>();
234         // assuming that there are three devices in the response msg from the AS
235         deviceList.add("device1");
236         deviceList.add("device2");
237         deviceList.add("device3");
238         responsePayload.put("devices", deviceList);
239         responsePayload.put("gid", "g0001");
240         responsePayload.put("gmid", "u0001");
241         ArrayList<String> midList = new ArrayList<String>();
242         midList.add("u0001");
243         responsePayload.put("memebers", midList);
244         IResponse response = MessageBuilder.createResponse(requestEntireDevices,
245                 ResponseStatus.CONTENT, ContentFormat.APPLICATION_CBOR,
246                 cbor.encodingPayloadToCbor(responsePayload));
247         return response;
248     }
249 }