aboutsummaryrefslogtreecommitdiffstats
path: root/music-core/src/test/java/org/onap/music/service/impl/MusicCassaCoreTest.java
blob: 33debfaa5c33810b9158a15da71258d438d5f2b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/*******************************************************************************
 * ============LICENSE_START==========================================
 * org.onap.music
 * ===================================================================
 *  Copyright (c) 2018 AT&T Intellectual Property
 * ===================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  
 * ============LICENSE_END=============================================
 * ====================================================================
 *******************************************************************************/
package org.onap.music.service.impl;

import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.onap.music.datastore.MusicDataStore;
import org.onap.music.datastore.MusicDataStoreHandle;
import org.onap.music.datastore.PreparedQueryObject;
import org.onap.music.datastore.jsonobjects.JsonKeySpace;
import org.onap.music.datastore.jsonobjects.JsonTable;
import org.onap.music.exceptions.MusicLockingException;
import org.onap.music.exceptions.MusicQueryException;
import org.onap.music.exceptions.MusicServiceException;
import org.onap.music.lockingservice.cassandra.CassaLockStore;
import org.onap.music.lockingservice.cassandra.CassaLockStore.LockObject;
import org.onap.music.lockingservice.cassandra.LockType;
import org.onap.music.main.MusicUtil;
import org.onap.music.main.ResultType;
import org.onap.music.main.ReturnType;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;

@RunWith(MockitoJUnitRunner.class)
public class MusicCassaCoreTest {

    @Mock
    private CassaLockStore mLockHandle;

    @Mock
    private MusicDataStore dsHandle;

    @Mock
    private Session session;

    MusicCassaCore core;

    @Before
    public void before() {
        core = MusicCassaCore.getInstance();
        MusicCassaCore.setmLockHandle(mLockHandle);
        MusicDataStoreHandle.setMDstoreHandle(dsHandle);
        Mockito.when(dsHandle.getSession()).thenReturn(session);
    }

    @Test
    public void testGetmLockHandle() {
        assertEquals(mLockHandle, MusicCassaCore.getmLockHandle());
    }

    @Test
    public void testSetmLockHandle() {
        CassaLockStore m2 = Mockito.mock(CassaLockStore.class);
        MusicCassaCore.setmLockHandle(m2);
        assertEquals(m2, MusicCassaCore.getmLockHandle());
        //revert back to original handle
        MusicCassaCore.setmLockHandle(mLockHandle);
    }

    @Test
    public void testGetInstance() {
        assertEquals(core, MusicCassaCore.getInstance());
    }

    @Test
    public void testGetLockingServiceHandle() {
        assertEquals(mLockHandle, MusicCassaCore.getmLockHandle());
    }

    @Test
    public void testCreateLockReferenceAtomicString() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, null))
                .thenReturn("lockReturned");

        String lockRef = core.createLockReferenceAtomic(fullyQualifiedKey);

        Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, null);
        assertEquals("lockReturned", lockRef);
    }

    @Test
    public void testCreateLockReferenceStringString() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        String owner = "owner1";
        Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, owner))
            .thenReturn("lockReturned");
        
        String lockRef = core.createLockReference(fullyQualifiedKey, owner);

        Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, owner);
        assertEquals("lockReturned", lockRef);
    }

    @Test
    public void testCreateLockReferenceAtomicStringLockType() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, null))
                .thenReturn("lockReturned");

        String lockRef = core.createLockReferenceAtomic(fullyQualifiedKey, LockType.READ);

        Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, null);
        assertEquals("lockReturned", lockRef);
    }

    @Test
    public void testCreateLockReferenceStringLockTypeString() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        String owner = "owner1";
        Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, owner))
            .thenReturn("lockReturned");
        
        String lockRef = core.createLockReference(fullyQualifiedKey, LockType.READ, owner);

        Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, owner);
        assertEquals("lockReturned", lockRef);
    }

    @Test
    public void testPromoteLock() throws Exception {
        String lockId = "$keyspace.table.lockName$1";
        Mockito.when(mLockHandle.promoteLock("keyspace", "table", "lockName", "1"))
            .thenReturn(new ReturnType(ResultType.SUCCESS, "Lock Promoted"));
        
        ReturnType rt = core.promoteLock(lockId);
        assertEquals(ResultType.SUCCESS, rt.getResult());
        assertEquals("Lock Promoted", rt.getMessage());
    }

    @Test
    public void testAcquireLockWithLease() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        String lockId = "$keyspace.table.lockName$1";
        long leasePeriod = 1000;
        String currTime = String.valueOf(System.currentTimeMillis());
        Mockito.when(mLockHandle.peekLockQueue("keyspace", "table", "lockName"))
            .thenReturn(mLockHandle.new LockObject(true, lockId, currTime, currTime, LockType.WRITE, null));
        Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1"))
            .thenReturn(mLockHandle.new LockObject(false, lockId, null, null, LockType.WRITE, null));
        
        ReturnType rt = core.acquireLockWithLease(fullyQualifiedKey, lockId, leasePeriod);
        assertEquals(ResultType.FAILURE, rt.getResult());
    }

    @Test
    public void testAcquireLock() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        String lockId = "$keyspace.table.lockName$1";
        Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1"))
            .thenReturn(mLockHandle.new LockObject(false, lockId, null, null, LockType.WRITE, null));
        
        ReturnType rt = core.acquireLock(fullyQualifiedKey, lockId);
        
        assertEquals(ResultType.FAILURE, rt.getResult());
        Mockito.verify(mLockHandle).getLockInfo("keyspace", "table", "lockName", "1");
        /*TODO: if we successfully acquire the lock we hit an error by trying to read MusicDatastoreHandle */
    }

    @Test
    public void testWhoseTurnIsIt() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        Mockito.when(mLockHandle.peekLockQueue("keyspace", "table", "lockName"))
            .thenReturn(mLockHandle.new LockObject(true, "1", "", "", LockType.WRITE, null));
        
        String topOfQ = core.whoseTurnIsIt(fullyQualifiedKey);
        System.out.println(topOfQ);
        
        assertEquals("$"+fullyQualifiedKey+"$1", topOfQ);
    }

    @Test
    public void testGetCurrentLockHolders() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        List<String> currentHolders = new ArrayList<>();
        currentHolders.add("$"+fullyQualifiedKey+"$1");
        currentHolders.add("$"+fullyQualifiedKey+"$2");
        Mockito.when(mLockHandle.getCurrentLockHolders("keyspace", "table", "lockName"))
            .thenReturn(currentHolders);

        List<String> holders = core.getCurrentLockHolders(fullyQualifiedKey);
        
        assertTrue(currentHolders.containsAll(holders) && holders.containsAll(currentHolders));
    }

    @Test
    public void testGetLockNameFromId() {
        String lockId = "$keyspace.table.lockName$1";
        assertEquals("keyspace.table.lockName", core.getLockNameFromId(lockId));
    }

    @Test
    public void testDestroyLockRefString() throws Exception {
        String lockId = "$keyspace.table.lockName$1";

        core.destroyLockRef(lockId);
        Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
    }

    @Test
    public void testDestroyLockRefStringString() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        String lockReference = "1";
        
        core.destroyLockRef(fullyQualifiedKey, lockReference);
        Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
    }

    @Test
    public void testReleaseLock() throws Exception {
        String lockId = "$keyspace.table.lockName$1";
        
        core.releaseLock(lockId, true);
        
        Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
    }

    @Test
    public void testVoluntaryReleaseLock() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        String lockReference = "1";
        
        core.voluntaryReleaseLock(fullyQualifiedKey, lockReference);
        
        Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
    }

    @Test
    public void testReleaseAllLocksForOwner() throws Exception {
        List<String> ownersLocks = new ArrayList<>();
        ownersLocks.add("lockName$1");
        ownersLocks.add("lockName$2");
        Mockito.when(mLockHandle.getAllLocksForOwner("ownerId", "keyspace", "table"))
            .thenReturn(ownersLocks);
        
        List<String> locksReleased = core.releaseAllLocksForOwner("ownerId", "keyspace", "table");
        
        Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
        Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "2", MusicUtil.getRetryCount());
        assertTrue(ownersLocks.containsAll(locksReleased) && locksReleased.containsAll(ownersLocks));
    }


    @Test
    public void testValidateLock() {
        String lockId = "$keyspace.table.lockName$1";
        
        assertFalse(core.validateLock(lockId).containsKey("Error"));
    }

    @Test
    public void testGetLockQueue() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        List<String> myList = new ArrayList<>();
        Mockito.when(mLockHandle.getLockQueue("keyspace", "table", "lockName"))
            .thenReturn(myList);
        List<String> theirList = core.getLockQueue(fullyQualifiedKey);
        
        assertEquals(myList, theirList);
    }

    @Test
    public void testGetLockQueueSize() throws Exception {
        String fullyQualifiedKey = "keyspace.table.lockName";
        Mockito.when(mLockHandle.getLockQueueSize("keyspace", "table", "lockName"))
            .thenReturn((long) 23);
        long theirSize = core.getLockQueueSize(fullyQualifiedKey);
        
        assertEquals(23, theirSize);
    }

    @Test
    public void testCreateTable() throws MusicServiceException, MusicQueryException {
        String keyspaceName = "keyspace";
        String tableName = "table";
        JsonTable table = new JsonTable();
        table.setTableName(tableName);
        table.setKeyspaceName(keyspaceName);
        Map<String, String> fields = new HashMap<>();
        fields.put("employee", "text");
        fields.put("salary", "int");
        table.setFields(fields);
        table.setPrimaryKey("employee");

        Mockito.when(mLockHandle.createLockQueue(Mockito.matches(keyspaceName), Mockito.matches(tableName)))
                .thenReturn(true);
        Mockito.when(dsHandle.executePut(Mockito.any(PreparedQueryObject.class), Mockito.matches("eventual"))).thenReturn(true);
        ResultType rs = core.createTable(table , "eventual");

        assertEquals(ResultType.SUCCESS, rs);
    }

    @Test
    public void testDropTable() throws MusicServiceException, MusicQueryException {
        String keyspaceName = "keyspace";
        String tableName = "table";
        JsonTable table = new JsonTable();
        table.setTableName(tableName);
        table.setKeyspaceName(keyspaceName);

        ArgumentCaptor<PreparedQueryObject> queryCaptor = ArgumentCaptor.forClass(PreparedQueryObject.class);
        Mockito.when(dsHandle.executePut(queryCaptor.capture(), Mockito.matches("eventual"))).thenReturn(true);

        ResultType rs = core.dropTable(table, "eventual");
        assertEquals(ResultType.SUCCESS, rs);
        assertEquals("DROP TABLE  keyspace.table;", queryCaptor.getValue().getQuery());
    }

    @Test
    public void testQuorumGet() throws MusicServiceException, MusicQueryException {
        PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES;");
        ResultSet rs = Mockito.mock(ResultSet.class);
        Mockito.when(dsHandle.executeQuorumConsistencyGet(Mockito.same(query))).thenReturn(rs);
        ResultSet returnedRs = core.quorumGet(query);

        assertEquals(rs, returnedRs);
    }

    @Test
    public void testForciblyReleaseLock() throws MusicServiceException, MusicQueryException, MusicLockingException {
        String fullyQualifiedKey = "keyspace.table.lockName";
        ArgumentCaptor<PreparedQueryObject> unsyncedQuery = ArgumentCaptor.forClass(PreparedQueryObject.class);
        Mockito.doReturn(true).when(dsHandle).executePut(unsyncedQuery.capture(), Mockito.matches("critical"));
        core.forciblyReleaseLock(fullyQualifiedKey, "123");

        assertEquals("insert into keyspace.unsyncedKeys_table (key) values (?);",unsyncedQuery.getValue().getQuery());
    }

    @Test
    public void testEventualPut() throws MusicServiceException, MusicQueryException {
        PreparedQueryObject query = new PreparedQueryObject("INSERT INTO EMPLOYEES VALUES ('John', 1);");
        Mockito.when(dsHandle.executePut(Mockito.same(query), Mockito.matches("eventual"))).thenReturn(true);

        assertEquals(ResultType.SUCCESS, core.eventualPut(query).getResult());
    }

    @Test
    public void testEventualPutNB() throws MusicServiceException, MusicQueryException {
        String keyspace = "keyspace";
        String table = "EMPLOYEES";
        String primaryKey = "NAME";
        PreparedQueryObject query = new PreparedQueryObject("INSERT INTO EMPLOYEES VALUES ('John', 1);");

        ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
        ResultSet rs = Mockito.mock(ResultSet.class);
        Row row = Mockito.mock(Row.class);
        Mockito.when(dsHandle.executeQuorumConsistencyGet(queryCapture.capture())).thenReturn(rs);
        Mockito.when(rs.one()).thenReturn(row);

        Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true);

        ReturnType rt = core.eventualPut_nb(query, keyspace, table, primaryKey);

        assertEquals("SELECT guard FROM keyspace.lockq_EMPLOYEES WHERE key = ? ;",
                queryCapture.getAllValues().get(0).getQuery());
        assertEquals("INSERT INTO EMPLOYEES VALUES ('John', 1);", queryCapture.getAllValues().get(1).getQuery());

        assertEquals(ResultType.SUCCESS, rt.getResult());
    }

    @Test
    public void testCriticalPut() throws MusicServiceException, MusicQueryException {
        String keyspace = "keyspace";
        String table = "table";
        String primaryKey = "lockName";
        PreparedQueryObject query = new PreparedQueryObject("INSERT INTO TABLE VALUES ('John', 1);");
        String lockId = "$keyspace.table.lockName$1";

        Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1"))
            .thenReturn(mLockHandle.new LockObject(true, lockId, null, null, LockType.WRITE, null));

        ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
        Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("critical"))).thenReturn(true);
        ReturnType rt = core.criticalPut(keyspace, table, primaryKey, query, lockId, null);

        assertEquals(true, queryCapture.getValue().getQuery()
                .startsWith("INSERT INTO TABLE VALUES ('John', 1) USING TIMESTAMP"));
        assertEquals(ResultType.SUCCESS, rt.getResult());
    }

    @Test
    public void testNonKeyRelatedPut() throws MusicServiceException, MusicQueryException {
        PreparedQueryObject query = new PreparedQueryObject("INSERT INTO TABLE VALUES ('John', 1);");
        String consistency = "eventual";
        ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
        Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches(consistency))).thenReturn(true);

        core.nonKeyRelatedPut(query, consistency);

        assertEquals(query.getQuery(), queryCapture.getValue().getQuery());
    }

    @Test
    public void testGet() throws MusicServiceException, MusicQueryException {
        PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES;");
        ResultSet rs = Mockito.mock(ResultSet.class);
        Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.same(query))).thenReturn(rs);
        assertEquals(rs, core.get(query));
    }

    @Test
    public void testCriticalGet() throws MusicServiceException, MusicQueryException {
        String keyspace = "keyspace";
        String table = "table";
        String primaryKey = "lockName";
        PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES WHERE LOCKNAME='lockName';");
        String lockId = "$keyspace.table.lockName$1";

        Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1"))
            .thenReturn(mLockHandle.new LockObject(true, lockId, null, null, LockType.WRITE, null));

        ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
        ResultSet rs = Mockito.mock(ResultSet.class);
        Mockito.when(dsHandle.executeQuorumConsistencyGet(queryCapture.capture())).thenReturn(rs);
        assertEquals(rs, core.criticalGet(keyspace, table, primaryKey, query, lockId));
    }

    @Test
    public void testCreateKeyspace() throws MusicServiceException, MusicQueryException {
        String keyspace = "cycling";
        JsonKeySpace ks = new JsonKeySpace();
        ks.setKeyspaceName(keyspace);
        ks.setDurabilityOfWrites("true");

        Map<String, Object> replicationInfo = new HashMap<>();
        replicationInfo.put("class", "SimpleStrategy");
        replicationInfo.put("replication_factor", 1);
        ks.setReplicationInfo(replicationInfo);
        Map<String, String> consistencyInfo = new HashMap<>();
        consistencyInfo.put("consistency", "quorum");
        ks.setConsistencyInfo(consistencyInfo);

        ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
        Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true);

        core.createKeyspace(ks , "eventual");

        assertEquals("CREATE KEYSPACE cycling WITH replication = {'replication_factor':1,'class':'SimpleStrategy'} AND durable_writes = true;",
                queryCapture.getValue().getQuery());
    }

    @Test
    public void testDropKeyspace() throws MusicServiceException, MusicQueryException {
        String keyspace = "cycling";
        JsonKeySpace ks = new JsonKeySpace();
        ks.setKeyspaceName(keyspace);

        ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
        Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true);

        core.dropKeyspace(ks , "eventual");

        assertEquals("DROP KEYSPACE cycling;", queryCapture.getValue().getQuery());
    }
}