61cefac07e2df23fd9b856d2d1d830bfea9bd376
[platform/upstream/iotivity.git] /
1
2 /*
3  * //******************************************************************
4  * //
5  * // Copyright 2016 Samsung Electronics All Rights Reserved.
6  * //
7  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
8  * //
9  * // Licensed under the Apache License, Version 2.0 (the "License");
10  * // you may not use this file except in compliance with the License.
11  * // You may obtain a copy of the License at
12  * //
13  * //      http://www.apache.org/licenses/LICENSE-2.0
14  * //
15  * // Unless required by applicable law or agreed to in writing, software
16  * // distributed under the License is distributed on an "AS IS" BASIS,
17  * // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * // See the License for the specific language governing permissions and
19  * // limitations under the License.
20  * //
21  * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
22  */
23 package org.iotivity.cloud.accountserver.resources.acl.group;
24
25 import static java.util.concurrent.TimeUnit.SECONDS;
26 import static org.junit.Assert.assertTrue;
27 import static org.mockito.Mockito.mock;
28
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.concurrent.CountDownLatch;
32
33 import org.iotivity.cloud.accountserver.Constants;
34 import org.iotivity.cloud.accountserver.db.MongoDB;
35 import org.iotivity.cloud.base.device.CoapDevice;
36 import org.iotivity.cloud.base.exception.ServerException;
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.Observe;
44 import org.iotivity.cloud.base.protocols.enums.RequestMethod;
45 import org.iotivity.cloud.base.protocols.enums.ResponseStatus;
46 import org.iotivity.cloud.util.Cbor;
47 import org.junit.After;
48 import org.junit.Before;
49 import org.junit.Test;
50 import org.mockito.Mockito;
51 import org.mockito.MockitoAnnotations;
52 import org.mockito.invocation.InvocationOnMock;
53 import org.mockito.stubbing.Answer;
54
55 public class GroupResourceTest {
56     private static final String           GROUP_URI         = Constants.GROUP_FULL_URI;
57     private final String                  mUserUuid         = "bc38f243-aab5-44d3-8eb9-4a54ebbaf359";
58     private String                        mGroupId          = null;
59     final CountDownLatch                  mLatch            = new CountDownLatch(
60             1);
61     private CoapDevice                    mMockDevice       = Mockito
62             .mock(CoapDevice.class);
63     private Cbor<HashMap<String, Object>> mCbor             = new Cbor<>();
64     private IResponse                     mResponse         = null;
65     private IResponse                     mResponseObserver = null;
66     private GroupResource                 mGroupResource    = new GroupResource();
67
68     @Before
69     public void setUp() throws Exception {
70         MockitoAnnotations.initMocks(this);
71         // reset data base
72         resetDB();
73         Mockito.doAnswer(new Answer<Object>() {
74             @Override
75             public CoapResponse answer(InvocationOnMock invocation)
76                     throws Throwable {
77                 Object[] args = invocation.getArguments();
78                 CoapResponse resp = (CoapResponse) args[0];
79                 System.out.println(
80                         "\t----------payload : " + resp.getPayloadString());
81                 System.out.println("\t---------method : " + resp.getStatus());
82                 mResponse = resp;
83                 if (mGroupId == null) {
84                     HashMap<String, Object> payloadData = mCbor
85                             .parsePayloadFromCbor(resp.getPayload(),
86                                     HashMap.class);
87                     if (payloadData.containsKey("gid")) {
88                         mGroupId = (String) payloadData.get("gid");
89                     }
90                 }
91                 mLatch.countDown();
92                 return null;
93             }
94         }).when(mMockDevice).sendResponse(Mockito.anyObject());
95     }
96
97     @After
98     public void resetAccountDatabase() throws Exception {
99         MongoDB mongoDB = new MongoDB(Constants.DB_NAME);
100         mongoDB.createTable(Constants.USER_TABLE);
101         mongoDB.createTable(Constants.TOKEN_TABLE);
102         mongoDB.createTable(Constants.GROUP_TABLE);
103     }
104
105     @Test
106     public void testCreateGroup() throws Exception {
107         getTestMethodName();
108         createGroup(mMockDevice, mUserUuid + "create", "Public");
109         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
110         assertTrue(hashmapCheck(mResponse, "gid"));
111         assertTrue(mLatch.await(2L, SECONDS));
112     }
113
114     @Test
115     public void testFindMyGroup() throws Exception {
116         getTestMethodName();
117         String uuid = this.mUserUuid + "find";
118         createGroup(mMockDevice, uuid, "Public");
119         findGroup(mMockDevice, uuid);
120         assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
121         assertTrue(hashmapCheck(mResponse, "gidlist"));
122         assertTrue(mLatch.await(2L, SECONDS));
123     }
124
125     @Test(expected = ServerException.BadRequestException.class)
126     public void testCreateGroupNotSupportedType() throws Exception {
127         getTestMethodName();
128         String uuid = this.mUserUuid + "delete";
129         createGroup(mMockDevice, uuid, "NotSupported");
130         deleteGroup(mMockDevice, uuid);
131     }
132
133     @Test
134     public void testDeleteGroup() throws Exception {
135         getTestMethodName();
136         String uuid = this.mUserUuid + "delete";
137         createGroup(mMockDevice, uuid, "Public");
138         deleteGroup(mMockDevice, uuid);
139         assertTrue(methodCheck(mResponse, ResponseStatus.DELETED));
140         assertTrue(mLatch.await(2L, SECONDS));
141     }
142
143     @Test(expected = ServerException.PreconditionFailedException.class)
144     public void testDeleteGroupWithoutGid() throws Exception {
145         getTestMethodName();
146         String uuid = this.mUserUuid + "delete";
147         createGroup(mMockDevice, uuid, "Public");
148         deleteGroupWithoutGid(mMockDevice, uuid);
149     }
150
151     @Test
152     public void testAddDeviceAndUserToGroup() throws Exception {
153         getTestMethodName();
154         String uuid = this.mUserUuid + "AddDeviceAndUser";
155         createGroup(mMockDevice, uuid, "Public");
156         ArrayList<String> midList = new ArrayList<>();
157         midList.add("member0001");
158         midList.add("member0002");
159         ArrayList<String> diList = new ArrayList<>();
160         diList.add("device0001");
161         diList.add("device0002");
162         addDeviceAndUser(mMockDevice, midList, diList);
163     }
164
165     @Test
166     public void testDeleteDeviceAndUserToGroup() throws Exception {
167         getTestMethodName();
168         String uuid = this.mUserUuid + "AddDeviceAndUser";
169         createGroup(mMockDevice, uuid, "Public");
170         ArrayList<String> midList = new ArrayList<>();
171         midList.add("member0001");
172         midList.add("member0002");
173         ArrayList<String> diList = new ArrayList<>();
174         diList.add("device0001");
175         diList.add("device0002");
176         addDeviceAndUser(mMockDevice, midList, diList);
177         deleteDeviceAndUser(mMockDevice, midList, diList);
178     }
179
180     @Test(expected = ServerException.BadRequestException.class)
181     public void testDeleteGroupInvalidGmid() throws Exception {
182         getTestMethodName();
183         String uuid = this.mUserUuid + "delete";
184         createGroup(mMockDevice, uuid, "Public");
185         deleteGroup(mMockDevice, uuid + "invlidGmid");
186     }
187
188     @Test
189     public void testJoinToinvitedGroup() throws Exception {
190         getTestMethodName();
191         String uuid = this.mUserUuid + "join";
192         createGroup(mMockDevice, uuid, "Public");
193         joinGroup(mMockDevice, "u0002");
194         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
195         assertTrue(mLatch.await(2L, SECONDS));
196     }
197
198     @Test
199     public void testObserveGroup() throws Exception {
200         getTestMethodName();
201         String uuid = this.mUserUuid + "obs";
202         createGroup(mMockDevice, uuid, "Public");
203         observeGroup(mMockDevice, uuid);
204         assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
205         assertTrue(hashmapCheck(mResponse, "gid"));
206         assertTrue(hashmapCheck(mResponse, "gmid"));
207         assertTrue(hashmapCheck(mResponse, "midlist"));
208         assertTrue(hashmapCheck(mResponse, "dilist"));
209         assertTrue(mLatch.await(2L, SECONDS));
210     }
211
212     @Test
213     public void testObserveDeregisterGroup() throws Exception {
214         getTestMethodName();
215         String uuid = this.mUserUuid + "obs";
216         createGroup(mMockDevice, uuid, "Public");
217         observeGroup(mMockDevice, uuid);
218         observeDeregisterGroup(mMockDevice, uuid);
219         assertTrue(methodCheck(mResponse, ResponseStatus.CONTENT));
220     }
221
222     @Test
223     public void testShareDeviceIntoGroup() throws Exception {
224         getTestMethodName();
225         String uuid = this.mUserUuid + "share";
226         createGroup(mMockDevice, uuid, "Public");
227         shareDevice(mMockDevice, "d0002");
228         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
229         assertTrue(mLatch.await(2L, SECONDS));
230     }
231
232     @Test
233     public void testShareDeviceNotification() throws Exception {
234         getTestMethodName();
235         String uuid = this.mUserUuid + "share";
236         String uuidGuest = "u0002guest";
237         CoapDevice mockDeviceGuest = mock(CoapDevice.class);
238         CountDownLatch memberLatch = new CountDownLatch(1);
239         Mockito.doAnswer(new Answer<Object>() {
240             @Override
241             public CoapResponse answer(InvocationOnMock invocation)
242                     throws Throwable {
243                 Object[] args = invocation.getArguments();
244                 CoapResponse resp = (CoapResponse) args[0];
245                 System.out.println("\t----------new member payload : "
246                         + resp.getPayloadString());
247                 System.out.println(
248                         "\t---------new member method : " + resp.getStatus());
249                 memberLatch.countDown();
250                 mResponseObserver = resp;
251                 return resp;
252             }
253         }).when(mockDeviceGuest).sendResponse(Mockito.anyObject());
254         createGroup(mMockDevice, uuid, "Public");
255         joinGroup(mockDeviceGuest, uuidGuest);
256         observeGroup(mockDeviceGuest, uuidGuest);
257         shareDevice(mMockDevice, "d0002");
258         // assertion for the group master
259         assertTrue(methodCheck(mResponse, ResponseStatus.CHANGED));
260         // assertion for the observer
261         assertTrue(methodCheck(mResponseObserver, ResponseStatus.CONTENT));
262         assertTrue(mLatch.await(2L, SECONDS));
263         assertTrue(memberLatch.await(2L, SECONDS));
264     }
265
266     public void addDeviceAndUser(CoapDevice device, ArrayList<String> midList,
267             ArrayList<String> diList) throws Exception {
268         HashMap<String, Object> payloadData = new HashMap<>();
269         payloadData.put("midlist", midList);
270         payloadData.put("dilist", diList);
271         IRequest request = MessageBuilder.createRequest(RequestMethod.POST,
272                 GROUP_URI + "/" + mGroupId, null,
273                 ContentFormat.APPLICATION_CBOR,
274                 mCbor.encodingPayloadToCbor(payloadData));
275         System.out.println("-----add Device and User : " + payloadData);
276         mGroupResource.onDefaultRequestReceived(device, request);
277     }
278
279     public void deleteDeviceAndUser(CoapDevice device,
280             ArrayList<String> midList, ArrayList<String> diList)
281             throws Exception {
282         String midListString = "";
283         String didListString = "";
284         for (String mid : midList) {
285             midListString += "midlist=";
286             midListString += mid;
287             midListString += ";";
288         }
289         for (String di : diList) {
290             didListString += "dilist=";
291             didListString += di;
292             didListString += ";";
293         }
294         System.out.println("-----delete Device and User, Query: "
295                 + midListString + didListString);
296         IRequest request = MessageBuilder.createRequest(RequestMethod.DELETE,
297                 GROUP_URI + "/" + mGroupId, midListString + didListString);
298         mGroupResource.onDefaultRequestReceived(device, request);
299     }
300
301     private void shareDevice(CoapDevice device, String deviceId)
302             throws Exception {
303         System.out.println("-----Share Device");
304         IRequest request = null;
305         request = createShareDeviceRequest(deviceId);
306         mGroupResource.onDefaultRequestReceived(device, request);
307     }
308
309     private void createGroup(CoapDevice device, String gmid, String gtype)
310             throws Exception {
311         System.out.println("-----Create Group");
312         IRequest request = null;
313         request = createGroupRequest(gmid, gtype);
314         mGroupResource.onDefaultRequestReceived(device, request);
315     }
316
317     private void findGroup(CoapDevice device, String uuid) throws Exception {
318         System.out.println("-----Find Group");
319         IRequest request = null;
320         request = findGroupRequest(uuid);
321         mGroupResource.onDefaultRequestReceived(device, request);
322     }
323
324     private void observeDeregisterGroup(CoapDevice device, String uuid)
325             throws Exception {
326         System.out.println("-----Observe Deregister Group");
327         IRequest request = null;
328         request = observeDeregisterGroupRequest(uuid);
329         mGroupResource.onDefaultRequestReceived(device, request);
330     }
331
332     private void observeGroup(CoapDevice device, String uuid) throws Exception {
333         System.out.println("-----Observe Group");
334         IRequest request = null;
335         request = observeGroupRequest(uuid);
336         mGroupResource.onDefaultRequestReceived(device, request);
337     }
338
339     private void joinGroup(CoapDevice device, String uuid) throws Exception {
340         System.out.println("-----Join Group");
341         IRequest request = null;
342         request = joinGroupRequest(uuid);
343         mGroupResource.onDefaultRequestReceived(device, request);
344     }
345
346     private void deleteGroup(CoapDevice device, String uuid) throws Exception {
347         System.out.println("-----Delete Group");
348         IRequest request = null;
349         request = deleteGroupRequest(uuid);
350         mGroupResource.onDefaultRequestReceived(device, request);
351     }
352
353     private void deleteGroupWithoutGid(CoapDevice device, String uuid)
354             throws Exception {
355         System.out.println("-----Delete Group");
356         IRequest request = null;
357         request = deleteGroupWithoutGidRequest(uuid);
358         mGroupResource.onDefaultRequestReceived(device, request);
359     }
360
361     private IRequest deleteGroupWithoutGidRequest(String uuid) {
362         IRequest request = null;
363         request = MessageBuilder.createRequest(RequestMethod.DELETE, GROUP_URI,
364                 "gmid=" + uuid);
365         return request;
366     }
367
368     private IRequest deleteGroupRequest(String uuid) {
369         IRequest request = null;
370         request = MessageBuilder.createRequest(RequestMethod.DELETE, GROUP_URI,
371                 "gid=" + mGroupId + ";" + "gmid=" + uuid);
372         return request;
373     }
374
375     private IRequest findGroupRequest(String uuid) {
376         IRequest request = null;
377         request = MessageBuilder.createRequest(RequestMethod.GET, GROUP_URI,
378                 "mid=" + uuid);
379         return request;
380     }
381
382     private IRequest createShareDeviceRequest(String deviceId) {
383         IRequest request = null;
384         HashMap<String, Object> payloadData = new HashMap<String, Object>();
385         ArrayList<String> diList = new ArrayList<>();
386         diList.add(deviceId);
387         payloadData.put("dilist", diList);
388         request = MessageBuilder.createRequest(RequestMethod.POST,
389                 GROUP_URI + "/" + mGroupId, null,
390                 ContentFormat.APPLICATION_CBOR,
391                 mCbor.encodingPayloadToCbor(payloadData));
392         return request;
393     }
394
395     private IRequest observeDeregisterGroupRequest(String uuid) {
396         IRequest request = null;
397         request = MessageBuilder.createRequest(RequestMethod.GET,
398                 GROUP_URI + "/" + mGroupId, "mid=" + uuid);
399         ((CoapRequest) request).setObserve(Observe.UNSUBSCRIBE);
400         return request;
401     }
402
403     private IRequest observeGroupRequest(String uuid) {
404         IRequest request = null;
405         request = MessageBuilder.createRequest(RequestMethod.GET,
406                 GROUP_URI + "/" + mGroupId, "mid=" + uuid);
407         ((CoapRequest) request).setObserve(Observe.SUBSCRIBE);
408         return request;
409     }
410
411     private IRequest joinGroupRequest(String uuid) {
412         IRequest request = null;
413         HashMap<String, Object> payloadData = new HashMap<String, Object>();
414         ArrayList<String> midList = new ArrayList<>();
415         midList.add(uuid);
416         payloadData.put("midlist", midList);
417         request = MessageBuilder.createRequest(RequestMethod.POST,
418                 GROUP_URI + "/" + mGroupId, null,
419                 ContentFormat.APPLICATION_CBOR,
420                 mCbor.encodingPayloadToCbor(payloadData));
421         return request;
422     }
423
424     private IRequest createGroupRequest(String uuid, String gtype) {
425         IRequest request = null;
426         HashMap<String, Object> payloadData = new HashMap<String, Object>();
427         payloadData.put("gmid", uuid);
428         payloadData.put("gtype", gtype);
429         request = MessageBuilder.createRequest(RequestMethod.POST, GROUP_URI,
430                 null, ContentFormat.APPLICATION_CBOR,
431                 mCbor.encodingPayloadToCbor(payloadData));
432         return request;
433     }
434
435     private boolean hashmapCheck(IResponse response, String propertyName) {
436         HashMap<String, Object> payloadData = mCbor
437                 .parsePayloadFromCbor(response.getPayload(), HashMap.class);
438         if (payloadData.containsKey(propertyName))
439             return true;
440         else
441             return false;
442     }
443
444     private boolean methodCheck(IResponse response,
445             ResponseStatus responseStatus) {
446         if (responseStatus == response.getStatus())
447             return true;
448         else
449             return false;
450     }
451
452     private void getTestMethodName() {
453         StackTraceElement[] stacks = new Throwable().getStackTrace();
454         StackTraceElement currentStack = stacks[1];
455         System.out.println("\t---Test Name : " + currentStack.getMethodName());
456     }
457
458     public void resetDB() throws Exception {
459         MongoDB mongoDB = new MongoDB(Constants.DB_NAME);
460         mongoDB.deleteTable(Constants.GROUP_TABLE);
461         mongoDB.createTable(Constants.GROUP_TABLE);
462         mongoDB.deleteTable(Constants.USER_TABLE);
463         mongoDB.createTable(Constants.USER_TABLE);
464         mongoDB.deleteTable(Constants.TOKEN_TABLE);
465         mongoDB.createTable(Constants.TOKEN_TABLE);
466     }
467 }