diff options
Diffstat (limited to 'src/test/java/org')
17 files changed, 3851 insertions, 0 deletions
diff --git a/src/test/java/org/onap/aai/cacher/common/MongoHelperSingletonNoFakeTest.java b/src/test/java/org/onap/aai/cacher/common/MongoHelperSingletonNoFakeTest.java new file mode 100644 index 0000000..1a086bc --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/common/MongoHelperSingletonNoFakeTest.java @@ -0,0 +1,490 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.common; + +import com.google.gson.JsonParser; +import com.mongodb.DB; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.UpdateOptions; +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodProcess; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.IMongodConfig; +import de.flapdoodle.embed.mongo.config.MongoCmdOptionsBuilder; +import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; +import org.bson.Document; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.*; +import org.onap.aai.cacher.dmaap.consumer.AAIDmaapEventProcessorScenariosTest; +import org.onap.aai.cacher.model.CacheEntry; +import org.onap.aai.cacher.model.DBAction; +import org.skyscreamer.jsonassert.JSONAssert; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + + +public class MongoHelperSingletonNoFakeTest { + + private static final String DB_NAME = AAIDmaapEventProcessorScenariosTest.class.getSimpleName(); + private static MongoDatabase mongoDatabase; + private static DB db; + private static MongodProcess mongod; + private static MongoClient mongoC; + + private MongoHelperSingleton mongoHelperSingleton; + private JsonParser parser = new JsonParser(); + + + @BeforeClass + public static void setup() throws IOException, InterruptedException { + + String bindIp = "localhost"; + int port = 27017; + startEmbedded(port); + + mongoC = new MongoClient(bindIp, port); + mongoDatabase = mongoC.getDatabase(DB_NAME); + db = mongoC.getDB(DB_NAME); + + } + + protected static void startEmbedded(int port) throws IOException { + IMongodConfig mongoConfigConfig = new MongodConfigBuilder() + .version(Version.Main.PRODUCTION) + .net(new Net(port, Network.localhostIsIPv6())) + .cmdOptions(new MongoCmdOptionsBuilder().verbose(true).build()) + .configServer(false) + .build(); + + MongodExecutable mongodExecutable = MongodStarter.getDefaultInstance().prepare(mongoConfigConfig); + + mongod = mongodExecutable.start(); + } + + @AfterClass + public static void tearDown() { + if (mongod != null && mongod.isProcessRunning()) { + mongod.stop(); + } + } + + @Before + public void init() { + mongoHelperSingleton = new MongoHelperSingleton(db, mongoDatabase); + } + + @After + public void cleanup() { + final List<String> collectionNames = new ArrayList<>(); + mongoDatabase.listCollections().iterator().forEachRemaining(document -> collectionNames.add(document.getString("name"))); + collectionNames.stream().forEach(collectionName -> mongoDatabase.getCollection(collectionName).drop()); + } + + + private MongoCollection<Document> setupCollection(String collectionName) { + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'}"); + Document obj = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1','hostname':'testPserver_1'," + + "'p-interfaces':{'p-interface':[" + + "{'interface-name':'interface-1','l-interfaces':{'l-interface':[{'interface-name':'l-interface-1','test':'test'}]}}," + + "{'interface-name':'interface-2'}" + + "]}}"); + collection.replaceOne(findQuery, obj, new UpdateOptions().upsert(true)); + + + findQuery = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'}"); + obj = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2','hostname':'testPserver_2'," + + "'p-interfaces':{'p-interface':[" + + "{'interface-name':'interface-1','l-interfaces':{'l-interface':[{'interface-name':'l-interface-1'}]}}," + + "{'interface-name':'interface-2'}" + + "]}}"); + collection.replaceOne(findQuery, obj, new UpdateOptions().upsert(true)); + + findQuery = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_99'}"); + obj = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_99','hostname':'testPserver_99'," + + "'p-interfaces':{'p-interface':[" + + "{'interface-name':'interface-1','l-interfaces':{'l-interface':[{'interface-name':'l-interface-1','l3-interface-ipv4-address-list':[{'l3-interface-ipv4-address':'address'}]}]}}," + + "{'interface-name':'interface-2'}" + + "]}}"); + collection.replaceOne(findQuery, obj, new UpdateOptions().upsert(true)); + + assertEquals("Pre " + collectionName + " test: collection contains 3 documents", 3L, collection.count()); + + return collection; + } + + @Test + public void getNestedObjectAddressList() throws JSONException { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_99'," + + "'hostname':'testPserver_99'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.l3-interface-ipv4-address-list.l3-interface-ipv4-address':'address'}"; + CacheEntry ce = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .isNested(true) + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()).build(); + + Optional<Document> nested = mongoHelperSingleton.getObject(ce); + + assertTrue(nested.isPresent()); + + JSONAssert.assertEquals( + new JSONObject("{'l3-interface-ipv4-address':'address'}"), + new JSONObject(nested.get().toJson()), + true); + + + } + + @Test + public void getNestedObject() throws JSONException { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_99'," + + "'hostname':'testPserver_99'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-1'}"; + CacheEntry ce = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .isNested(true) + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()).build(); + + Optional<Document> nested = mongoHelperSingleton.getObject(ce); + + assertTrue(nested.isPresent()); + JSONAssert.assertEquals( + new JSONObject("{'interface-name':'l-interface-1','l3-interface-ipv4-address-list':[{'l3-interface-ipv4-address':'address'}]}"), + new JSONObject(nested.get().toJson()), + true); + + } + + @Test + public void insertNewTop() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(false) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_3") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_3'}").getAsJsonObject()) + .withPayload(parser.parse("{'hostname':'testPserver_1'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 4 document", 4L, collection.count()); + + } + + @Test + public void insertNewNested() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-NEW'}"; + Document nestedFind = Document.parse(nestedFindString); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_1") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'}").getAsJsonObject()) + .withPayload(parser.parse("{'interface-name':'interface-NEW'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'interface-NEW'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + + } + + @Test + public void insertNewTwoNested() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-NEW'}"; + Document nestedFind = Document.parse(nestedFindString); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_1") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}").getAsJsonObject()) + .withPayload(parser.parse("{'interface-name':'l-interface-NEW','new-field':'NEW'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface.$.l-interfaces.l-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'l-interface-NEW'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + + } + + @Test + public void insertNewThreeNested() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.vlans.vlan.vlan-interface':'vlan-NEW'}"; + Document nestedFind = Document.parse(nestedFindString); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_1") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-1'}").getAsJsonObject()) + .withPayload(parser.parse("{'vlan-interface':'vlan-NEW','new-field':'NEW4'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface.$.l-interfaces.l-interface.$.vlans.vlan") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'vlan-interface':'vlan-NEW'}").getAsJsonObject()) + .build(); + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + + } + + + @Test + public void insertExstingNested() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}"; + Document nestedFind = Document.parse(nestedFindString); + + String newNestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.new-field':'NEW'}"; + Document newNestedFind = Document.parse(newNestedFindString); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_1") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'}").getAsJsonObject()) + .withPayload(parser.parse("{'interface-name':'interface-1','new-field':'NEW'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'interface-1'}").getAsJsonObject()) + .build(); + + assertEquals("Pre " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested property", 1L, collection.count(newNestedFind)); + + } + + @Test + public void replaceTop() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + + MongoCollection<Document> collection = setupCollection(collectionName); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(false) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_2") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'}").getAsJsonObject()) + .withPayload(parser.parse("{'hostname':'testPserver_2','new-property':'NEW'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 3 document", 3L, collection.count()); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new property", + 1L, + collection.count(Document.parse("{'new-property':'NEW'}"))); + + + } + + @Test + public void deleteTopLevel() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.DELETE) + .isNested(false) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_2") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.delete(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 2 document", 2L, collection.count()); + + } + + @Test + public void deleteNestedOneLevel() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}"; + Document nestedFind = Document.parse(nestedFindString); + + assertEquals("Pre " + collectionName + " test: collection contains 1 document with filter", + 1L, + collection.count(nestedFind)); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.DELETE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_2") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'interface-1'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.delete(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 0 document", + 0L, + collection.count(nestedFind)); + + } + + @Test + public void deleteNestedTwoLevel() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-1'}"; + Document nestedFind = Document.parse(nestedFindString); + + assertEquals("Pre " + collectionName + " test: collection contains 1 document with filter", + 1L, + collection.count(nestedFind)); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.DELETE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_2") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface.$.l-interfaces.l-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'l-interface-1'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.delete(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 0 document", + 0L, + collection.count(nestedFind)); + + + } + + //TODO delete non existent top + + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/cacher/common/MongoHelperSingletonTest.java b/src/test/java/org/onap/aai/cacher/common/MongoHelperSingletonTest.java new file mode 100644 index 0000000..872f099 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/common/MongoHelperSingletonTest.java @@ -0,0 +1,417 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.common; + +import com.github.fakemongo.Fongo; +import com.google.gson.JsonParser; +import com.mongodb.DB; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.UpdateOptions; +import org.bson.Document; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.aai.cacher.model.CacheEntry; +import org.onap.aai.cacher.model.DBAction; +import org.skyscreamer.jsonassert.JSONAssert; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class MongoHelperSingletonTest { + + private static final String DB_NAME = "testDb"; + private static MongoDatabase mongoDatabase; + private static DB db; + private MongoHelperSingleton mongoHelperSingleton; + private JsonParser parser = new JsonParser(); + + + @BeforeClass + public static void setup() { + Fongo fongo = new Fongo(DB_NAME); + mongoDatabase = fongo.getDatabase(DB_NAME); + db = fongo.getDB(DB_NAME); + } + + @Before + public void init() { + mongoHelperSingleton = new MongoHelperSingleton(db, mongoDatabase); + } + + @After + public void cleanup() { + final List<String> collectionNames = new ArrayList<>(); + mongoDatabase.listCollections().iterator().forEachRemaining(document -> collectionNames.add(document.getString("name"))); + collectionNames.stream().forEach(collectionName -> mongoDatabase.getCollection(collectionName).drop()); + } + + private MongoCollection<Document> setupCollection(String collectionName) { + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'}"); + Document obj = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1','hostname':'testPserver_1'," + + "'p-interfaces':{'p-interface':[" + + "{'interface-name':'interface-1','l-interfaces':{'l-interface':[{'interface-name':'l-interface-1','test':'test'}]}}," + + "{'interface-name':'interface-2'}" + + "]}}"); + collection.replaceOne(findQuery, obj, new UpdateOptions().upsert(true)); + + + findQuery = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'}"); + obj = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2','hostname':'testPserver_2'," + + "'p-interfaces':{'p-interface':[" + + "{'interface-name':'interface-1','l-interfaces':{'l-interface':[{'interface-name':'l-interface-1'}]}}," + + "{'interface-name':'interface-2'}" + + "]}}"); + collection.replaceOne(findQuery, obj, new UpdateOptions().upsert(true)); + + findQuery = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_99'}"); + obj = Document.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_99','hostname':'testPserver_99'," + + "'p-interfaces':{'p-interface':[" + + "{'interface-name':'interface-1','l-interfaces':{'l-interface':[{'interface-name':'l-interface-1','l3-interface-ipv4-address-list':[{'l3-interface-ipv4-address':'address'}]}]}}," + + "{'interface-name':'interface-2'}" + + "]}}"); + collection.replaceOne(findQuery, obj, new UpdateOptions().upsert(true)); + + assertEquals("Pre " + collectionName + " test: collection contains 3 documents", 3L, collection.count()); + + return collection; + } + + @Test + public void getNestedObjectAddressList() throws JSONException { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_99'," + + "'hostname':'testPserver_99'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.l3-interface-ipv4-address-list.l3-interface-ipv4-address':'address'}"; + CacheEntry ce = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .isNested(true) + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()).build(); + + Optional<Document> nested = mongoHelperSingleton.getObject(ce); + + assertTrue(nested.isPresent()); + + JSONAssert.assertEquals( + new JSONObject("{'l3-interface-ipv4-address':'address'}"), + new JSONObject(nested.get().toJson()), + true); + + + } + + @Test + public void getNestedObject() throws JSONException { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_99'," + + "'hostname':'testPserver_99'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-1'}"; + CacheEntry ce = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .isNested(true) + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()).build(); + + Optional<Document> nested = mongoHelperSingleton.getObject(ce); + + assertTrue(nested.isPresent()); + JSONAssert.assertEquals( + new JSONObject("{'interface-name':'l-interface-1','l3-interface-ipv4-address-list':[{'l3-interface-ipv4-address':'address'}]}"), + new JSONObject(nested.get().toJson()), + true); + } + + @Test + public void insertNewTop() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + setupCollection(collectionName); + + MongoCollection<Document> collection = setupCollection(collectionName); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(false) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_3") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_3'}").getAsJsonObject()) + .withPayload(parser.parse("{'hostname':'testPserver_1'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 4 document", 4L, collection.count()); + + } + + @Test + public void insertNewNested() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + setupCollection(collectionName); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-NEW'}"; + Document nestedFind = Document.parse(nestedFindString); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_1") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'}").getAsJsonObject()) + .withPayload(parser.parse("{'interface-name':'interface-NEW'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'interface-NEW'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + + } + + @Test + public void insertNewTwoNested() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + setupCollection(collectionName); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-NEW'}"; + Document nestedFind = Document.parse(nestedFindString); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_1") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}").getAsJsonObject()) + .withPayload(parser.parse("{'interface-name':'l-interface-NEW','new-field':'NEW'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface.$.l-interfaces.l-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'l-interface-NEW'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + + } + + + @Test + public void insertExstingNested() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + setupCollection(collectionName); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}"; + Document nestedFind = Document.parse(nestedFindString); + + String newNestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.new-field':'NEW'}"; + Document newNestedFind = Document.parse(newNestedFindString); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_1") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'}").getAsJsonObject()) + .withPayload(parser.parse("{'interface-name':'interface-1','new-field':'NEW'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'interface-1'}").getAsJsonObject()) + .build(); + + assertEquals("Pre " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested", 1L, collection.count(nestedFind)); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new nested property", 1L, collection.count(newNestedFind)); + + } + + @Test + public void replaceTop() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + setupCollection(collectionName); + + MongoCollection<Document> collection = setupCollection(collectionName); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.INSERT_REPLACE) + .isNested(false) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_2") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'}").getAsJsonObject()) + .withPayload(parser.parse("{'hostname':'testPserver_2','new-property':'NEW'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.insertReplace(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 3 document", 3L, collection.count()); + assertEquals("Post " + collectionName + " test: collection contains 1 document with new property", + 1L, + collection.count(Document.parse("{'new-property':'NEW'}"))); + + + } + + @Test + public void deleteTopLevel() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.DELETE) + .isNested(false) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_2") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.delete(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 2 document", 2L, collection.count()); + + } + + @Test + public void deleteNestedOneLevel() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}"; + Document nestedFind = Document.parse(nestedFindString); + + assertEquals("Pre " + collectionName + " test: collection contains 1 document with filter", + 1L, + collection.count(nestedFind)); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.DELETE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_2") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'interface-1'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.delete(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 0 document", + 0L, + collection.count(nestedFind)); + + } + + @Test + public void deleteNestedTwoLevel() throws Exception { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + MongoCollection<Document> collection = setupCollection(collectionName); + + String nestedFindString = "{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_1'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'l-interface-1'}"; + Document nestedFind = Document.parse(nestedFindString); + + assertEquals("Pre " + collectionName + " test: collection contains 1 document with filter", + 1L, + collection.count(nestedFind)); + + CacheEntry cacheEntry = CacheEntry.CacheEntryBuilder.createCacheEntry() + .inCollection(collectionName) + .withDbAction(DBAction.DELETE) + .isNested(true) + .withId("/cloud-infrastructure/pservers/pserver/testPserver_2") + .withFindQuery(parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/testPserver_2'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}").getAsJsonObject()) + .withNestedField("p-interfaces.p-interface.$.l-interfaces.l-interface") + .withNestedFind(parser.parse(nestedFindString).getAsJsonObject()) + .withNestedFieldIdentifierObj(parser.parse("{'interface-name':'l-interface-1'}").getAsJsonObject()) + .build(); + + assertTrue(mongoHelperSingleton.delete(cacheEntry)); + assertEquals("Post " + collectionName + " test: collection contains 0 document", + 0L, + collection.count(nestedFind)); + + } + + //TODO delete non existent top + + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIDmaapEventProcessorScenariosTest.java b/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIDmaapEventProcessorScenariosTest.java new file mode 100644 index 0000000..2c01f5a --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIDmaapEventProcessorScenariosTest.java @@ -0,0 +1,496 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.dmaap.consumer; + +import com.google.gson.JsonParser; +import com.mongodb.DB; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodProcess; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.IMongodConfig; +import de.flapdoodle.embed.mongo.config.MongoCmdOptionsBuilder; +import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; +import org.apache.commons.io.IOUtils; +import org.bson.Document; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.aai.cacher.common.MongoHelperSingleton; +import org.onap.aai.cacher.injestion.parser.InjestionTestComponent; +import org.onap.aai.cacher.injestion.parser.PayloadParserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import static junit.framework.TestCase.assertFalse; +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@Configuration +@ContextConfiguration(classes = {InjestionTestComponent.class, AAIDmaapEventProcessorScenariosTest.class}) +public class AAIDmaapEventProcessorScenariosTest { + + private static final String DB_NAME = AAIDmaapEventProcessorScenariosTest.class.getSimpleName(); + private static MongoDatabase mongoDb; + private static DB db; + private static MongodProcess mongod; + private static MongoClient mongoC; + + private JsonParser parser = new JsonParser(); + + @Autowired + private AAIDmaapEventProcessor aaiDmaapEventProcessor; + + @Bean + public DB db() { + return db; + } + + @Bean + public MongoDatabase mongoDatabase() { + return mongoDb; + } + + @Bean + public MongoHelperSingleton mongoHelperSingleton(DB db, MongoDatabase mongoDb) { + return new MongoHelperSingleton(db, mongoDb); + } + + @Bean + public AAIDmaapEventProcessor aaiDmaapEventProcessor(MongoHelperSingleton mongoHelperSingleton, PayloadParserService payloadParserService) { + return new AAIDmaapEventProcessor(mongoHelperSingleton, payloadParserService); + } + + @BeforeClass + public static void setup() throws IOException, InterruptedException { + + String bindIp = "localhost"; + int port = 27017; + startEmbedded(port); + + mongoC = new MongoClient(bindIp, port); + mongoDb = mongoC.getDatabase(DB_NAME); + db = mongoC.getDB(DB_NAME); + + } + + protected static void startEmbedded(int port) throws IOException { + IMongodConfig mongoConfigConfig = new MongodConfigBuilder() + .version(Version.Main.PRODUCTION) + .net(new Net(port, Network.localhostIsIPv6())) + .cmdOptions(new MongoCmdOptionsBuilder().verbose(true).build()) + .configServer(false) + .build(); + + MongodExecutable mongodExecutable = MongodStarter.getDefaultInstance().prepare(mongoConfigConfig); + + mongod = mongodExecutable.start(); + } + + @AfterClass + public static void tearDown() { + if (mongod != null && mongod.isProcessRunning()) { + mongod.stop(); + } + } + + @After + public void cleanup() { + final List<String> collectionNames = new ArrayList<>(); + mongoDb.listCollections().iterator().forEachRemaining(document -> collectionNames.add(document.getString("name"))); + collectionNames.forEach(collectionName -> mongoDb.getCollection(collectionName).drop()); + } + + + @Test + public void createPserverCreateCRWithNestingAndRelationshipsToTest() throws Exception { + String pserverCreate = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false}}"; + + aaiDmaapEventProcessor.process(pserverCreate); + assertNotEquals("pserver collection exists", mongoDatabase().getCollection("pserver"), null); + assertEquals("pserver collection contains 1", mongoDatabase().getCollection("pserver").count(), 1); + assertTrue("pserver collection contains the pserver in the event", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'" + + "}")) + .iterator().hasNext() + ); + assertFalse("pserver should not have relationship to vserver", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1'" + + "}")) + .iterator().hasNext() + ); + assertFalse("pserver should not have relationship to l-interface", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1'" + + "}")) + .iterator().hasNext() + ); + + + String crWithNestingAndWithRels = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'cloud-region','top-entity-type':'cloud-region','entity-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'3d567832-df00-49b5-b862-4d3a341dbec1','source-name':'JUNIT','version':'v13','timestamp':'20180515-10:57:55:750'},'entity':{'tenants':{'tenant':[{'vservers':{'vserver':[{'relationship-list':{'relationship':[{'related-to':'pserver','relationship-data':[{'relationship-value':'pserver-1','relationship-key':'pserver.hostname'}],'related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','relationship-label':'tosca.relationships.HostedOn'}]},'l-interfaces':{'l-interface':[{'interface-name':'l-int-1','interface-id':'l-int-1','l3-interface-ipv4-address-list':[{'neutron-network-id':'93fb399c-9bfc-4234-b2bb-a76eda38f117','neutron-subnet-id':'79e5bb69-24bb-4ea3-8d1d-c04fca5f5e1e','l3-interface-ipv4-address':'192.168.70.3'}],'relationship-list':{'relationship':[{'related-to':'pserver','relationship-data':[{'relationship-value':'pserver-1','relationship-key':'pserver.hostname'}],'related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','relationship-label':'tosca.relationships.HostedOn'}]}}]},'vserver-id':'vserver-1'}]},'tenant-id':'tenenat-1'}]},'cloud-owner':'onap-cloud-owner','cloud-region-id':'mtn6'}}"; + + aaiDmaapEventProcessor.process(crWithNestingAndWithRels); + + assertNotEquals("cloud-region collection exists", mongoDatabase().getCollection("cloud-region"), null); + assertTrue("Now pserver has relationship to vserver", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1'" + + "}")) + .iterator().hasNext() + ); + assertTrue("Now pserver has relationship to l-interface", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1'" + + "}")) + .iterator().hasNext() + ); + } + + + @Test + public void createCRWithNestingCreatePserverRelationshipsToNestedTest() throws Exception { + String crWithNesting = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'cloud-region','top-entity-type':'cloud-region','entity-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'3d567832-df00-49b5-b862-4d3a341dbec1','source-name':'JUNIT','version':'v13','timestamp':'20180515-10:57:55:750'},'entity':{'tenants':{'tenant':[{'vservers':{'vserver':[{'l-interfaces':{'l-interface':[{'interface-name':'l-int-1','interface-id':'l-int-1','l3-interface-ipv4-address-list':[{'neutron-network-id':'93fb399c-9bfc-4234-b2bb-a76eda38f117','neutron-subnet-id':'79e5bb69-24bb-4ea3-8d1d-c04fca5f5e1e','l3-interface-ipv4-address':'192.168.70.3'}]}]},'vserver-id':'vserver-1'}]},'tenant-id':'tenenat-1'}]},'cloud-owner':'onap-cloud-owner','cloud-region-id':'mtn6'}}"; + + aaiDmaapEventProcessor.process(crWithNesting); + + assertNotEquals("cloud-region collection exists", mongoDatabase().getCollection("cloud-region"), null); + + String pserverWithRelsToNested = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false,'relationship-list':{'relationship':[{'related-to':'vserver','relationship-label':'tosca.relationships.HostedOn','related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1','relationship-data':[{'relationship-key':'cloud-region.cloud-owner','relationship-value':'onap-cloud-owner'},{'relationship-key':'cloud-region.cloud-region-id','relationship-value':'mtn6'},{'relationship-key':'tenant.tenant-id','relationship-value':'tenenat-1'},{'relationship-key':'vserver.vserver-id','relationship-value':'vserver-1'}]},{'related-to':'l-interface','relationship-label':'tosca.relationships.HostedOn','related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1','relationship-data':[{'relationship-key':'cloud-region.cloud-owner','relationship-value':'onap-cloud-owner'},{'relationship-key':'cloud-region.cloud-region-id','relationship-value':'mtn6'},{'relationship-key':'tenant.tenant-id','relationship-value':'tenenat-1'},{'relationship-key':'vserver.vserver-id','relationship-value':'vserver-1'},{'relationship-key':'l-interface.interface-name','relationship-value':'l-int-1'}]}]}}}"; + + aaiDmaapEventProcessor.process(pserverWithRelsToNested); + assertTrue("Now cloud-region->tenant->vserver now has relationship to pserver", + mongoDatabase().getCollection("cloud-region") + .find(Document.parse("{" + + "'cloud-owner':'onap-cloud-owner'," + + "'cloud-region-id':'mtn6'," + + "'tenants.tenant.tenant-id':'tenenat-1'," + + "'tenants.tenant.vservers.vserver.vserver-id':'vserver-1'," + + "'tenants.tenant.vservers.vserver.relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1'" + + "}")) + .iterator().hasNext() + ); + assertTrue("Now cloud-region->tenant->vserver->l-interface now has relationship to pserver", + mongoDatabase().getCollection("cloud-region") + .find(Document.parse("{" + + "'cloud-owner':'onap-cloud-owner'," + + "'cloud-region-id':'mtn6'," + + "'tenants.tenant.tenant-id':'tenenat-1'," + + "'tenants.tenant.vservers.vserver.vserver-id':'vserver-1'," + + "'tenants.tenant.vservers.vserver.l-interfaces.l-interface.interface-name':'l-int-1'," + + "'tenants.tenant.vservers.vserver.relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1'" + + "}")) + .iterator().hasNext() + ); + } + + @Ignore + @Test + public void createPserverCreateCRWithNestingAndRelsToUpdateRemovingARelTest() throws Exception { + String pserverCreate = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false}}"; + + aaiDmaapEventProcessor.process(pserverCreate); + assertNotEquals("pserver collection exists", mongoDatabase().getCollection("pserver"), null); + assertEquals("pserver collection contains 1", mongoDatabase().getCollection("pserver").count(), 1); + assertTrue("pserver collection contains the pserver in the event", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'" + + "}")) + .iterator().hasNext() + ); + assertFalse("pserver should not have relationship to vserver", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1'" + + "}")) + .iterator().hasNext() + ); + assertFalse("pserver should not have relationship to l-interface", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1'" + + "}")) + .iterator().hasNext() + ); + + + String crWithNestingAndWithRels = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'cloud-region','top-entity-type':'cloud-region','entity-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'3d567832-df00-49b5-b862-4d3a341dbec1','source-name':'JUNIT','version':'v13','timestamp':'20180515-10:57:55:750'},'entity':{'tenants':{'tenant':[{'vservers':{'vserver':[{'relationship-list':{'relationship':[{'related-to':'pserver','relationship-data':[{'relationship-value':'pserver-1','relationship-key':'pserver.hostname'}],'related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','relationship-label':'tosca.relationships.HostedOn'}]},'l-interfaces':{'l-interface':[{'interface-name':'l-int-1','interface-id':'l-int-1','l3-interface-ipv4-address-list':[{'neutron-network-id':'93fb399c-9bfc-4234-b2bb-a76eda38f117','neutron-subnet-id':'79e5bb69-24bb-4ea3-8d1d-c04fca5f5e1e','l3-interface-ipv4-address':'192.168.70.3'}],'relationship-list':{'relationship':[{'related-to':'pserver','relationship-data':[{'relationship-value':'pserver-1','relationship-key':'pserver.hostname'}],'related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','relationship-label':'tosca.relationships.HostedOn'}]}}]},'vserver-id':'vserver-1'}]},'tenant-id':'tenenat-1'}]},'cloud-owner':'onap-cloud-owner','cloud-region-id':'mtn6'}}"; + + aaiDmaapEventProcessor.process(crWithNestingAndWithRels); + + assertNotEquals("cloud-region collection exists", mongoDatabase().getCollection("cloud-region"), null); + assertTrue("Now pserver has relationship to vserver", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1'" + + "}")) + .iterator().hasNext() + ); + assertTrue("Now pserver has relationship to l-interface", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1'" + + "}")) + .iterator().hasNext() + ); + + + String updatePserverWithoutInterfaceRel = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'UPDATE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false,'relationship-list':{'relationship':[{'related-to':'vserver','relationship-label':'tosca.relationships.HostedOn','related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1','relationship-data':[{'relationship-key':'cloud-region.cloud-owner','relationship-value':'onap-cloud-owner'},{'relationship-key':'cloud-region.cloud-region-id','relationship-value':'mtn6'},{'relationship-key':'tenant.tenant-id','relationship-value':'tenenat-1'},{'relationship-key':'vserver.vserver-id','relationship-value':'vserver-1'}]}]}}}"; + + aaiDmaapEventProcessor.process(updatePserverWithoutInterfaceRel); + + assertTrue("Now cloud-region->tenant->vserver should still have relationship to pserver", + mongoDatabase().getCollection("cloud-region") + .find(Document.parse("{" + + "'cloud-owner':'onap-cloud-owner'," + + "'cloud-region-id':'mtn6'," + + "'tenants.tenant.tenant-id':'tenenat-1'," + + "'tenants.tenant.vservers.vserver.vserver-id':'vserver-1'," + + "'tenants.tenant.vservers.vserver.relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1'" + + "}")) + .iterator().hasNext() + ); + assertFalse("Now cloud-region->tenant->vserver->l-interface should not have relationship to pserver", + mongoDatabase().getCollection("cloud-region") + .find(Document.parse("{" + + "'cloud-owner':'onap-cloud-owner'," + + "'cloud-region-id':'mtn6'," + + "'tenants.tenant.tenant-id':'tenenat-1'," + + "'tenants.tenant.vservers.vserver.vserver-id':'vserver-1'," + + "'tenants.tenant.vservers.vserver.l-interfaces.l-interface.interface-name':'l-int-1'," + + "'tenants.tenant.vservers.vserver.l-interfaces.l-interface.relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1'" + + "}")) + .iterator().hasNext() + ); + } + + @Test + public void createPserverCreateCRWithNestingAndRelationshipsToThenDeletePserverTest() throws Exception { + String pserverCreate = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false}}"; + + aaiDmaapEventProcessor.process(pserverCreate); + assertNotEquals("pserver collection exists", mongoDatabase().getCollection("pserver"), null); + assertEquals("pserver collection contains 1", mongoDatabase().getCollection("pserver").count(), 1); + assertTrue("pserver collection contains the pserver in the event", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'" + + "}")) + .iterator().hasNext() + ); + assertFalse("pserver should not have relationship to vserver", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1'" + + "}")) + .iterator().hasNext() + ); + assertFalse("pserver should not have relationship to l-interface", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1'" + + "}")) + .iterator().hasNext() + ); + + + String crWithNestingAndWithRels = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'cloud-region','top-entity-type':'cloud-region','entity-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'3d567832-df00-49b5-b862-4d3a341dbec1','source-name':'JUNIT','version':'v13','timestamp':'20180515-10:57:55:750'},'entity':{'tenants':{'tenant':[{'vservers':{'vserver':[{'relationship-list':{'relationship':[{'related-to':'pserver','relationship-data':[{'relationship-value':'pserver-1','relationship-key':'pserver.hostname'}],'related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','relationship-label':'tosca.relationships.HostedOn'}]},'l-interfaces':{'l-interface':[{'interface-name':'l-int-1','interface-id':'l-int-1','l3-interface-ipv4-address-list':[{'neutron-network-id':'93fb399c-9bfc-4234-b2bb-a76eda38f117','neutron-subnet-id':'79e5bb69-24bb-4ea3-8d1d-c04fca5f5e1e','l3-interface-ipv4-address':'192.168.70.3'}],'relationship-list':{'relationship':[{'related-to':'pserver','relationship-data':[{'relationship-value':'pserver-1','relationship-key':'pserver.hostname'}],'related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','relationship-label':'tosca.relationships.HostedOn'}]}}]},'vserver-id':'vserver-1'}]},'tenant-id':'tenenat-1'}]},'cloud-owner':'onap-cloud-owner','cloud-region-id':'mtn6'}}"; + + aaiDmaapEventProcessor.process(crWithNestingAndWithRels); + + assertNotEquals("cloud-region collection exists", mongoDatabase().getCollection("cloud-region"), null); + assertTrue("Now pserver has relationship to vserver", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1'" + + "}")) + .iterator().hasNext() + ); + assertTrue("Now pserver has relationship to l-interface", + mongoDatabase().getCollection("pserver") + .find(Document.parse("{" + + "'hostname':'pserver-1'," + + "'relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1'" + + "}")) + .iterator().hasNext() + ); + + String pserverDelete = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'DELETE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false,'relationship-list':{'relationship':[{'related-to':'vserver','relationship-label':'tosca.relationships.HostedOn','related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1','relationship-data':[{'relationship-key':'cloud-region.cloud-owner','relationship-value':'onap-cloud-owner'},{'relationship-key':'cloud-region.cloud-region-id','relationship-value':'mtn6'},{'relationship-key':'tenant.tenant-id','relationship-value':'tenenat-1'},{'relationship-key':'vserver.vserver-id','relationship-value':'vserver-1'}]},{'related-to':'l-interface','relationship-label':'tosca.relationships.HostedOn','related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1','relationship-data':[{'relationship-key':'cloud-region.cloud-owner','relationship-value':'onap-cloud-owner'},{'relationship-key':'cloud-region.cloud-region-id','relationship-value':'mtn6'},{'relationship-key':'tenant.tenant-id','relationship-value':'tenenat-1'},{'relationship-key':'vserver.vserver-id','relationship-value':'vserver-1'},{'relationship-key':'l-interface.interface-name','relationship-value':'l-int-1'}]}]}}}"; + + aaiDmaapEventProcessor.process(pserverDelete); + assertNotEquals("pserver collection exists", mongoDatabase().getCollection("pserver"), null); + assertEquals("pserver collection contains 1", mongoDatabase().getCollection("pserver").count(), 0); + + assertFalse("Now cloud-region->tenant->vserver should not have relationship to pserver", + mongoDatabase().getCollection("cloud-region") + .find(Document.parse("{" + + "'cloud-owner':'onap-cloud-owner'," + + "'cloud-region-id':'mtn6'," + + "'tenants.tenant.tenant-id':'tenenat-1'," + + "'tenants.tenant.vservers.vserver.vserver-id':'vserver-1'," + + "'tenants.tenant.vservers.vserver.relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1'" + + "}")) + .iterator().hasNext() + ); + assertFalse("Now cloud-region->tenant->vserver->l-interface should not have relationship to pserver", + mongoDatabase().getCollection("cloud-region") + .find(Document.parse("{" + + "'cloud-owner':'onap-cloud-owner'," + + "'cloud-region-id':'mtn6'," + + "'tenants.tenant.tenant-id':'tenenat-1'," + + "'tenants.tenant.vservers.vserver.vserver-id':'vserver-1'," + + "'tenants.tenant.vservers.vserver.l-interfaces.l-interface.interface-name':'l-int-1'," + + "'tenants.tenant.vservers.vserver.l-interfaces.l-interface.relationship-list.relationship.related-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1'" + + "}")) + .iterator().hasNext() + ); + + } + + + @Test + public void createPserverRelationshipsToNonExistingTest() throws Exception { + + String pserverWithRelsToNested = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false,'relationship-list':{'relationship':[{'related-to':'cloud-region','relationship-label':'tosca.relationships.HostedOn','related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6','relationship-data':[{'relationship-key':'cloud-region.cloud-owner','relationship-value':'onap-cloud-owner'},{'relationship-key':'cloud-region.cloud-region-id','relationship-value':'mtn6'}]},{'related-to':'vserver','relationship-label':'tosca.relationships.HostedOn','related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1','relationship-data':[{'relationship-key':'cloud-region.cloud-owner','relationship-value':'onap-cloud-owner'},{'relationship-key':'cloud-region.cloud-region-id','relationship-value':'mtn6'},{'relationship-key':'tenant.tenant-id','relationship-value':'tenenat-1'},{'relationship-key':'vserver.vserver-id','relationship-value':'vserver-1'}]},{'related-to':'l-interface','relationship-label':'tosca.relationships.HostedOn','related-link':'/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/mtn6/tenants/tenant/tenenat-1/vservers/vserver/vserver-1/l-interfaces/l-interface/l-int-1','relationship-data':[{'relationship-key':'cloud-region.cloud-owner','relationship-value':'onap-cloud-owner'},{'relationship-key':'cloud-region.cloud-region-id','relationship-value':'mtn6'},{'relationship-key':'tenant.tenant-id','relationship-value':'tenenat-1'},{'relationship-key':'vserver.vserver-id','relationship-value':'vserver-1'},{'relationship-key':'l-interface.interface-name','relationship-value':'l-int-1'}]}]}}}"; + + aaiDmaapEventProcessor.process(pserverWithRelsToNested); + + } + + @Test + public void linterfaceWithLinterfaceTest() throws Exception { + + String linterfaceWithLinterface = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'l-interface','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/c9e8ffb6-a360-4f9c-96c3-f5f0244dfe55-jenkins/lag-interfaces/lag-interface/8806d30d-e5f5-409e-9e9e-9b1c1943058d-jenkins/l-interfaces/l-interface/f4f9b9c7-eb83-4622-9d6f-14027a556ff5-jenkins/l-interfaces/l-interface/89796dd1-89a5-4ddc-bd13-324ba9bce3b6-jenkins','event-type':'AAI-EVENT','domain':'uINT1','action':'DELETE','sequence-number':'0','id':'9060077e-00a3-4239-80ed-855331b4d551','source-name':'FitNesse-Test-jenkins','version':'v13','timestamp':'20180625-01:24:04:857'},'entity':{'pserver-name2':'iqFmGNmNLM6','hostname':'c9e8ffb6-a360-4f9c-96c3-f5f0244dfe55-jenkins','lag-interfaces':{'lag-interface':[{'l-interfaces':{'l-interface':[{'l-interfaces':{'l-interface':[{'v6-wan-link-ip':'PuNFKRUUpd3','interface-name':'89796dd1-89a5-4ddc-bd13-324ba9bce3b6-jenkins','allowed-address-pairs':'RGo6MaADK','prov-status':'uot','macaddr':'xUj8TGre','interface-role':'SyT0hd9Uu4b','selflink':'HxDI','in-maint':false,'admin-status':'GDgD','is-port-mirrored':true,'resource-version':'1529889840462','is-ip-unnumbered':false,'network-name':'RXCo3p3p5BhBS','management-option':'jNiTd','interface-id':'4n8niH','interface-description':'drnTF3'}]},'interface-name':'f4f9b9c7-eb83-4622-9d6f-14027a556ff5-jenkins'}]},'interface-name':'8806d30d-e5f5-409e-9e9e-9b1c1943058d-jenkins'}]}}}"; + + aaiDmaapEventProcessor.process(linterfaceWithLinterface); + + } + + @Test + public void nosTest() throws Exception { + + String nos = getEventPayload("nos"); + + aaiDmaapEventProcessor.process(nos); + + } + + @Test + public void addressListTest() throws Exception { + + String event = getEventPayload("address-list"); + aaiDmaapEventProcessor.process(event); + + } + + @Test + public void vceTest() throws Exception { + + String event = getEventPayload("vce"); + aaiDmaapEventProcessor.process(event); + + } + + @Test + public void largePserverTest() throws Exception { + + String event = getEventPayload("large-pserver"); + aaiDmaapEventProcessor.process(event); + + } + + @Test + public void delRel() throws Exception { + + String event = getEventPayload("deleteRelationship/1-create-logical-link"); + aaiDmaapEventProcessor.process(event); + + event = getEventPayload("deleteRelationship/2-create-generic-vnf"); + aaiDmaapEventProcessor.process(event); + + event = getEventPayload("deleteRelationship/3-create-rel-generic-vnf-vlan-to-logical-link"); + aaiDmaapEventProcessor.process(event); + + event = getEventPayload("deleteRelationship/4-delete-rel-to-generic-vnf-vlan-from-logical-link"); + aaiDmaapEventProcessor.process(event); + + assertFalse("Now generic-vnf->l-interface->vlan should not have relationship to logical-link", + mongoDatabase().getCollection("generic-vnf") + .find(Document.parse("{" + + "'_id': '/network/generic-vnfs/generic-vnf/generic-vnf-id'," + + "'vnf-id': 'generic-vnf-id'," + + "'l-interfaces.l-interface.interface-name': 'l-interface-name-1'," + + "'l-interfaces.l-interface.vlans.vlan.vlan-interface': 'vlan-1'," + + "'l-interfaces.l-interface.vlans.vlan.relationship-list.relationship.related-link':'/aai/v13/network/logical-links/logical-link/logical-link'" + + "}")) + .iterator().hasNext()); + + } + + protected String getEventPayload(String eventpayloadName) throws IOException { + return getPayload("test/payloads/dmaapEvents/" + eventpayloadName + ".json"); + } + + private String getPayload(String filename) throws IOException { + + InputStream inputStream = getClass() + .getClassLoader() + .getResourceAsStream(filename); + + String message = String.format("Unable to find the %s in src/test/resources", filename); + assertNotNull(message, inputStream); + + return IOUtils.toString(inputStream); + } + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIDmaapEventProcessorTest.java b/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIDmaapEventProcessorTest.java new file mode 100644 index 0000000..8fcd7e2 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIDmaapEventProcessorTest.java @@ -0,0 +1,80 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.dmaap.consumer; + +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + + +public class AAIDmaapEventProcessorTest { + private AAIDmaapEventProcessor eventProcessor; + + private String validEventMessage = "{'cambria.partition': 'AAI','event-header': {'id': 'ABC','source-name': 'sourceName'},'entity': {'hostname': 'hostName'}}"; + private String invalidEventMessageHeader = "{'cambria.partition': 'AAI','Xevent-header': {'id': 'ABC','source-name': 'sourceName'},'entity': {'hostname': 'hostName'}}"; + private String invalidEventMessageHeaderMissingId = "{'cambria.partition': 'AAI','event-header': {'idX': 'ABC','source-name': 'sourceName'},'entity': {'hostname': 'hostName'}}"; + private String invalidEventMessageHeaderMissingSourceName = "{'cambria.partition': 'AAI','event-header': {'id': 'ABC','source-nameX': 'sourceName'},'entity': {'hostname': 'hostName'}}"; + private String invalidEventMessageBody = "{'cambria.partition': 'AAI','event-header': {'id': 'ABC','source-name': 'sourceName'},'Xentity': {'hostname': 'hostName'}}"; + + + @Before + public void setUp() throws Exception { + eventProcessor = new AAIDmaapEventProcessor(); + } + + @Ignore + @Test + public void testValidEventMessage() throws Exception { + eventProcessor.process(validEventMessage); + JSONObject header = eventProcessor.getEventHeader(); + JSONObject body = eventProcessor.getEventBody(); + assertEquals("header id", "ABC",header.getString("id") ); + assertEquals("hostname", "hostName",body.getString("hostname") ); + } + + @Test(expected = JSONException.class) + public void testJSONException() throws Exception { + eventProcessor.process("invalidJson"); + } + + @Test(expected = JSONException.class) + public void testInvalidHeader() throws Exception { + eventProcessor.process(invalidEventMessageHeader); + } + + @Test(expected = JSONException.class) + public void testInvalidHeaderMissingId() throws Exception { + eventProcessor.process(invalidEventMessageHeaderMissingId); + } + + @Test(expected = JSONException.class) + public void testInvalidHeaderMissingSourceName() throws Exception { + eventProcessor.process(invalidEventMessageHeaderMissingSourceName); + } + + @Test(expected = JSONException.class) + public void testInvalidEventMessageBody() throws Exception { + eventProcessor.process(invalidEventMessageBody); + } +} diff --git a/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIEventConsumerTest.java b/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIEventConsumerTest.java new file mode 100644 index 0000000..3ca3390 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/dmaap/consumer/AAIEventConsumerTest.java @@ -0,0 +1,185 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.dmaap.consumer; + +import com.att.nsa.mr.client.MRConsumer; +import com.mongodb.DB; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; + +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodProcess; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.IMongodConfig; +import de.flapdoodle.embed.mongo.config.MongoCmdOptionsBuilder; +import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.aai.cacher.common.MongoHelperSingleton; +import org.onap.aai.cacher.egestion.printer.EgestionTestComponent; +import org.onap.aai.cacher.injestion.parser.InjestionTestComponent; +import org.onap.aai.cacher.injestion.parser.PayloadParserService; +import org.onap.aai.cacher.service.helper.RestClientHelperService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +//@Ignore +@RunWith(SpringJUnit4ClassRunner.class) +@Configuration +@ContextConfiguration(classes = {InjestionTestComponent.class, AAIEventConsumerTest.class}) +public class AAIEventConsumerTest { + private static final String DB_NAME = AAIEventConsumerTest.class.getSimpleName(); + private static MongoDatabase mongoDb; + private static RestClientHelperService restClientHelperService; + private static DB db; + private static MongodProcess mongod; + private static MongoClient mongoC; + + private AAIEventConsumer aaiEventConsumer; + + @Autowired + private AAIDmaapEventProcessor aaiDmaapEventProcessor; + + @Bean + public DB db() { + return db; + } + + @Bean + public MongoDatabase mongoDatabase() { + return mongoDb; + } + + @Bean + public RestClientHelperService restClientHelperService() { + return restClientHelperService; + } + + @Bean + public MongoHelperSingleton mongoHelperSingleton(DB db, MongoDatabase mongoDb) { + return new MongoHelperSingleton(db, mongoDb); + } + + @Bean + public AAIDmaapEventProcessor aaiDmaapEventProcessor(MongoHelperSingleton mongoHelperSingleton, PayloadParserService payloadParserService) { + return new AAIDmaapEventProcessor(mongoHelperSingleton, payloadParserService); + } + + + MRConsumer client; + private String validEventMessage = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false}}"; + private String validHeldEventMessage = "{'cambria.partition':'AAI','event-header':{'severity':'NORMAL','entity-type':'pserver','top-entity-type':'pserver','entity-link':'/aai/v13/cloud-infrastructure/pservers/pserver/pserver-1','event-type':'AAI-EVENT','domain':'JUNIT','action':'CREATE','sequence-number':'0','id':'0c3b336d-6554-4ddf-a4d7-90f97876a966','source-name':'JUNIT','version':'v13','timestamp':'20180209-21:02:20:344'},'entity':{'hostname':'pserver-1','in-maint':false}}"; + DmaapConsumerSingleton singleton = DmaapConsumerSingleton.getInstance(); + List<String> eventMessageList = new ArrayList<>(); + + + @BeforeClass + public static void setUp() throws Exception { + String bindIp = "localhost"; + int port = 27017; + startEmbedded(port); + + mongoC = new MongoClient(bindIp, port); + mongoDb = mongoC.getDatabase(DB_NAME); + db = mongoC.getDB(DB_NAME); + + } + + @Before + public void init() throws Exception { + eventMessageList.add(validEventMessage); + //super.setupBundleconfig(); + aaiEventConsumer = new AAIEventConsumer("aaiDmaaPEventConsumer.properties", true); + Properties prop = aaiEventConsumer.getDmaapEventConsumerProperties(); + client = Mockito.mock(MRConsumer.class); + aaiEventConsumer.setConsumer(client); + + + } + + protected static void startEmbedded(int port) throws IOException { + IMongodConfig mongoConfigConfig = new MongodConfigBuilder() + .version(Version.Main.PRODUCTION) + .net(new Net(port, Network.localhostIsIPv6())) + .cmdOptions(new MongoCmdOptionsBuilder().verbose(true).build()) + .configServer(false) + .build(); + + MongodExecutable mongodExecutable = MongodStarter.getDefaultInstance().prepare(mongoConfigConfig); + + mongod = mongodExecutable.start(); + } + + @AfterClass + public static void tearDown() { + if (mongod != null && mongod.isProcessRunning()) { + mongod.stop(); + } + } + + @After + public void cleanup() { + final List<String> collectionNames = new ArrayList<>(); + mongoDb.listCollections().iterator().forEachRemaining(document -> collectionNames.add(document.getString("name"))); + collectionNames.forEach(collectionName -> mongoDb.getCollection(collectionName).drop()); + } + + @Test + public void startProcessing() throws IOException, Exception { + Mockito.when(client.fetch()).thenReturn(eventMessageList); + aaiEventConsumer.startProcessing(aaiDmaapEventProcessor); + } + + @Test + public void startProcessingWaitWithHeldEventMessage() throws IOException, Exception { + singleton.setIsInitialized(true); + singleton.setFirstEventMessage(validHeldEventMessage); + Mockito.when(client.fetch()).thenReturn(eventMessageList); + aaiEventConsumer.startProcessing(aaiDmaapEventProcessor); + } + + @Test + public void startProcessingNoWaitWithHeldEventMessage() throws IOException, Exception { + singleton.setProcessEvents(true); + singleton.setFirstEventMessage(validHeldEventMessage); + Mockito.when(client.fetch()).thenReturn(eventMessageList); + aaiEventConsumer.startProcessing(aaiDmaapEventProcessor); + } + +} + diff --git a/src/test/java/org/onap/aai/cacher/dmaap/consumer/DmaapConsumerSingletonTest.java b/src/test/java/org/onap/aai/cacher/dmaap/consumer/DmaapConsumerSingletonTest.java new file mode 100644 index 0000000..60ee2e1 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/dmaap/consumer/DmaapConsumerSingletonTest.java @@ -0,0 +1,39 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.dmaap.consumer; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class DmaapConsumerSingletonTest { + + static final String firstEventMessage = "firstMessageValue"; + @Test + public void testSingleton() { + DmaapConsumerSingleton dmaapConsumerSingleton = DmaapConsumerSingleton.getInstance(); + dmaapConsumerSingleton.setIsInitialized(true); + dmaapConsumerSingleton.setProcessEvents(false); + dmaapConsumerSingleton.setFirstEventMessage(firstEventMessage); + assertTrue("isInitialized", dmaapConsumerSingleton.getIsInitialized()); + assertFalse("processEvents", dmaapConsumerSingleton.getProcessEvents()); + assertEquals("firstEventMessage", firstEventMessage, dmaapConsumerSingleton.getFirstEventMessage()); + } +} diff --git a/src/test/java/org/onap/aai/cacher/egestion/printer/EgestionTestComponent.java b/src/test/java/org/onap/aai/cacher/egestion/printer/EgestionTestComponent.java new file mode 100644 index 0000000..fa4ce13 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/egestion/printer/EgestionTestComponent.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.egestion.printer; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import java.nio.file.FileSystems; + +@Configuration +@ComponentScan(basePackages = {"org.onap.aai.cacher.egestion.printer"}) +public class EgestionTestComponent { + public EgestionTestComponent() { + System.setProperty("AJSC_HOME", FileSystems.getDefault().getPath(".").toAbsolutePath().toString()); + System.setProperty("BUNDLECONFIG_DIR", "src/main/resources"); + + } +} diff --git a/src/test/java/org/onap/aai/cacher/injestion/parser/AAIResourcesUriTemplatesTest.java b/src/test/java/org/onap/aai/cacher/injestion/parser/AAIResourcesUriTemplatesTest.java new file mode 100644 index 0000000..a48712f --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/injestion/parser/AAIResourcesUriTemplatesTest.java @@ -0,0 +1,137 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.injestion.parser; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = InjestionTestComponent.class) +public class AAIResourcesUriTemplatesTest { + + @Autowired + AAIResourcesUriTemplates aaiResourcesUriTemplates; + + @Test + public void getUriTemplateByType() throws Exception { + + assertEquals("Service template is returned", + "/service-design-and-creation/services/service/{service-id}", + aaiResourcesUriTemplates.getUriTemplateByType("service")); + + assertFalse(aaiResourcesUriTemplates.getUriTemplateByType("does not exist") != null); + + } + + @Test + public void getMatchingStartingTemplate() throws Exception { + String uri = "/service-design-and-creation/services/service/id/l-interfaces/l-interface/name/p-interfaces/p-interface/name2"; + assertEquals("Service template is returned", + "/service-design-and-creation/services/service/{service-id}", + aaiResourcesUriTemplates.getMatchingStartingTemplate(uri).get()); + + uri = "/l-interfaces/l-interface/name/p-interfaces/p-interface/name2"; + assertEquals("l-interface template is returned", + "/l-interfaces/l-interface/{interface-name}", + aaiResourcesUriTemplates.getMatchingStartingTemplate(uri).get()); + + uri = "/l-interface/name/p-interfaces/p-interface/name2"; + assertFalse(aaiResourcesUriTemplates.getMatchingStartingTemplate(uri).isPresent()); + } + + @Test + public void uriToTemplatesValidTest() throws Exception { + String uri = "/service-design-and-creation/services/service/id/l-interfaces/l-interface/name/p-interfaces/p-interface/name2"; + List<String> expected = Arrays.asList( + "/service-design-and-creation/services/service/{service-id}", + "/l-interfaces/l-interface/{interface-name}", + "/p-interfaces/p-interface/{interface-name}" + ); + + assertThat(aaiResourcesUriTemplates.uriToTemplates(uri), is(expected)); + } + + @Test + public void uriToTemplatesRepeatedValidTest() throws Exception { + String uri = "/service-design-and-creation/services/service/id/l-interfaces/l-interface/name/l-interfaces/l-interface/name2"; + List<String> expected = Arrays.asList( + "/service-design-and-creation/services/service/{service-id}", + "/l-interfaces/l-interface/{interface-name}", + "/l-interfaces/l-interface/{interface-name}" + ); + + assertThat(aaiResourcesUriTemplates.uriToTemplates(uri), is(expected)); + } + + @Test + public void uriToSegmentsValidTest() throws Exception { + String uri = "/service-design-and-creation/services/service/id/l-interfaces/l-interface/name/p-interfaces/p-interface/name2"; + List<String> expected = Arrays.asList( + "/service-design-and-creation/services/service/id", + "/l-interfaces/l-interface/name", + "/p-interfaces/p-interface/name2" + ); + + assertThat(aaiResourcesUriTemplates.uriToSegments(uri), is(expected)); + } + + @Test + public void uriAndTemplateToKeyValueMappingTest() throws Exception { + String uri = "/service-design-and-creation/services/service/id"; + String template = "/service-design-and-creation/services/service/{service-id}"; + Map<String, String> expected = new HashMap<>(); + expected.put("service-id", "id"); + + assertThat(aaiResourcesUriTemplates.getUriTemplateMappings(uri, template), is(expected)); + } + + @Test + public void uriAndTemplateToKeyValueMappingWithEncodingTest() throws Exception { + String uri = "/service-design-and-creation/services/service/i%3Ad"; + String template = "/service-design-and-creation/services/service/{service-id}"; + Map<String, String> expected = new HashMap<>(); + expected.put("service-id", "i:d"); + + assertThat(aaiResourcesUriTemplates.getUriTemplateMappings(uri, template), is(expected)); + } + + @Test + public void uriAndTemplateToKeyValueMappingWihtMultipleTest() throws Exception { + String uri = "/cloud-infrastructure/cloud-regions/cloud-region/owner/i%3Ad"; + String template = "/cloud-infrastructure/cloud-regions/cloud-region/{cloud-owner}/{cloud-region-id}"; + Map<String, String> expected = new HashMap<>(); + expected.put("cloud-owner", "owner"); + expected.put("cloud-region-id", "i:d"); + + assertThat(aaiResourcesUriTemplates.getUriTemplateMappings(uri, template), is(expected)); + } + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/cacher/injestion/parser/InjestionTestComponent.java b/src/test/java/org/onap/aai/cacher/injestion/parser/InjestionTestComponent.java new file mode 100644 index 0000000..34cc8a3 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/injestion/parser/InjestionTestComponent.java @@ -0,0 +1,35 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.injestion.parser; + +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +import java.nio.file.FileSystems; + +@Configuration +@ComponentScan(basePackages = {"org.onap.aai.cacher.injestion"}) +public class InjestionTestComponent { + public InjestionTestComponent() { + System.setProperty("AJSC_HOME", FileSystems.getDefault().getPath(".").toAbsolutePath().toString()); + System.setProperty("BUNDLECONFIG_DIR", "src/main/resources"); + + } +} diff --git a/src/test/java/org/onap/aai/cacher/injestion/parser/PayloadParserServiceTest.java b/src/test/java/org/onap/aai/cacher/injestion/parser/PayloadParserServiceTest.java new file mode 100644 index 0000000..1579323 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/injestion/parser/PayloadParserServiceTest.java @@ -0,0 +1,148 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.injestion.parser; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.aai.cacher.injestion.parser.strategy.PayloadParserType; +import org.onap.aai.cacher.model.CacheEntry; +import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.util.List; + +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = InjestionTestComponent.class) +public class PayloadParserServiceTest { + + @Autowired + private PayloadParserService parserService; + + private JsonParser parser = new JsonParser(); + + private String aaiGetAllServiceResponse = + "{" + + " 'service': [" + + " {" + + " 'service-id': 'service-id-1:1'," + + " 'service-description': 'A'," + + " 'resource-version': '1'" + + " }," + + " {" + + " 'service-id': 'service-id-2'," + + " 'service-description': 'B'," + + " 'resource-version': '2'" + + " }" + + " ]" + + "}"; + private JsonObject aaiGetAllServiceResponseJson = parser.parse(aaiGetAllServiceResponse).getAsJsonObject(); + + + + private void print(List<CacheEntry> result) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + result.forEach(e -> System.out.println("Collection: " + e.getCollection() + "\nKey: " + e.getId() + "\n" + gson.toJson(e.getPayload()))); + } + + @Test + public void testGetAllAAIResourceTest() throws JSONException { + String expectedUri = "/service-design-and-creation/services/service/service-id-1%3A1"; + + List<CacheEntry> result = parserService.doParse("service", aaiGetAllServiceResponseJson, "aai-resource-get-all"); + print(result); + + assertTrue(result.stream().map(cacheIdentifier -> cacheIdentifier.getId()).anyMatch(id -> id.equals(expectedUri))); + JSONAssert.assertEquals( + new JSONObject(aaiGetAllServiceResponseJson.getAsJsonArray("service").get(0).getAsJsonObject().toString()), + new JSONObject(result.stream().filter(e -> e.getId().equals(expectedUri)).map(CacheEntry::getPayload).findFirst().get().toString()), + false); + + } + + @Test + public void testGetAllAAIResourceStringTest() throws JSONException { + String expectedUri = "/service-design-and-creation/services/service/service-id-2"; + + List<CacheEntry> result = parserService.doParse("service", aaiGetAllServiceResponse, PayloadParserType.AAI_RESOURCE_GET_ALL); + print(result); + + assertTrue(result.stream().map(cacheIdentifier -> cacheIdentifier.getId()).anyMatch(id -> id.equals(expectedUri))); + JSONAssert.assertEquals( + new JSONObject(aaiGetAllServiceResponseJson.getAsJsonArray("service").get(1).getAsJsonObject().toString()), + new JSONObject(result.stream().filter(e -> e.getId().equals(expectedUri)).map(CacheEntry::getPayload).findFirst().get().toString()), + false); + } + + @Test + public void testNoneStrategyTest1() throws JSONException { + String cacheKey = "service"; + List<CacheEntry> result = parserService.doParse(cacheKey, aaiGetAllServiceResponse); + print(result); + noneTests(cacheKey, result); + } + + @Test + public void testNoneStrategyTest2() throws JSONException { + String cacheKey = "service"; + List<CacheEntry> result = parserService.doParse(cacheKey, aaiGetAllServiceResponseJson); + print(result); + noneTests(cacheKey, result); + } + + @Test + public void testNoneStrategyTest3() throws JSONException { + String cacheKey = "service"; + List<CacheEntry> result = parserService.doParse(cacheKey, aaiGetAllServiceResponse, PayloadParserType.NONE); + print(result); + noneTests(cacheKey, result); + } + + @Test + public void testNoneStrategyTest4() throws JSONException { + String cacheKey = "service"; + List<CacheEntry> result = parserService.doParse(cacheKey, aaiGetAllServiceResponse, "none"); + print(result); + noneTests(cacheKey, result); + } + + private void noneTests(String cacheKey, List<CacheEntry> result) throws JSONException { + assertThat(result.size(), is(1)); + assertTrue(result.stream().map(cacheIdentifier -> cacheIdentifier.getId()).anyMatch(id -> id.equals(cacheKey))); + JSONAssert.assertEquals( + new JSONObject(aaiGetAllServiceResponse), + new JSONObject(result.get(0).getPayload().toString()), + false); + } + + +} + diff --git a/src/test/java/org/onap/aai/cacher/injestion/parser/strategy/AAIResourceDmaapParserStrategyTest.java b/src/test/java/org/onap/aai/cacher/injestion/parser/strategy/AAIResourceDmaapParserStrategyTest.java new file mode 100644 index 0000000..8a4ab0b --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/injestion/parser/strategy/AAIResourceDmaapParserStrategyTest.java @@ -0,0 +1,429 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.injestion.parser.strategy; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.json.JSONObject; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.aai.cacher.injestion.parser.InjestionTestComponent; +import org.onap.aai.cacher.injestion.parser.PayloadParserService; +import org.onap.aai.cacher.model.CacheEntry; +import org.skyscreamer.jsonassert.JSONAssert; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.util.MultiValueMap; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = InjestionTestComponent.class) +public class AAIResourceDmaapParserStrategyTest { + + @Autowired + private PayloadParserService parserService; + + @Autowired + @Qualifier("aai-resource-dmaap") + private AAIResourceDmaapParserStrategy aaiResourceDmaapParserStrategy; + + private JsonParser parser = new JsonParser(); + + private JsonObject pserverCreateEvent = parser.parse( + new FileReader("./src/test/resources/test/payloads/dmaap-pserver-create.json")).getAsJsonObject(); + + public AAIResourceDmaapParserStrategyTest() throws FileNotFoundException {} + + private void print(List<CacheEntry> result) { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + result.forEach(e -> System.out.println("\n\nCollection: " + e.getCollection() + + "\nKey: " + e.getId() + + "\nFind: " + gson.toJson(e.getFindQuery()) + + "\nNestedFind: " + gson.toJson(e.getNestedFind()) + + "\nNestedField: " + e.getNestedField() + + "\nNestedFieldIdentifier: " + gson.toJson(e.getNestedFieldIdentifierObj()) + + "\nPayload: " + gson.toJson(e.getPayload()))); + } + + @Test + public void test(){ + List<CacheEntry> result = parserService.doParse("dmaapEvent", pserverCreateEvent, PayloadParserType.AAI_RESOURCE_DMAAP); + print(result); + } + + + @Test + public void getUriTest() { + String fullUri = aaiResourceDmaapParserStrategy.getFullUri(pserverCreateEvent.getAsJsonObject("event-header")); + assertEquals("/aai/v12/cloud-infrastructure/pservers/pserver/dmaap-pserver-create", fullUri); + String uri = aaiResourceDmaapParserStrategy.getUri(fullUri); + assertEquals("/cloud-infrastructure/pservers/pserver/dmaap-pserver-create", uri); + } + + @Test + public void getAaiUriSegmentsTest() { + + String uri = "/service-design-and-creation/services/service/id/l-interfaces/l-interface/name/p-interfaces/p-interface/name2"; + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + + assertEquals("3 segments are generated", 3, segments.size()); + + assertEquals("Segment 1 plural is services", "services", segments.get(0).getSegmentPlural().get()); + assertEquals("Segment 2 plural is l-interfaces", "l-interfaces", segments.get(1).getSegmentPlural().get()); + assertEquals("Segment 3 plural is p-interfaces", "p-interfaces", segments.get(2).getSegmentPlural().get()); + + assertEquals("Segment 1 singular is service", "service", segments.get(0).getSegmentSingular()); + assertEquals("Segment 2 singular is l-interface", "l-interface", segments.get(1).getSegmentSingular()); + assertEquals("Segment 3 singular is p-interface", "p-interface", segments.get(2).getSegmentSingular()); + + assertEquals("Segment 1 template", + "/service-design-and-creation/services/service/{service-id}", + segments.get(0).getSegmentTemplate()); + assertEquals("Segment 2 template", + "/l-interfaces/l-interface/{interface-name}", + segments.get(1).getSegmentTemplate()); + assertEquals("Segment 3 template", + "/p-interfaces/p-interface/{interface-name}", + segments.get(2).getSegmentTemplate()); + + assertEquals("Segment 1 uri", + "/service-design-and-creation/services/service/id", + segments.get(0).getSegment()); + assertEquals("Segment 2 uri", + "/l-interfaces/l-interface/name", + segments.get(1).getSegment()); + assertEquals("Segment 3 uri", + "/p-interfaces/p-interface/name2", + segments.get(2).getSegment()); + + Map<String, String> expected = new HashMap<>(); + expected.put("service-id", "id"); + assertEquals("Segment 1 mapping", expected, segments.get(0).getSegmentKeyValues()); + expected = new HashMap<>(); + expected.put("interface-name", "name"); + assertEquals("Segment 2 mapping", expected, segments.get(1).getSegmentKeyValues()); + expected = new HashMap<>(); + expected.put("interface-name", "name2"); + assertEquals("Segment 3 mapping", expected, segments.get(2).getSegmentKeyValues()); + } + + @Test + public void getEntityBodyChildTest() throws Exception { + String uri = "/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/ams1b/tenants/tenant/52fd05137ab4453bb53084a13c7bb7a4/vservers/vserver/vs-id"; + String entityString = + "{" + + " 'tenants':" + + " {" + + " 'tenant': [" + + " {" + + " 'vservers':" + + " {" + + " 'vserver': [" + + " {" + + " 'in-maint': false," + + " 'resource-version': '1525978690717'," + + " 'vserver-name': 'slaa-regression-cr-id-api-server-449704329'," + + " 'vserver-id': 'vs-id'" + + " }" + + " ]" + + " }," + + " 'tenant-id': 'ten-id'," + + " 'tenant-name': 'name'" + + " }" + + " ]" + + " }," + + " 'cloud-owner': 'cr-o'," + + " 'owner-defined-type': 'lcp'," + + " 'cloud-region-id': 'cr-id'" + + "}"; + + JsonObject entity = parser.parse(entityString).getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + + JsonObject result = aaiResourceDmaapParserStrategy.getEntityBody(entity, segments); + + JSONAssert.assertEquals( + new JSONObject(entity + .getAsJsonObject("tenants").getAsJsonArray("tenant").get(0) .getAsJsonObject() + .getAsJsonObject("vservers").getAsJsonArray("vserver").get(0).getAsJsonObject() + .toString()), + new JSONObject(result.toString()), + true); + + } + + @Test + public void getEntityBodyTopTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn"; + String entityString = "{'hostname':'hn','in-maint':false,'resource-version':'1525801811662','pserver-id':'0A47B945-9C74-4CBE-AD72-0DECB966EB94'}"; + + JsonObject entity = parser.parse(entityString).getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + + JsonObject result = aaiResourceDmaapParserStrategy.getEntityBody(entity, segments); + + JSONAssert.assertEquals( + new JSONObject(entity.toString()), + new JSONObject(result.toString()), + true); + + } + + @Test + public void getFindQueryTopTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn"; + JsonObject expected = parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/hn'," + + "'hostname':'hn'}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject findQuery = aaiResourceDmaapParserStrategy.getFindQuery(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(findQuery.toString()), + true); + } + + @Test + public void getFindQueryOneLevelTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1"; + JsonObject expected = parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/hn'," + + "'hostname':'hn'}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject findQuery = aaiResourceDmaapParserStrategy.getFindQuery(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(findQuery.toString()), + true); + } + + @Test + public void getFindQueryTwoLevelTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1/l-interfaces/l-interface/interface-2"; + JsonObject expected = parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/hn'," + + "'hostname':'hn'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject findQuery = aaiResourceDmaapParserStrategy.getFindQuery(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(findQuery.toString()), + true); + } + + @Test + public void getNestedFindQueryTopTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn"; + JsonObject expected = parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/hn'," + + "'hostname':'hn'}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject findQuery = aaiResourceDmaapParserStrategy.getNestedFindQuery(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(findQuery.toString()), + true); + } + + @Test + public void getNestedFindQueryOneLevelTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1"; + JsonObject expected = parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/hn'," + + "'hostname':'hn'," + + "'p-interfaces.p-interface.interface-name':'interface-1'}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject findQuery = aaiResourceDmaapParserStrategy.getNestedFindQuery(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(findQuery.toString()), + true); + } + + @Test + public void getNestedFindQueryTwoLevelTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1/l-interfaces/l-interface/interface-2"; + JsonObject expected = parser.parse("{'_id':'/cloud-infrastructure/pservers/pserver/hn'," + + "'hostname':'hn'," + + "'p-interfaces.p-interface.interface-name':'interface-1'," + + "'p-interfaces.p-interface.l-interfaces.l-interface.interface-name':'interface-2'}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject findQuery = aaiResourceDmaapParserStrategy.getNestedFindQuery(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(findQuery.toString()), + true); + } + + @Test + public void getNestedFieldTopTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn"; + String expected = ""; + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + String nestedField = aaiResourceDmaapParserStrategy.getNestedField(segments); + + assertEquals("Top nested field", expected, nestedField); + } + + @Test + public void getNestedFieldOneLevelTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1"; + String expected = "p-interfaces.p-interface"; + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + String nestedField = aaiResourceDmaapParserStrategy.getNestedField(segments); + + assertEquals("Top nested field", expected, nestedField); + } + + @Test + public void getNestedFieldTwoLevelTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1/l-interfaces/l-interface/interface-2"; + String expected = "p-interfaces.p-interface.$.l-interfaces.l-interface"; + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + String nestedField = aaiResourceDmaapParserStrategy.getNestedField(segments); + + assertEquals("Top nested field", expected, nestedField); + } + + @Test + public void getNestedFieldThreeLevelOddCaseTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1/l-interfaces/l-interface/interface-2/l3-interface-ipv4-address-list/addressA"; + String expected = "p-interfaces.p-interface.$.l-interfaces.l-interface.$.l3-interface-ipv4-address-list"; + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + String nestedField = aaiResourceDmaapParserStrategy.getNestedField(segments); + + assertEquals("Top nested field", expected, nestedField); + } + + + + + @Test + public void getNestedIdentifierTopTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn"; + JsonObject expected = parser.parse("{}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject nestedIdentifier = aaiResourceDmaapParserStrategy.getNestedIdentifier(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(nestedIdentifier.toString()), + true); + } + + @Test + public void getNestedIdentifierOneLevelTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1"; + JsonObject expected = parser.parse("{'interface-name':'interface-1'}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject nestedIdentifier = aaiResourceDmaapParserStrategy.getNestedIdentifier(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(nestedIdentifier.toString()), + true); + } + + @Test + public void getNestedIdentifierTwoLevelTest() throws Exception { + String uri = "/cloud-infrastructure/pservers/pserver/hn/p-interfaces/p-interface/interface-1/l-interfaces/l-interface/interface-2"; + JsonObject expected = parser.parse("{'interface-name':'interface-2'}").getAsJsonObject(); + + List<AAIResourceDmaapParserStrategy.AAIUriSegment> segments = aaiResourceDmaapParserStrategy.getAaiUriSegments(uri); + JsonObject nestedIdentifier = aaiResourceDmaapParserStrategy.getNestedIdentifier(segments); + + JSONAssert.assertEquals( + new JSONObject(expected.toString()), + new JSONObject(nestedIdentifier.toString()), + true); + } + + + @Test + public void getFullUriPrefixTest() throws Exception { + assertEquals("/aai/v12", aaiResourceDmaapParserStrategy.getFullUriPrefix("/aai/v12/network/pnfs/pnf/pnf-name-value/p-interfaces/p-interface/xe-10%2F3%2F2/l-interfaces/l-interface/l-interface-name")); + assertEquals("/aai/v4", aaiResourceDmaapParserStrategy.getFullUriPrefix("/aai/v4/names")); + } + + + @Test + public void fullUriToRelationshipObj() throws Exception { + String fullUri = AAIResourceDmaapParserStrategyTestConstants.VSERVER_URI; + String expectedRelObj = AAIResourceDmaapParserStrategyTestConstants.VSERVER_RELATIONSHIP_OBJ; + JsonObject relObj = aaiResourceDmaapParserStrategy.fullUriToRelationshipObj(fullUri, "tosca.relationships.HostedOn"); + + JSONAssert.assertEquals(new JSONObject(expectedRelObj), new JSONObject(relObj.toString()), true); + } + + @Test + public void verifyRelationshipEntriesOnUpdateTest() throws Exception { + List<CacheEntry> result = aaiResourceDmaapParserStrategy + .process("TEST", parser.parse(AAIResourceDmaapParserStrategyTestConstants.GENERIC_VNF_EVENT_WITH_2_RELAT).getAsJsonObject()); + + assertEquals(3, result.size()); + + } + @Test + public void verifyRelationshipEntriesSimpleEvent() throws Exception { + List<CacheEntry> result = aaiResourceDmaapParserStrategy + .process("TEST", parser.parse(AAIResourceDmaapParserStrategyTestConstants.GENERIC_VNF_EVENT).getAsJsonObject()); + + assertEquals(1, result.size()); + + } + + @Test + public void getFromRelationshipFullUriToRelationshipObjTest() throws Exception { + String entity = AAIResourceDmaapParserStrategyTestConstants.FULL_PSERVER; + String fullUri = AAIResourceDmaapParserStrategyTestConstants.FULL_PSERVER_URI; + MultiValueMap<String, AAIResourceDmaapParserStrategy.AAIRelatedToDetails> result = aaiResourceDmaapParserStrategy.getFromRelationshipFullUriToRelationshipObj(parser.parse(entity).getAsJsonObject(), fullUri); + + assertEquals(3, result.size()); + + } +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/cacher/injestion/parser/strategy/AAIResourceDmaapParserStrategyTestConstants.java b/src/test/java/org/onap/aai/cacher/injestion/parser/strategy/AAIResourceDmaapParserStrategyTestConstants.java new file mode 100644 index 0000000..659c881 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/injestion/parser/strategy/AAIResourceDmaapParserStrategyTestConstants.java @@ -0,0 +1,372 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.injestion.parser.strategy; + +public class AAIResourceDmaapParserStrategyTestConstants { + + public static final String VSERVER_URI = "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/AAIAIC25/tenants/tenant/SERVERNAME%3A%3AXXXX/vservers/vserver/afce2113-297a-436c-811a-acf9981fff68"; + public static final String VSERVER_RELATIONSHIP_OBJ = "{" + + " 'related-to': 'vserver'," + + " 'relationship-label': 'tosca.relationships.HostedOn'," + + " 'related-link': '/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/AAIAIC25/tenants/tenant/SERVERNAME%3A%3AXXXX/vservers/vserver/afce2113-297a-436c-811a-acf9981fff68'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'cloud-region.cloud-owner'," + + " 'relationship-value': 'onap-cloud-owner'" + + " }," + + " {" + + " 'relationship-key': 'cloud-region.cloud-region-id'," + + " 'relationship-value': 'AAIAIC25'" + + " }," + + " {" + + " 'relationship-key': 'tenant.tenant-id'," + + " 'relationship-value': 'SERVERNAME::XXXX'" + + " }," + + " {" + + " 'relationship-key': 'vserver.vserver-id'," + + " 'relationship-value': 'afce2113-297a-436c-811a-acf9981fff68'" + + " }" + + " ]" + + "}"; + + public static final String FULL_PSERVER_URI = "/aai/v12/cloud-infrastructure/pservers/pserver/SERVERNAME"; + public static final String FULL_PSERVER = "{" + + " 'hostname': 'SERVERNAME'," + + " 'relationship-list':" + + " {" + + " 'relationship': [" + + " {" + + " 'related-to': 'generic-vnf'," + + " 'relationship-label': 'tosca.relationships.HostedOn'," + + " 'related-link': '/aai/v12/network/generic-vnfs/generic-vnf/205c64eb-88b1-490a-a838-b0080e6902bc'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'generic-vnf.vnf-id'," + + " 'relationship-value': '205c64eb-88b1-490a-a838-b0080e6902bc'" + + " }" + + " ]," + + " 'related-to-property': [" + + " {" + + " 'property-key': 'generic-vnf.vnf-name'," + + " 'property-value': 'USAUTOUFTIL2001UJDM02'" + + " }" + + " ]" + + " }," + + " {" + + " 'related-to': 'vserver'," + + " 'relationship-label': 'tosca.relationships.HostedOn'," + + " 'related-link': '/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/AAIAIC25/tenants/tenant/SERVERNAME%3A%3AXXXX/vservers/vserver/74a47c2c-b53f-4264-87fc-bb85c7f49207'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'cloud-region.cloud-owner'," + + " 'relationship-value': 'onap-cloud-owner'" + + " }," + + " {" + + " 'relationship-key': 'cloud-region.cloud-region-id'," + + " 'relationship-value': 'AAIAIC25'" + + " }," + + " {" + + " 'relationship-key': 'tenant.tenant-id'," + + " 'relationship-value': 'SERVERNAME::XXXX'" + + " }," + + " {" + + " 'relationship-key': 'vserver.vserver-id'," + + " 'relationship-value': '74a47c2c-b53f-4264-87fc-bb85c7f49207'" + + " }" + + " ]," + + " 'related-to-property': [" + + " {" + + " 'property-key': 'vserver.vserver-name'," + + " 'property-value': 'SERVERNAME-USAUTOUFTIL2001UJTE03'" + + " }" + + " ]" + + " }," + + " {" + + " 'related-to': 'vserver'," + + " 'relationship-label': 'tosca.relationships.HostedOn'," + + " 'related-link': '/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/AAIAIC25/tenants/tenant/SERVERNAME%3A%3AXXXX/vservers/vserver/afce2113-297a-436c-811a-acf9981fff68'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'cloud-region.cloud-owner'," + + " 'relationship-value': 'onap-cloud-owner'" + + " }," + + " {" + + " 'relationship-key': 'cloud-region.cloud-region-id'," + + " 'relationship-value': 'AAIAIC25'" + + " }," + + " {" + + " 'relationship-key': 'tenant.tenant-id'," + + " 'relationship-value': 'SERVERNAME::XXXX'" + + " }," + + " {" + + " 'relationship-key': 'vserver.vserver-id'," + + " 'relationship-value': 'afce2113-297a-436c-811a-acf9981fff68'" + + " }" + + " ]," + + " 'related-to-property': [" + + " {" + + " 'property-key': 'vserver.vserver-name'," + + " 'property-value': 'SERVERNAME-vjunos0'" + + " }" + + " ]" + + " }," + + " {" + + " 'related-to': 'complex'," + + " 'relationship-label': 'org.onap.relationships.inventory.LocatedIn'," + + " 'related-link': '/aai/v12/cloud-infrastructure/complexes/complex/STLSMO0914'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'complex.physical-location-id'," + + " 'relationship-value': 'STLSMO0914'" + + " }" + + " ]" + + " }" + + " ]" + + " }," + + " 'p-interfaces':" + + " {" + + " 'p-interface': [" + + " {" + + " 'interface-name': 'ge-0/0/10'," + + " 'relationship-list':" + + " {" + + " 'relationship': [" + + " {" + + " 'related-to': 'physical-link'," + + " 'relationship-label': 'tosca.relationships.network.LinksTo'," + + " 'related-link': '/aai/v12/network/physical-links/physical-link/HIS.1702.03053.121'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'physical-link.link-name'," + + " 'relationship-value': 'HIS.1702.03053.121'" + + " }" + + " ]" + + " }" + + " ]" + + " }" + + " }," + + " {" + + " 'interface-name': 'ge-0/0/11'," + + " 'relationship-list':" + + " {" + + " 'relationship': [" + + " {" + + " 'related-to': 'physical-link'," + + " 'relationship-label': 'tosca.relationships.network.LinksTo'," + + " 'related-link': '/aai/v12/network/physical-links/physical-link/HIS.1702.03053.122'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'physical-link.link-name'," + + " 'relationship-value': 'HIS.1702.03053.122'" + + " }" + + " ]" + + " }" + + " ]" + + " }" + + " }" + + " ]" + + " }" + + "}"; + + + public final static String GENERIC_VNF_EVENT_WITH_2_RELAT = "{" + + " 'cambria.partition': 'AAI'," + + " 'event-header':" + + " {" + + " 'severity': 'NORMAL'," + + " 'entity-type': 'generic-vnf'," + + " 'top-entity-type': 'generic-vnf'," + + " 'entity-link': '/aai/v13/network/generic-vnfs/generic-vnf/cc1703a9-a63f-46c5-a6b1-7ff67f3a9848'," + + " 'event-type': 'AAI-EVENT'," + + " 'domain': 'e2e1'," + + " 'action': 'UPDATE'," + + " 'sequence-number': '0'," + + " 'id': '35717064-c145-4172-941a-ae71dced750e'," + + " 'version': 'v12'," + + " 'timestamp': '20180523-15:41:19:570'" + + " }," + + " 'entity':" + + " {" + + " 'vnf-id': 'cc1703a9-a63f-46c5-a6b1-7ff67f3a9848'," + + " 'vf-modules':" + + " {" + + " 'vf-module': [" + + " {" + + " 'vf-module-id': 'eb792c93-d7e6-481c-8a78-e63d39f63e3a'" + + " }," + + " {" + + " 'vf-module-id': '43448d88-099f-4a33-8860-889773440675'" + + " }" + + " ]" + + " }," + + " 'relationship-list':" + + " {" + + " 'relationship': [" + + " {" + + " 'related-to': 'service-instance'," + + " 'relationship-label': 'org.onap.relationships.inventory.ComposedOf'," + + " 'related-link': '/aai/v13/business/customers/customer/1702_IT3_SubscGblID_20170426162928/service-subscriptions/service-subscription/XXXX-VMS/service-instances/service-instance/SERVERNAME'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'customer.global-customer-id'," + + " 'relationship-value': '1702_IT3_SubscGblID_20170426162928'" + + " }," + + " {" + + " 'relationship-key': 'service-subscription.service-type'," + + " 'relationship-value': 'XXXX-VMS'" + + " }," + + " {" + + " 'relationship-key': 'service-instance.service-instance-id'," + + " 'relationship-value': 'SERVERNAME'" + + " }" + + " ]," + + " 'related-to-property': [" + + " {" + + " 'property-key': 'service-instance.service-instance-name'" + + " }" + + " ]" + + " }," + + " {" + + " 'related-to': 'vserver'," + + " 'relationship-label': 'tosca.relationships.HostedOn'," + + " 'related-link': '/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/AAIAIC25/tenants/tenant/SERVERNAME%3A%3AXXXX-VMS/vservers/vserver/e77451f2-1c07-4db4-b92b-9907b840fc8f'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'cloud-region.cloud-owner'," + + " 'relationship-value': 'onap-cloud-owner'" + + " }," + + " {" + + " 'relationship-key': 'cloud-region.cloud-region-id'," + + " 'relationship-value': 'AAIAIC25'" + + " }," + + " {" + + " 'relationship-key': 'tenant.tenant-id'," + + " 'relationship-value': 'SERVERNAME::XXXX-VMS'" + + " }," + + " {" + + " 'relationship-key': 'vserver.vserver-id'," + + " 'relationship-value': 'e77451f2-1c07-4db4-b92b-9907b840fc8f'" + + " }" + + " ]," + + " 'related-to-property': [" + + " {" + + " 'property-key': 'vserver.vserver-name'," + + " 'property-value': 'SERVERNAME-vsrx'" + + " }" + + " ]" + + " }" + + " ]" + + " }" + + " }," + + " 'existing-obj':" + + " {" + + " 'vnf-id': 'cc1703a9-a63f-46c5-a6b1-7ff67f3a9848'," + + " 'vf-modules':" + + " {" + + " 'vf-module': [" + + " {" + + " 'vf-module-id': 'eb792c93-d7e6-481c-8a78-e63d39f63e3a'" + + " }," + + " {" + + " 'vf-module-id': '43448d88-099f-4a33-8860-889773440675'," + + " 'relationship-list':" + + " {" + + " 'relationship': [" + + " {" + + " 'related-to': 'l3-network'," + + " 'relationship-data': [" + + " {" + + " 'relationship-value': '91eae07d-6f38-4fd8-b929-e7c04614c8c3'," + + " 'relationship-key': 'l3-network.network-id'" + + " }" + + " ]," + + " 'related-link': '/aai/v13/network/l3-networks/l3-network/91eae07d-6f38-4fd8-b929-e7c04614c8c3'," + + " 'relationship-label': 'org.onap.relationships.inventory.Uses'," + + " 'related-to-property': [" + + " {" + + " 'property-key': 'l3-network.network-name'," + + " 'property-value': 'ADIODvPE-24388-T-E2E-001_int_AdiodVpeTenantOamNetwork.vpeNodMisOam_net_2'" + + " }" + + " ]" + + " }" + + " ]" + + " }" + + " }" + + " ]" + + " }," + + " 'relationship-list':" + + " {" + + " 'relationship': [" + + " {" + + " 'related-to': 'vserver'," + + " 'relationship-label': 'tosca.relationships.HostedOn'," + + " 'related-link': '/aai/v13/cloud-infrastructure/cloud-regions/cloud-region/onap-cloud-owner/AAIAIC25/tenants/tenant/SERVERNAME%3A%3AXXXX-VMS/vservers/vserver/e77451f2-1c07-4db4-b92b-9907b840fc8f'," + + " 'relationship-data': [" + + " {" + + " 'relationship-key': 'cloud-region.cloud-owner'," + + " 'relationship-value': 'onap-cloud-owner'" + + " }," + + " {" + + " 'relationship-key': 'cloud-region.cloud-region-id'," + + " 'relationship-value': 'AAIAIC25'" + + " }," + + " {" + + " 'relationship-key': 'tenant.tenant-id'," + + " 'relationship-value': 'SERVERNAME::XXXX-VMS'" + + " }," + + " {" + + " 'relationship-key': 'vserver.vserver-id'," + + " 'relationship-value': 'e77451f2-1c07-4db4-b92b-9907b840fc8f'" + + " }" + + " ]," + + " 'related-to-property': [" + + " {" + + " 'property-key': 'vserver.vserver-name'," + + " 'property-value': 'SERVERNAME-vsrx'" + + " }" + + " ]" + + " }" + + " ]" + + " }" + + " }" + + "}"; + + public final static String GENERIC_VNF_EVENT = "{" + + " 'cambria.partition': 'AAI'," + + " 'event-header':" + + " {" + + " 'severity': 'NORMAL'," + + " 'entity-type': 'generic-vnf'," + + " 'top-entity-type': 'generic-vnf'," + + " 'entity-link': '/aai/v13/network/generic-vnfs/generic-vnf/cc1703a9-a63f-46c5-a6b1-7ff67f3a9848'," + + " 'event-type': 'AAI-EVENT'," + + " 'domain': 'e2e1'," + + " 'action': 'UPDATE'," + + " 'sequence-number': '0'," + + " 'id': '35717064-c145-4172-941a-ae71dced750e'," + + " 'version': 'v12'," + + " 'timestamp': '20180523-15:41:19:570'" + + " }," + + " 'entity':" + + " {" + + " 'vnf-id': 'cc1703a9-a63f-46c5-a6b1-7ff67f3a9848'" + + " }" + + "}"; +} diff --git a/src/test/java/org/onap/aai/cacher/model/CacheKeyTest.java b/src/test/java/org/onap/aai/cacher/model/CacheKeyTest.java new file mode 100644 index 0000000..19a3b3b --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/model/CacheKeyTest.java @@ -0,0 +1,169 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.model; + +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CacheKeyTest { + + public String inputGETOnInit = "{" + + "'cacheKey': 'cloud-region'," + + "'baseUrl': 'http://localhost:8447'," + + "'module': '/aai/v13/'," + + "'URI': 'cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3'," + + "'timingIndicator': 'onInit'," + + "'httpMethod': 'GET'}"; + + public String inputGETFirstHitDefault = "{" + + "'cacheKey': 'cloud-region'," + + "'baseUrl': 'http://localhost:8447'," + + "'module': '/aai/v13/'," + + "'URI': 'cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3'}"; + + public String inputGETScheduledDefault = "{" + + "'cacheKey': 'cloud-region'," + + "'baseUrl': 'http://localhost:8447'," + + "'module': '/aai/v13/'," + + "'timingIndicator': 'scheduled'," + + "'URI': 'cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3'}"; + + public String inputGETScheduledWithSyncInterval = "{" + + "'cacheKey': 'cloud-region'," + + "'baseUrl': 'http://localhost:8447'," + + "'module': '/aai/v13/'," + + "'syncInterval': '2'," + + "'timingIndicator': 'scheduled'," + + "'URI': 'cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3'}"; + + public String inputGETScheduledWithSyncIntervalWithId = "{" + + "'_id': 'cloud-region'," + + "'baseUrl': 'http://localhost:8447'," + + "'module': '/aai/v13/'," + + "'syncInterval': '2'," + + "'timingIndicator': 'scheduled'," + + "'URI': 'cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3'}"; + + + @Test + public void testCacheKeyObjectGETOnInit() { + JsonParser parser = new JsonParser(); + JsonObject ckJson = (JsonObject) parser.parse(inputGETOnInit); + CacheKey ck = CacheKey.fromJson(ckJson); + assertEquals("cacheKey was incorrect", "cloud-region", ck.getCacheKey()); + assertEquals("baseUrl was incorrect", "http://localhost:8447", ck.getBaseUrl()); + assertEquals("Module was incorrect", "/aai/v13/", ck.getModule()); + assertEquals("URI was incorrect", "cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3", ck.getURI()); + assertEquals("timingIndicator was incorrect", "onInit", ck.getTimingIndicator()); + assertEquals("Http Method was incorrect", "GET", ck.getHttpMethod()); + assertEquals("Http Body was incorrect", "-1", ck.getHttpBody()); + assertEquals("Sync Interval was incorrect", "-1", ck.getSyncInterval()); + assertEquals("Last Sync Start Time was incorrect", "-1", ck.getLastSyncStartTime()); + assertEquals("Last Sync Success Time was incorrect", "-1", ck.getLastSyncSuccessTime()); + } + + @Test + public void testCacheKeyObjectGETFirstHitDefault() { + JsonParser parser = new JsonParser(); + JsonObject ckJson = (JsonObject) parser.parse(inputGETFirstHitDefault); + CacheKey ck = CacheKey.fromJson(ckJson); + assertEquals("cacheKey was incorrect", "cloud-region", ck.getCacheKey()); + assertEquals("baseUrl was incorrect", "http://localhost:8447", ck.getBaseUrl()); + assertEquals("Module was incorrect", "/aai/v13/", ck.getModule()); + assertEquals("URI was incorrect", "cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3", ck.getURI()); + assertEquals("timingIndicator was incorrect", "firstHit", ck.getTimingIndicator()); + assertEquals("Http Method was incorrect", "GET", ck.getHttpMethod()); + assertEquals("Http Body was incorrect", "-1", ck.getHttpBody()); + assertEquals("Sync Interval was incorrect", "-1", ck.getSyncInterval()); + assertEquals("Last Sync Start Time was incorrect", "-1", ck.getLastSyncStartTime()); + assertEquals("Last Sync Success Time was incorrect", "-1", ck.getLastSyncSuccessTime()); + } + + @Test + public void testCacheKeyObjectDefaults() { + JsonParser parser = new JsonParser(); + JsonObject ckJson = (JsonObject) parser.parse("{}"); + CacheKey ck = CacheKey.fromJson(ckJson); + assertEquals("cacheKey was incorrect", "-1", ck.getCacheKey()); + assertEquals("baseUrl was incorrect", "-1", ck.getBaseUrl()); + assertEquals("Module was incorrect", "-1", ck.getModule()); + assertEquals("URI was incorrect", "-1", ck.getURI()); + assertEquals("timingIndicator was incorrect", "firstHit", ck.getTimingIndicator()); + assertEquals("Http Method was incorrect", "GET", ck.getHttpMethod()); + assertEquals("Http Body was incorrect", "-1", ck.getHttpBody()); + assertEquals("Sync Interval was incorrect", "-1", ck.getSyncInterval()); + assertEquals("Last Sync Start Time was incorrect", "-1", ck.getLastSyncStartTime()); + assertEquals("Last Sync Success Time was incorrect", "-1", ck.getLastSyncSuccessTime()); + } + + @Test + public void testCacheKeyObjectGETScheduled() { + JsonParser parser = new JsonParser(); + JsonObject ckJson = (JsonObject) parser.parse(inputGETScheduledDefault); + CacheKey ck = CacheKey.fromJson(ckJson); + assertEquals("cacheKey was incorrect", "cloud-region", ck.getCacheKey()); + assertEquals("baseUrl was incorrect", "http://localhost:8447", ck.getBaseUrl()); + assertEquals("Module was incorrect", "/aai/v13/", ck.getModule()); + assertEquals("URI was incorrect", "cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3", ck.getURI()); + assertEquals("timingIndicator was incorrect", "scheduled", ck.getTimingIndicator()); + assertEquals("Http Method was incorrect", "GET", ck.getHttpMethod()); + assertEquals("Http Body was incorrect", "-1", ck.getHttpBody()); + assertEquals("Sync Interval was incorrect", "1440", ck.getSyncInterval()); + assertEquals("Last Sync Start Time was incorrect", "-1", ck.getLastSyncStartTime()); + assertEquals("Last Sync Success Time was incorrect", "-1", ck.getLastSyncSuccessTime()); + } + + @Test + public void testCacheKeyObjectGETScheduledWithSyncInterval() { + JsonParser parser = new JsonParser(); + JsonObject ckJson = (JsonObject) parser.parse(inputGETScheduledWithSyncInterval); + CacheKey ck = CacheKey.fromJson(ckJson); + assertEquals("cacheKey was incorrect", "cloud-region", ck.getCacheKey()); + assertEquals("baseUrl was incorrect", "http://localhost:8447", ck.getBaseUrl()); + assertEquals("Module was incorrect", "/aai/v13/", ck.getModule()); + assertEquals("URI was incorrect", "cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3", ck.getURI()); + assertEquals("timingIndicator was incorrect", "scheduled", ck.getTimingIndicator()); + assertEquals("Http Method was incorrect", "GET", ck.getHttpMethod()); + assertEquals("Http Body was incorrect", "-1", ck.getHttpBody()); + assertEquals("Sync Interval was incorrect", "2", ck.getSyncInterval()); + assertEquals("Last Sync Start Time was incorrect", "-1", ck.getLastSyncStartTime()); + assertEquals("Last Sync Success Time was incorrect", "-1", ck.getLastSyncSuccessTime()); + } + + @Test + public void testCacheKeyObjectGETScheduledWithSyncIntervalWithId() { + JsonParser parser = new JsonParser(); + JsonObject ckJson = (JsonObject) parser.parse(inputGETScheduledWithSyncIntervalWithId); + CacheKey ck = CacheKey.fromJson(ckJson); + assertEquals("cacheKey was incorrect", "cloud-region", ck.getCacheKey()); + assertEquals("baseUrl was incorrect", "http://localhost:8447", ck.getBaseUrl()); + assertEquals("Module was incorrect", "/aai/v13/", ck.getModule()); + assertEquals("URI was incorrect", "cloud-infrastructure/cloud-regions?depth=0&resultIndex=1&resultSize=3", ck.getURI()); + assertEquals("timingIndicator was incorrect", "scheduled", ck.getTimingIndicator()); + assertEquals("Http Method was incorrect", "GET", ck.getHttpMethod()); + assertEquals("Http Body was incorrect", "-1", ck.getHttpBody()); + assertEquals("Sync Interval was incorrect", "2", ck.getSyncInterval()); + assertEquals("Last Sync Start Time was incorrect", "-1", ck.getLastSyncStartTime()); + assertEquals("Last Sync Success Time was incorrect", "-1", ck.getLastSyncSuccessTime()); + } +} diff --git a/src/test/java/org/onap/aai/cacher/service/helper/CacheHelperServiceScenariosTest.java b/src/test/java/org/onap/aai/cacher/service/helper/CacheHelperServiceScenariosTest.java new file mode 100644 index 0000000..f4543ad --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/service/helper/CacheHelperServiceScenariosTest.java @@ -0,0 +1,232 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.service.helper; + +import com.mongodb.DB; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; +import de.flapdoodle.embed.mongo.MongodExecutable; +import de.flapdoodle.embed.mongo.MongodProcess; +import de.flapdoodle.embed.mongo.MongodStarter; +import de.flapdoodle.embed.mongo.config.IMongodConfig; +import de.flapdoodle.embed.mongo.config.MongoCmdOptionsBuilder; +import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; +import de.flapdoodle.embed.mongo.config.Net; +import de.flapdoodle.embed.mongo.distribution.Version; +import de.flapdoodle.embed.process.runtime.Network; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.aai.cacher.common.MongoHelperSingleton; +import org.onap.aai.cacher.egestion.printer.EgestionTestComponent; +import org.onap.aai.cacher.injestion.parser.InjestionTestComponent; +import org.onap.aai.cacher.injestion.parser.strategy.PayloadParserType; +import org.onap.aai.cacher.model.CacheKey; +import org.onap.aai.cacher.util.AAIConstants; +import org.onap.aai.exceptions.AAIException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import javax.ws.rs.core.Response; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@Configuration +@ContextConfiguration(classes = {InjestionTestComponent.class, EgestionTestComponent.class, CacheHelperServiceScenariosTest.class}) +public class CacheHelperServiceScenariosTest { + + private String aaiGetAllComplexResponse = + "{" + + " 'complex': [" + + " {" + + " 'physical-location-id': 'physical-location-id-1'," + + " 'resource-version': '1'" + + " }," + + " {" + + " 'physical-location-id': 'physical-location-id-2'," + + " 'resource-version': '2'" + + " }" + + " ]" + + "}"; + + private String idForDeleteCache = "/cloud-infrastructure/complexes/complex/physical-location-id-2"; + + + private static final String DB_NAME = CacheHelperServiceScenariosTest.class.getSimpleName(); + private static MongoDatabase mongoDb; + private static RestClientHelperService restClientHelperService; + private static DB db; + private static MongodProcess mongod; + private static MongoClient mongoC; + + + @Autowired + private CacheHelperService cacheHelperService; + + @Bean + public DB db() { + return db; + } + + @Bean + public MongoDatabase mongoDatabase() { + return mongoDb; + } + + @Bean + public RestClientHelperService restClientHelperService() { + return restClientHelperService; + } + + @Bean + public MongoHelperSingleton mongoHelperSingleton(DB db, MongoDatabase mongoDb) { + return new MongoHelperSingleton(db, mongoDb); + } + + @Bean + public CacheHelperService cacheHelperService() { + return new CacheHelperService(); + } + + @BeforeClass + public static void setup() throws IOException, InterruptedException { + + String bindIp = "localhost"; + int port = 27017; + startEmbedded(port); + + mongoC = new MongoClient(bindIp, port); + mongoDb = mongoC.getDatabase(DB_NAME); + db = mongoC.getDB(DB_NAME); + + } + + protected static void startEmbedded(int port) throws IOException { + IMongodConfig mongoConfigConfig = new MongodConfigBuilder() + .version(Version.Main.PRODUCTION) + .net(new Net(port, Network.localhostIsIPv6())) + .cmdOptions(new MongoCmdOptionsBuilder().verbose(true).build()) + .configServer(false) + .build(); + + MongodExecutable mongodExecutable = MongodStarter.getDefaultInstance().prepare(mongoConfigConfig); + + mongod = mongodExecutable.start(); + } + + @AfterClass + public static void tearDown() { + if (mongod != null && mongod.isProcessRunning()) { + mongod.stop(); + } + } + + @After + public void cleanup() { + final List<String> collectionNames = new ArrayList<>(); + mongoDb.listCollections().iterator().forEachRemaining(document -> collectionNames.add(document.getString("name"))); + collectionNames.forEach(collectionName -> mongoDb.getCollection(collectionName).drop()); + } + + + @Test + public void cacheKeyProcessingTest() throws Exception { + + CacheKey ck = new CacheKey("complex"); + cacheHelperService.addCacheKey(ck); + Response resp = cacheHelperService.getAllKeys(); + assertEquals("getAllKeys", 200, resp.getStatus()); + CacheKey ck1 = new CacheKey("pserver"); + ck1.timingIndicator = "scheduled"; + cacheHelperService.addCacheKey(ck1); + resp = cacheHelperService.getAllKeys(); + assertEquals("getAllKeys", 200, resp.getStatus()); + CacheKey retrieveCk = cacheHelperService.retrieveCacheKeyObject(ck); + assertEquals("retrieved cacheKey complex", "complex", retrieveCk.getCacheKey()); + + retrieveCk.setParserStrategy(PayloadParserType.AAI_RESOURCE_GET_ALL.toString()); + cacheHelperService.updateCacheKey(retrieveCk); + assertEquals("retrieved cacheKey complex", PayloadParserType.AAI_RESOURCE_GET_ALL.toString(), retrieveCk.getParserStrategy()); + assertEquals("getScheduledCaches", 1, cacheHelperService.getScheduledCaches().size()); + + resp = cacheHelperService.populateCache(retrieveCk, aaiGetAllComplexResponse); + assertEquals("populateCache", 201, resp.getStatus()); + resp = cacheHelperService.getData(retrieveCk); + assertEquals("getData", 200, resp.getStatus()); + resp = cacheHelperService.retrieveCollectionByKey(retrieveCk, AAIConstants.COLLECTION_CACHEKEY); + assertEquals("retrieveCollectionByKey", 200, resp.getStatus()); + resp = cacheHelperService.deleteCache(idForDeleteCache, "complex"); + assertEquals("deleteCache1", 204, resp.getStatus()); + resp = cacheHelperService.deleteCache("noSuchId", "complex"); + assertEquals("deleteCache2", 404, resp.getStatus()); + + + assertTrue("isShouldTrigger1", cacheHelperService.isShouldTrigger(retrieveCk)); + long current = System.currentTimeMillis(); + DateFormat formatter = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss.SSSZ"); + String syncStartTime = formatter.format(current - 61000); + String syncEndTime = formatter.format(current - 60500); + // setup sync in progress + retrieveCk.syncInterval = "1"; + retrieveCk.lastSyncStartTime = syncEndTime; + retrieveCk.lastSyncEndTime = syncStartTime; + cacheHelperService.updateCacheKey(retrieveCk); + + resp = cacheHelperService.forceSync(retrieveCk); + assertEquals("forceSync", 500, resp.getStatus()); + retrieveCk.lastSyncStartTime = syncStartTime; + retrieveCk.lastSyncEndTime = syncEndTime; + assertTrue("isShouldTrigger2", cacheHelperService.isShouldTrigger(retrieveCk)); + + resp = cacheHelperService.deleteCacheKeyAndAssociatedCache("complex"); + assertEquals("deleteCacheKeyAndAssociatedCache", 204, resp.getStatus()); + List<CacheKey> ckList = new ArrayList<CacheKey>(); + ck = new CacheKey("pnf"); + ck1 = new CacheKey("logical-link"); + ckList.add(ck); + ckList.add(ck1); + assertTrue(cacheHelperService.bulkAddCacheKeys(ckList)); + + } + + @Test + public void buildResponseTest() throws Exception { + List<String> issueList = Arrays.asList("First Issue", "Second Issue"); + Response resp = cacheHelperService.buildValidationResponse(issueList); + assertEquals("buildValidationResponse", 400, resp.getStatus()); + AAIException ex = new AAIException("AAI_4000"); + resp = cacheHelperService.buildExceptionResponse(ex); + assertEquals("buildExceptionResponse", 500, resp.getStatus()); + + } +} diff --git a/src/test/java/org/onap/aai/cacher/service/helper/CacheHelperServiceTest.java b/src/test/java/org/onap/aai/cacher/service/helper/CacheHelperServiceTest.java new file mode 100644 index 0000000..4a2ed94 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/service/helper/CacheHelperServiceTest.java @@ -0,0 +1,88 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.service.helper; + +import org.junit.Test; +import org.onap.aai.cacher.model.CacheKey; + +import java.text.SimpleDateFormat; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +public class CacheHelperServiceTest { + + private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss.SSSZ"); + + @Test + public void isShouldTrigger1() throws Exception { + + CacheKey cacheKey = new CacheKey("test"); + cacheKey.setLastSyncStartTime("-1"); + cacheKey.setLastSyncEndTime("-1"); + cacheKey.setLastSyncSuccessTime("-1"); + cacheKey.setSyncInterval("1"); + + CacheHelperService cacheHelperService = new CacheHelperService(); + assertTrue("No timings set (should trigger)", cacheHelperService.isShouldTrigger(cacheKey)); + } + + @Test + public void isShouldTrigger2() throws Exception { + + CacheKey cacheKey = new CacheKey("test"); + cacheKey.setLastSyncStartTime(sdf.format(System.currentTimeMillis()-300000)); //5 mins ago + cacheKey.setLastSyncEndTime("-1"); // has not ended + cacheKey.setLastSyncSuccessTime("-1"); + cacheKey.setSyncInterval("1"); //1 min interval + + CacheHelperService cacheHelperService = new CacheHelperService(); + assertFalse("Start time set (should not trigger)", cacheHelperService.isShouldTrigger(cacheKey)); + } + + @Test + public void isShouldTrigger3() throws Exception { + + CacheKey cacheKey = new CacheKey("test"); + cacheKey.setLastSyncStartTime(sdf.format(System.currentTimeMillis()-300000)); //5 mins ago + cacheKey.setLastSyncEndTime(sdf.format(System.currentTimeMillis()-240000)); // 4 mins ago + cacheKey.setLastSyncSuccessTime("-1"); + cacheKey.setSyncInterval("1"); //1 min interval + + CacheHelperService cacheHelperService = new CacheHelperService(); + assertTrue("Start time less than endtime (should trigger)", cacheHelperService.isShouldTrigger(cacheKey)); + } + + @Test + public void isShouldTrigger4() throws Exception { + + CacheKey cacheKey = new CacheKey("test"); + cacheKey.setLastSyncStartTime(sdf.format(System.currentTimeMillis()-300000)); //5 mins ago + cacheKey.setLastSyncEndTime(sdf.format(System.currentTimeMillis()-360000)); // 6 mins ago + cacheKey.setLastSyncSuccessTime("-1"); + cacheKey.setSyncInterval("1"); //1 min interval + + CacheHelperService cacheHelperService = new CacheHelperService(); + assertFalse("Start time greater than endtime (should not trigger)", cacheHelperService.isShouldTrigger(cacheKey)); + } + + + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/cacher/service/helper/CrudOperationsTest.java b/src/test/java/org/onap/aai/cacher/service/helper/CrudOperationsTest.java new file mode 100644 index 0000000..1aa1d81 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/service/helper/CrudOperationsTest.java @@ -0,0 +1,409 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.service.helper; + +import com.github.fakemongo.Fongo; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.FindOneAndUpdateOptions; +import com.mongodb.client.model.UpdateOptions; +import org.bson.Document; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class CrudOperationsTest { + + public static final String DB_NAME = "testDb"; + private static MongoDatabase mongoDatabase; + + @BeforeClass + public static void setup() { + Fongo fongo = new Fongo(DB_NAME); + mongoDatabase = fongo.getDatabase(DB_NAME); + } + + @Test + public void insertOrUpdateObjInCollection() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery1 = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"}"); + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery1, newObj, new UpdateOptions().upsert(true)); + + Document findQuery2 = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_2\"}"); + newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_2\",\"hostname\":\"testPserver_2\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery2, newObj, new UpdateOptions().upsert(true)); + + newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_2\",\"hostname\":\"testPserver_2\",\"equip-type\":\"NEW\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery2, newObj, new UpdateOptions().upsert(true)); + + FindIterable<Document> docs = collection.find(); + int counter = 0; + for (Document doc : docs) { + counter++; + } + assertEquals("collection contains 2 document", 2, counter); + + Document doc = collection.find(findQuery1).first(); + assertEquals("Found testPserver_1", "testPserver_1", doc.getString("hostname")); + + doc = collection.find(findQuery2).first(); + assertEquals("Found testPserver_2", "testPserver_2", doc.getString("hostname")); + assertEquals("testPserver_2 has NEW as equip-type", "NEW", doc.getString("equip-type")); + } + + @Test + public void removeObjectFromCollection() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery1 = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"}"); + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery1, newObj, new UpdateOptions().upsert(true)); + + Document findQuery2 = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_2\"}"); + newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_2\",\"hostname\":\"testPserver_2\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery2, newObj, new UpdateOptions().upsert(true)); + + assertEquals("PRE DELETE: collection contains 2 documents", 2, collection.count()); + + collection.deleteOne(findQuery1); + + assertEquals("POST DELETE: collection contains 1 documents", 1, collection.count()); + + + } + + @Test + public void findOneFromCollection() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery1 = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"}"); + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery1, newObj, new UpdateOptions().upsert(true)); + + Document findQuery2 = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_2\"}"); + newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_2\",\"hostname\":\"testPserver_2\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery2, newObj, new UpdateOptions().upsert(true)); + + Document findQuery = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_2\"}"); + + assertEquals("collection contains 1 document with id /cloud-infrastructure/pservers/pserver/testPserver_2", + 1L, collection.count(findQuery)); + } + + @Test + public void findFromCollectionWithNested() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery1 = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"}"); + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery1, newObj, new UpdateOptions().upsert(true)); + + Document findQuery = Document.parse( + "{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.interface-name\":\"interface-1\"}" + ); + + assertEquals("collection contains 1 document with id /cloud-infrastructure/pservers/pserver/testPserver_2", + 1L, collection.count(findQuery)); + + + } + + @Test + public void findFromCollectionWithNestedFail() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery1 = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"}"); + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery1, newObj, new UpdateOptions().upsert(true)); + + Document findQuery = Document.parse( + "{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.interface-name\":\"interface-NONE\"}" + ); + + assertEquals("collection contains 1 document with id /cloud-infrastructure/pservers/pserver/testPserver_2", + 0L, collection.count(findQuery)); + + } + + + @Test + public void addToNestedListWithNonExistingList() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"}"); + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\",\"equip-type\":\"JUNIPER XXXX\"}"); + collection.replaceOne(findQuery, newObj, new UpdateOptions().upsert(true)); + + //Check for existing obj + String field = "p-interfaces.p-interface"; + String obj = "{\"interface-name\":\"interface-NEW\"}"; + String nestedFindString = "{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.interface-name\":\"interface-NEW\"}"; + + Document nestedFind = Document.parse(nestedFindString); + + assertEquals("PRE UPDATE: collection contains 0 document with id and nested field", + Long.valueOf(0L), + Long.valueOf(collection.count(nestedFind))); + + Document doc = new Document(); + doc.put(field, Document.parse(obj)); + Document push = new Document(); + push.put("$push", doc); + + System.out.println(collection.find(findQuery).first().toJson()); + + collection.findOneAndUpdate(findQuery, push, new FindOneAndUpdateOptions().upsert(true)); + + System.out.println(collection.find(findQuery).first().toJson()); + + assertEquals("POST UPDATE: collection contains 1 document with id and nested field", + Long.valueOf(1L), + Long.valueOf(collection.count(nestedFind))); + + } + + @Test + public void addToNestedExistingList() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"}"); + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery, newObj, new UpdateOptions().upsert(true)); + + //Check for existing obj + String field = "p-interfaces.p-interface"; + String obj = "{\"interface-name\":\"interface-NEW\"}"; + String nestedFindString = "{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.interface-name\":\"interface-NEW\"}"; + + Document nestedFind = Document.parse(nestedFindString); + + assertEquals("PRE UPDATE: collection contains 0 document with id and nested field", + Long.valueOf(0L), + Long.valueOf(collection.count(nestedFind))); + + Document doc = new Document(); + doc.put(field, Document.parse(obj)); + Document push = new Document(); + push.put("$push", doc); + + System.out.println(collection.find(findQuery).first().toJson()); + + collection.findOneAndUpdate(findQuery, push, new FindOneAndUpdateOptions().upsert(true)); + + System.out.println(collection.find(findQuery).first().toJson()); + + assertEquals("POST UPDATE: collection contains 1 document with id and nested field", + Long.valueOf(1L), + Long.valueOf(collection.count(nestedFind))); + + } + + @Test + public void addToNestedWhereNestedObjExists() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document findQuery = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"}"); + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\",\"equip-type\":\"JUNIPER XXXX\",\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"interface-1\"}]}}"); + collection.replaceOne(findQuery, newObj, new UpdateOptions().upsert(true)); + + //Check for existing obj + String field = "p-interfaces.p-interface"; + String obj = "{\"interface-name\":\"interface-NEW\",\"new-field\":\"NEW\"}"; + String nestedFindString = "{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.interface-name\":\"interface-1\"}"; + String nestedFindUsingNewFieldString = "{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.new-field\":\"NEW\"}"; + String nestedFieldPull = "{\"p-interfaces.p-interface\":{\"interface-name\":\"interface-1\"}}"; + + Document nestedFind = Document.parse(nestedFindString); + + assertEquals("PRE UPDATE: collection contains 1 document with id and nested field", + Long.valueOf(1L), + Long.valueOf(collection.count(nestedFind))); + assertEquals("PRE UPDATE: collection contains 0 document with id and new nested field", + Long.valueOf(0L), + Long.valueOf(collection.count(Document.parse(nestedFindUsingNewFieldString)))); + + //REMOVE existing + Document pull = new Document(); + pull.put("$pull", Document.parse(nestedFieldPull)); + + collection.findOneAndUpdate(nestedFind, pull); + + assertEquals("PRE UPDATE POST DELETE: collection no longer the nested obj that will be inserted", + Long.valueOf(0L), + Long.valueOf(collection.count(nestedFind))); + + + Document doc = new Document(); + doc.put(field, Document.parse(obj)); + Document push = new Document(); + push.put("$push", doc); + + System.out.println(collection.find(findQuery).first().toJson()); + + collection.findOneAndUpdate(findQuery, push, new FindOneAndUpdateOptions().upsert(true)); + + System.out.println(collection.find(findQuery).first().toJson()); + + assertEquals("POST UPDATE: collection contains 1 document with id and nested field", + Long.valueOf(1L), + Long.valueOf(collection.count(Document.parse(nestedFindUsingNewFieldString)))); + + } + + @Test + public void addToNestedWhereNestedObjExistsTwoLevels() { + String collectionName = new Object() {} + .getClass() + .getEnclosingMethod() + .getName(); + + mongoDatabase.createCollection(collectionName); + + MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName); + + Document newObj = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\",\"hostname\":\"testPserver_1\"," + + "\"p-interfaces\":{\"p-interface\":[" + + "{\"interface-name\":\"interface-1\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"l-interface-1\"}]}}," + + "{\"interface-name\":\"interface-2\"}" + + "]}}"); + + Document findQuery = Document.parse("{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.interface-name\":\"interface-1\"}"); + + collection.replaceOne(findQuery, newObj, new UpdateOptions().upsert(true)); + + //Check for existing obj + String field = "p-interfaces.p-interface.$.l-interfaces.l-interface"; + String obj = "{\"interface-name\":\"l-interface-1\",\"new-field\":\"NEW\"}"; + + String nestedFindString = "{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.interface-name\":\"interface-1\"," + + "\"p-interfaces.p-interface.l-interfaces.l-interface.interface-name\":\"l-interface-1\"}"; + + String nestedFindUsingNewFieldString = "{\"_id\":\"/cloud-infrastructure/pservers/pserver/testPserver_1\"," + + "\"p-interfaces.p-interface.interface-name\":\"interface-1\"" + + "\"p-interfaces.p-interface.l-interfaces.l-interface.new-field\":\"NEW\"}"; + + String nestedFieldPull = "{\"p-interfaces.p-interface.$.l-interfaces.l-interface\":{\"interface-name\":\"l-interface-1\"}}"; + + Document nestedFind = Document.parse(nestedFindString); + + assertEquals("PRE UPDATE: collection contains 1 document with id and nested field", + Long.valueOf(1L), + Long.valueOf(collection.count(nestedFind))); + assertEquals("PRE UPDATE: collection contains 0 document with id and new nested field", + Long.valueOf(0L), + Long.valueOf(collection.count(Document.parse(nestedFindUsingNewFieldString)))); + + //REMOVE existing + Document pull = new Document(); + pull.put("$pull", Document.parse(nestedFieldPull)); + + collection.findOneAndUpdate(nestedFind, pull); + + assertEquals("PRE UPDATE POST DELETE: collection no longer the nested obj that will be inserted", + Long.valueOf(0L), + Long.valueOf(collection.count(nestedFind))); + + + Document doc = new Document(); + doc.put(field, Document.parse(obj)); + Document push = new Document(); + push.put("$push", doc); + + System.out.println(collection.find(findQuery).first().toJson()); + + collection.findOneAndUpdate(findQuery, push, new FindOneAndUpdateOptions().upsert(true)); + + System.out.println(collection.find(findQuery).first().toJson()); + + assertEquals("POST UPDATE: collection contains 1 document with id and nested field", + Long.valueOf(1L), + Long.valueOf(collection.count(Document.parse(nestedFindUsingNewFieldString)))); + + } + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/cacher/service/rest/util/CacheKeyRequestValidationTest.java b/src/test/java/org/onap/aai/cacher/service/rest/util/CacheKeyRequestValidationTest.java new file mode 100644 index 0000000..53f90a3 --- /dev/null +++ b/src/test/java/org/onap/aai/cacher/service/rest/util/CacheKeyRequestValidationTest.java @@ -0,0 +1,90 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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.aai.cacher.service.rest.util; + +import com.google.gson.JsonParser; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.cacher.service.helper.CacheHelperService; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class CacheKeyRequestValidationTest { + + protected CacheHelperService cacheHelperService; + protected CacheKeyRequestValidation addCacheKeyRequestValidation; + protected CacheKeyRequestValidation updateCacheKeyRequestValidation; + + private String emptyPayload = "{}"; + private String nonEmptyPayload = "{\"cacheKey\" : \"complex\"}"; + private JsonParser parser; + + @Before + public void setup() { + cacheHelperService = Mockito.mock(CacheHelperService.class); + addCacheKeyRequestValidation = new CacheKeyRequestValidation(CacheKeyRequestValidationType.ADD); + updateCacheKeyRequestValidation = new CacheKeyRequestValidation(CacheKeyRequestValidationType.UPDATE); + parser = new JsonParser(); + } + + @Test + public void testNullPayload() { + List<String> results = addCacheKeyRequestValidation.validateCacheKeyRequest(null, cacheHelperService); + assertEquals("null payload ok", "Unsupported CacheKey request format, empty payload.", results.get(0)); + } + + @Test + public void testEmptyPayload() { + List<String> results = addCacheKeyRequestValidation.validateCacheKeyRequest(parser.parse(emptyPayload).getAsJsonObject(), cacheHelperService); + assertEquals("empty payload ok", "Unsupported CacheKey request format, unspecified cacheKey.", results.get(0)); + } + + @Test + public void testAddNewCacheKey() { + Mockito.when(cacheHelperService.isKeyPresent(Mockito.any(), Mockito.anyString())).thenReturn(false); + List<String> results = addCacheKeyRequestValidation.validateCacheKeyRequest(parser.parse(nonEmptyPayload).getAsJsonObject(), cacheHelperService); + assertEquals("add new CacheKey ok", 0, results.size()); + } + + @Test + public void testAddExistingCacheKey() { + Mockito.when(cacheHelperService.isKeyPresent(Mockito.any(), Mockito.anyString())).thenReturn(true); + List<String> results = addCacheKeyRequestValidation.validateCacheKeyRequest(parser.parse(nonEmptyPayload).getAsJsonObject(), cacheHelperService); + assertEquals("add existing CacheKey ok", "Invalid request to add cacheKey complex, cacheKey exists.", results.get(0)); + } + + + @Test + public void testUpdateNewCacheKey() { + Mockito.when(cacheHelperService.isKeyPresent(Mockito.any(), Mockito.anyString())).thenReturn(false); + List<String> results = updateCacheKeyRequestValidation.validateCacheKeyRequest(parser.parse(nonEmptyPayload).getAsJsonObject(), cacheHelperService); + assertEquals("update new CacheKey ok", "Invalid request to update cacheKey complex, cacheKey does not exist.", results.get(0)); + } + + @Test + public void testUpdateExistingCacheKey() { + Mockito.when(cacheHelperService.isKeyPresent(Mockito.any(), Mockito.anyString())).thenReturn(true); + List<String> results = updateCacheKeyRequestValidation.validateCacheKeyRequest(parser.parse(nonEmptyPayload).getAsJsonObject(), cacheHelperService); + assertEquals("update existing CacheKey ok", 0, results.size()); + } +} |