diff options
Diffstat (limited to 'src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template')
5 files changed, 606 insertions, 0 deletions
diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/FsToDbTemplateSynchronizerTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/FsToDbTemplateSynchronizerTest.java new file mode 100644 index 0000000..4f92558 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/FsToDbTemplateSynchronizerTest.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2020 Nokia. 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.integration.simulators.nfsimulator.vesclient.template; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; + +import java.util.List; + +import static org.junit.Assert.assertEquals; + +public class FsToDbTemplateSynchronizerTest { + + + @Test + public void shouldReturnErrorSynchronizedMessage() { + //given + FsToDbTemplateSynchronizer fsToDbTemplateSynchronizer = new FsToDbTemplateSynchronizer("someInvalidValue", null); + Logger logger = (Logger) LoggerFactory.getLogger(FsToDbTemplateSynchronizer.class); + ListAppender<ILoggingEvent> listAppender = new ListAppender<>(); + listAppender.start(); + logger.addAppender(listAppender); + //when + fsToDbTemplateSynchronizer.synchronize(); + List<ILoggingEvent> logsList = listAppender.list; + //then + assertEquals("Cannot synchronize templates. Check whether the proper folder exists.", logsList.get(0) + .getMessage()); + assertEquals(Level.ERROR, logsList.get(0) + .getLevel()); + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/TemplateServiceTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/TemplateServiceTest.java new file mode 100644 index 0000000..617e7b5 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/TemplateServiceTest.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.integration.simulators.nfsimulator.vesclient.template; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.assertj.core.api.Assertions; +import org.assertj.core.util.Lists; +import org.bson.Document; +import org.junit.Assert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.integration.simulators.nfsimulator.vesclient.template.search.TemplateSearchHelper; +import org.onap.integration.simulators.nfsimulator.vesclient.template.search.viewmodel.FlatTemplateContent; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Query; + +import java.time.Instant; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + +class TemplateServiceTest { + private static final Gson GSON = new Gson(); + private static final Template SAMPLE_TEMPLATE = new Template("sample name", new Document(), Instant.now().getNano()); + private static final List<Template> SAMPLE_TEMPLATE_LIST = Collections.singletonList(SAMPLE_TEMPLATE); + + @Mock + private TemplateRepository templateRepositoryMock; + + @Mock + private MongoTemplate mongoTemplate; + + @InjectMocks + private TemplateService service; + + @BeforeEach + void setUp() { + initMocks(this); + TemplateSearchHelper searchHelper = new TemplateSearchHelper(mongoTemplate); + service = new TemplateService(templateRepositoryMock, searchHelper); + } + + @Test + void testShouldReturnAllTemplates() { + when(templateRepositoryMock.findAll()).thenReturn(SAMPLE_TEMPLATE_LIST); + + List<Template> actual = service.getAll(); + Assertions.assertThat(actual).containsExactly(SAMPLE_TEMPLATE_LIST.get(0)); + } + + + @Test + void testShouldGetTemplateBySpecifiedName() { + when(templateRepositoryMock.findById("sample name")).thenReturn(Optional.of(SAMPLE_TEMPLATE)); + + Optional<Template> actualTemplate = service.get("sample name"); + Assertions.assertThat(actualTemplate).isPresent(); + assertThat(actualTemplate.get()).isEqualTo(SAMPLE_TEMPLATE); + } + + @Test + void testShouldSaveTemplate() { + service.persist(SAMPLE_TEMPLATE); + + verify(templateRepositoryMock, times(1)).save(SAMPLE_TEMPLATE); + } + + @Test + void testShouldDeleteTemplateByName() { + service.delete("sample name"); + + verify(templateRepositoryMock, times(1)).deleteById("sample name"); + } + + + @Test + void testShouldReturnTemplatesAccordingToGivenSearchCriteria() { + doReturn(Lists.emptyList()).when(mongoTemplate).find(any(Query.class), anyObject(), any(String.class)); + + List<String> idsByContentCriteria = service.getIdsByContentCriteria(GSON.fromJson("{\"domain\": \"notification.json\"}", JsonObject.class)); + + assertThat(idsByContentCriteria).isEmpty(); + } + + @Test + void shouldReturnNamesForGivenComposedSearchCriteria() { + JsonObject composedCriteriaObject = GSON.fromJson("{\"eventName\": \"pnfRegistration_Nokia_5gDu\", \"sequence\": 1}", JsonObject.class); + List<FlatTemplateContent> arr = Lists.newArrayList(new FlatTemplateContent("sampleId", null)); + + doReturn(arr).when(mongoTemplate).find(any(Query.class), anyObject(), any(String.class)); + + List<String> idsByContentCriteria = service.getIdsByContentCriteria(composedCriteriaObject); + assertThat(idsByContentCriteria).containsOnly("sampleId"); + } + + @Test + void shouldReturnFalseWhenOverwritingWithoutForce() { + String id = "someTemplate"; + Template template = new Template(id, new Document(), Instant.now().getNano()); + when(templateRepositoryMock.existsById(id)).thenReturn(true); + boolean actual = service.tryPersistOrOverwrite(template, false); + Assert.assertFalse(actual); + } + + @Test + void shouldReturnTrueWhenOverwritingWithForce() { + String id = "someTemplate"; + Template template = new Template(id, new Document(), Instant.now().getNano()); + when(templateRepositoryMock.existsById(id)).thenReturn(true); + boolean actual = service.tryPersistOrOverwrite(template, true); + Assert.assertTrue(actual); + } + + @Test + void shouldReturnTrueWhenSavingNonExistingTemplate() { + String id = "someTemplate"; + Template template = new Template(id, new Document(), Instant.now().getNano()); + when(templateRepositoryMock.existsById(id)).thenReturn(false); + boolean actual = service.tryPersistOrOverwrite(template, false); + Assert.assertTrue(actual); + } + +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/JsonUtilsTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/JsonUtilsTest.java new file mode 100644 index 0000000..6690aa6 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/JsonUtilsTest.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.integration.simulators.nfsimulator.vesclient.template.search; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +class JsonUtilsTest { + + private static final Gson GSON_HELPER = new Gson(); + private JsonUtils utils; + + @BeforeEach + void setUp() { + utils = new JsonUtils(); + } + + private static final String NOTIFICATION_JSON = "{\n\"event\": {\n" + + " \"commonEventHeader\": {\n" + + " \"domain\": \"notification\",\n" + + " \"eventName\": \"vFirewallBroadcastPackets\"\n" + + " },\n" + + " \"notificationFields\": {\n" + + " \"changeIdentifier\": \"PM_MEAS_FILES\",\n" + + " \"arrayOfNamedHashMap\": [{\n" + + " \"name\": \"A20161221.1031-1041.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileformatType\": \"org.3GPP.32.435#measCollec\",\n" + + " \"fileFormatVersion\": \"V10\"\n" + + " }\n" + + " }, {\n" + + " \"name\": \"A20161222.1042-1102.bin.gz\",\n" + + " \"hashMap\": {\n" + + " \"fileFormatType\": \"org.3GPP.32.435#measCollec\",\n" + + " \"fileFormatVersion\": \"1.0.0\"\n" + + " }\n" + + " }],\n" + + " \"notificationFieldsVersion\": \"2.0\"\n}\n\n}}"; + private static final String EXPECTED_FLATTENED_NOTIFICATION = "{" + + " \":event:commonEventHeader:domain\" : \"notification\"," + + " \":event:commonEventHeader:eventName\" : \"vFirewallBroadcastPackets\"," + + " \":event:notificationFields:changeIdentifier\" : \"PM_MEAS_FILES\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:name\" : \"A20161221.1031-1041.bin.gz\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:hashMap:fileformatType\" : \"org.3GPP.32.435#measCollec\"," + + " \":event:notificationFields:arrayOfNamedHashMap[0]:hashMap:fileFormatVersion\" : \"V10\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:name\" : \"A20161222.1042-1102.bin.gz\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:hashMap:fileFormatType\" : \"org.3GPP.32.435#measCollec\"," + + " \":event:notificationFields:arrayOfNamedHashMap[1]:hashMap:fileFormatVersion\" : \"1.0.0\"," + + " \":event:notificationFields:notificationFieldsVersion\" : \"2.0\" }"; + + @Test + void shouldFlattenNestedJsonAndSeparateKeysWithDoubleHash() { + JsonObject templateJson = GSON_HELPER.fromJson(NOTIFICATION_JSON, JsonObject.class); + + JsonObject result = utils.flatten(templateJson); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(EXPECTED_FLATTENED_NOTIFICATION, JsonObject.class)); + } + + @Test + void shouldWorkOnEmptyJsonObject() { + JsonObject result = utils.flatten(new JsonObject()); + + assertThat(result.toString()).isEqualTo("{}"); + } + + @Test + void shouldFlattenObjectWithArrayValue() { + String expectedFlattenedObjectWithArray = "{" + + " \":sample[0]\": 1," + + " \":sample[1]\": 2," + + " \":sample[2]\": 3}"; + JsonObject jsonWithPrimitivesArray = GSON_HELPER.fromJson("{\"sample\": [1, 2, 3]}", JsonObject.class); + + JsonObject result = utils.flatten(jsonWithPrimitivesArray); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedFlattenedObjectWithArray, JsonObject.class)); + } + + @Test + void shouldFlattenObjectWithEmptyArrayValue() { + String expectedFlattenedObjectWithEmptyArray = "{\":sample\": []}"; + JsonObject jsonWithEmptyArrayValue = GSON_HELPER.fromJson("{\"sample\": []}", JsonObject.class); + + JsonObject result = utils.flatten(jsonWithEmptyArrayValue); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedFlattenedObjectWithEmptyArray, JsonObject.class)); + } + + @Test + void shouldFlattenNestedObjectWithEmptyObjectValue() { + String expectedFlattenedNestedObjectWithEmptyObject = "{\":sample:key\": {}}"; + JsonObject nestedJsonWithEmptyObject = GSON_HELPER.fromJson("{\"sample\": {\"key\":{}}}", JsonObject.class); + + JsonObject result = utils.flatten(nestedJsonWithEmptyObject); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedFlattenedNestedObjectWithEmptyObject, JsonObject.class)); + } + + @Test + void shouldFlattenObjectWithDifferentDataTypes() { + String jsonWithDifferentDataTypes = "{ \"topLevelKey\": {\"sampleInt\": 1, \"sampleBool\": false, \"sampleDouble\": 10.0, \"sampleString\": \"str\"}}"; + String expectedResult = "{\":topLevelKey:sampleInt\": 1," + + " \":topLevelKey:sampleBool\": \"false\"," + + " \":topLevelKey:sampleDouble\": 10.0," + + " \":topLevelKey:sampleString\": \"str\"}"; + JsonObject templateJson = GSON_HELPER.fromJson(jsonWithDifferentDataTypes, JsonObject.class); + + JsonObject result = utils.flatten(templateJson); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedResult, JsonObject.class)); + } + + @Test + void shouldHandleNullValues() { + String jsonWithNullValue = "{ \"topLevelKey\": {\"sampleNull\": null, \"sampleString\": \"str\"}}"; + String expectedResult = "{\":topLevelKey:sampleNull\": null," + + " \":topLevelKey:sampleString\": \"str\"}"; + JsonObject templateJson = GSON_HELPER.fromJson(jsonWithNullValue, JsonObject.class); + + JsonObject result = utils.flatten(templateJson); + + assertThat(result).isEqualTo(GSON_HELPER.fromJson(expectedResult, JsonObject.class)); + } + + @Test + void shouldFlattenBsonDocument() { + Document documentInput = Document.parse(NOTIFICATION_JSON); + + Document result = utils.flatten(documentInput); + + assertThat(result.toJson()).isEqualTo(EXPECTED_FLATTENED_NOTIFICATION); + } + + @Test + void shouldNotChangeEmptyBsonDocument() { + Document input = Document.parse("{}"); + + Document result = utils.flatten(input); + + assertThat(result.toJson()).isEqualTo("{ }"); + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/TemplateSearchHelperTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/TemplateSearchHelperTest.java new file mode 100644 index 0000000..01e06b1 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/TemplateSearchHelperTest.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.integration.simulators.nfsimulator.vesclient.template.search; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import org.assertj.core.util.Lists; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.integration.simulators.nfsimulator.vesclient.template.search.viewmodel.FlatTemplateContent; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.BasicQuery; +import org.springframework.data.mongodb.core.query.Query; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Java6Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyObject; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + + +class TemplateSearchHelperTest { + + private static final Gson GSON = new Gson(); + private static final String FLATTENED_TEMPLATES_VIEW = "flatTemplatesView"; + + @Mock + private MongoTemplate mongoTemplate; + + @InjectMocks + private TemplateSearchHelper helper; + + private static final ArgumentCaptor<Query> QUERY_CAPTOR = ArgumentCaptor.forClass(Query.class); + private static final ArgumentCaptor<String> COLLECTION_NAME_CAPTOR = ArgumentCaptor.forClass(String.class); + private static final ArgumentCaptor<Class<FlatTemplateContent>> CLASS_TYPE_CAPTOR = ArgumentCaptor.forClass((Class) FlatTemplateContent.class); + + + @BeforeEach + void setUp() { + initMocks(this); + } + + @Test + void shouldReturnNamesForGivenComposedSearchCriteria() { + String expectedComposedQueryString = "{\"$and\":[{\"keyValues\":{\"$elemMatch\":{\"k\":{\"$regex\":\":eventName(?:(\\\\[[\\\\d]+\\\\]))?$\",\"$options\":\"iu\"},\"v\":{\"$regex\":\"^\\\\QpnfRegistration_Nokia_5gDu\\\\E$\",\"$options\":\"iu\"}}}},{\"keyValues\":{\"$elemMatch\":{\"k\":{\"$regex\":\":sequence(?:(\\\\[[\\\\d]+\\\\]))?$\",\"$options\":\"iu\"},\"v\":1.0}}}]}"; + Query expectedQuery = new BasicQuery(expectedComposedQueryString); + + String composedCriteriaInputJson = "{\"eventName\": \"pnfRegistration_Nokia_5gDu\", \"sequence\": 1}"; + JsonObject composedCriteriaObject = GSON.fromJson(composedCriteriaInputJson, JsonObject.class); + + when(mongoTemplate.find(any(Query.class), anyObject(), any(String.class))).thenReturn(Lists.newArrayList(new FlatTemplateContent("sampleId1", null), new FlatTemplateContent("sampleId2", null))); + + List<String> idsOfDocumentMatchingCriteria = helper.getIdsOfDocumentMatchingCriteria(composedCriteriaObject); + + assertThat(idsOfDocumentMatchingCriteria).containsOnly("sampleId1", "sampleId2"); + verify(mongoTemplate, times(1)).find(QUERY_CAPTOR.capture(), CLASS_TYPE_CAPTOR.capture(), COLLECTION_NAME_CAPTOR.capture()); + assertThat(QUERY_CAPTOR.getValue().toString()).isEqualTo(expectedQuery.toString()); + assertThat(COLLECTION_NAME_CAPTOR.getValue()).isEqualTo(FLATTENED_TEMPLATES_VIEW); + assertThat(CLASS_TYPE_CAPTOR.getValue()).isEqualTo(FlatTemplateContent.class); + } + + @Test + void shouldReturnTemplatesAccordingToGivenSearchCriteria() { + Query expectedQueryStructure = new BasicQuery("{\"$and\":[{\"keyValues\": { \"$elemMatch\" : { \"k\" : { \"$regex\" : \":domain(?:(\\\\[[\\\\d]+\\\\]))?$\", \"$options\" : \"iu\" }, \"v\" : { \"$regex\" : \"^\\\\Qnotification\\\\E$\", \"$options\" : \"iu\" }}}}]}"); + + helper.getIdsOfDocumentMatchingCriteria(GSON.fromJson("{\"domain\": \"notification\"}", JsonObject.class)); + + + verify(mongoTemplate, times(1)).find(QUERY_CAPTOR.capture(), CLASS_TYPE_CAPTOR.capture(), COLLECTION_NAME_CAPTOR.capture()); + + assertThat(QUERY_CAPTOR.getValue().toString()).isEqualTo(expectedQueryStructure.toString()); + assertThat(COLLECTION_NAME_CAPTOR.getValue()).isEqualTo(FLATTENED_TEMPLATES_VIEW); + assertThat(CLASS_TYPE_CAPTOR.getValue()).isEqualTo(FlatTemplateContent.class); + } + + @Test + void shouldGetQueryForEmptyJson() { + JsonObject jsonObject = GSON.fromJson("{}", JsonObject.class); + + String expectedComposedQueryString = "{}"; + Query expectedQuery = new BasicQuery(expectedComposedQueryString); + + helper.getIdsOfDocumentMatchingCriteria(jsonObject); + + verify(mongoTemplate, times(1)).find(QUERY_CAPTOR.capture(), CLASS_TYPE_CAPTOR.capture(), COLLECTION_NAME_CAPTOR.capture()); + Query queryBasedOnCriteria = QUERY_CAPTOR.getValue(); + + assertThat(QUERY_CAPTOR.getValue().toString()).isEqualTo(expectedQuery.toString()); + assertThat(COLLECTION_NAME_CAPTOR.getValue()).isEqualTo(FLATTENED_TEMPLATES_VIEW); + assertThat(CLASS_TYPE_CAPTOR.getValue()).isEqualTo(FlatTemplateContent.class); + } + + + @Test + void shouldGetQueryWithAllTypeValues() { + JsonObject jsonObject = GSON.fromJson("{\"stringKey\": \"stringValue\", \"numberKey\": 16.00, \"boolKey\": false}", JsonObject.class); + + helper.getIdsOfDocumentMatchingCriteria(jsonObject); + + verify(mongoTemplate, times(1)).find(QUERY_CAPTOR.capture(), CLASS_TYPE_CAPTOR.capture(), COLLECTION_NAME_CAPTOR.capture()); + Query queryBasedOnCriteria = QUERY_CAPTOR.getValue(); + + assertThat(queryBasedOnCriteria.getQueryObject().get("$and")).isInstanceOf(List.class); + List<Document> conditionDocuments = new ArrayList<>((List<Document>) queryBasedOnCriteria.getQueryObject().get("$and")); + List<Document> conditions = conditionDocuments.stream().map(el -> (Document) el.get("keyValues")).map(el -> (Document) el.get("$elemMatch")).collect(Collectors.toList()); + + assertThat(conditionDocuments).hasSize(3); + assertJsonPreparedKeyHasCorrectStructure(conditions.get(0), "stringKey"); + assertThat(conditions.get(0).get("v").toString()).isEqualTo(TemplateSearchHelper.getCaseInsensitive("^\\QstringValue\\E$").toString()); + + assertJsonPreparedKeyHasCorrectStructure(conditions.get(1), "numberKey"); + assertThat(conditions.get(1).get("v")).isEqualTo(16.0); + + assertJsonPreparedKeyHasCorrectStructure(conditions.get(2), "boolKey"); + assertThat(conditions.get(2).get("v")).isEqualTo("false"); + } + + @Test + void shouldThrowExceptionWhenNullIsPresentAsCriteriaValue() { + JsonObject jsonObject = GSON.fromJson("{\"stringKey\": \"stringValue\", \"nullKey\": null}", JsonObject.class); + + assertThrows(IllegalJsonValueException.class, () -> helper.getIdsOfDocumentMatchingCriteria(jsonObject)); + } + + private void assertJsonPreparedKeyHasCorrectStructure(Document actual, String expectedPattern) { + assertThat(actual.get("k").toString()).isEqualTo(Pattern.compile(String.format(":%s(?:(\\[[\\d]+\\]))?$", expectedPattern)).toString()); + + } +} diff --git a/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/handler/PrimitiveValueCriteriaBuilderTest.java b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/handler/PrimitiveValueCriteriaBuilderTest.java new file mode 100644 index 0000000..2626253 --- /dev/null +++ b/src/test/java/org/onap/integration/simulators/nfsimulator/vesclient/template/search/handler/PrimitiveValueCriteriaBuilderTest.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * Simulator + * ================================================================================ + * Copyright (C) 2019 Nokia. 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.integration.simulators.nfsimulator.vesclient.template.search.handler; + +import com.google.gson.JsonPrimitive; +import org.junit.jupiter.api.Test; +import org.springframework.data.mongodb.core.query.Criteria; + +import static org.assertj.core.api.Java6Assertions.assertThat; + +class PrimitiveValueCriteriaBuilderTest { + + private PrimitiveValueCriteriaBuilder builder = new PrimitiveValueCriteriaBuilder(); + + @Test + void testShouldAddRegexLikeCriteriaForStringType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive("sample")); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : { \"$regex\" : \"^\\\\Qsample\\\\E$\", \"$options\" : \"iu\" } }"); + } + + @Test + void testShouldAddRegexLikeAndEscapeStringWithMetaChars() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive("[1,2,3,4,5]")); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : { \"$regex\" : \"^\\\\Q[1,2,3,4,5]\\\\E$\", \"$options\" : \"iu\" } }"); + } + + @Test + void testShouldAddRegexLikeCriteriaForIntType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(1)); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 1.0 }"); + } + + @Test + void testShouldAddRegexLikeCriteriaForLongType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(Long.MAX_VALUE)); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 9.223372036854776E18 }"); + } + + @Test + void testShouldAddRegexLikeCriteriaForDoubleType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(2.5)); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : 2.5 }"); + } + + @Test + void testShouldAddRegexLikeCriteriaForBooleanType() { + Criteria criteria = builder.applyValueCriteriaBasedOnPrimitiveType(Criteria.where("k").is("10").and("v"), new JsonPrimitive(true)); + + assertThat(criteria.getCriteriaObject().toJson()).isEqualTo("{ \"k\" : \"10\", \"v\" : \"true\" }"); + } + +} |