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