From 255235644c8c302e1e92c41c13be3f3ad5973b16 Mon Sep 17 00:00:00 2001 From: JoeOLeary Date: Tue, 14 Jan 2020 10:54:59 +0000 Subject: Add support for TS 28.550/28.532 Issue-ID: DCAEGEN2-1912 Change-Id: If05c3673a240e6ea5e3d1caca3ff5bf5828590d3 Signed-off-by: JoeOLeary --- .../onap/dcaegen2/services/pmmapper/AppTest.java | 33 ++--- .../pmmapper/filtering/MeasFilterHandlerTest.java | 149 ++++++--------------- .../pmmapper/filtering/MetadataFilterTest.java | 45 +++++-- .../services/pmmapper/mapping/MapperTest.java | 107 ++++++++++----- .../pmmapper/utils/DataRouterUtilsTest.java | 8 +- .../services/pmmapper/utils/MeasConverterTest.java | 37 +++-- .../services/pmmapper/utils/MeasSplitterTest.java | 100 ++++++-------- .../services/pmmapper/utils/XMLValidatorTest.java | 62 ++++++--- src/test/java/utils/ArgumentCreator.java | 36 +++++ src/test/java/utils/EventUtils.java | 45 ++++++- 10 files changed, 357 insertions(+), 265 deletions(-) create mode 100644 src/test/java/utils/ArgumentCreator.java (limited to 'src/test/java') diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/AppTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/AppTest.java index 46994b3..ce051e4 100644 --- a/src/test/java/org/onap/dcaegen2/services/pmmapper/AppTest.java +++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/AppTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -37,6 +38,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import com.google.gson.Gson; @@ -83,7 +85,7 @@ class AppTest { private static final Path dataDirectory = Paths.get("src/test/resources/mapper_test/mapping_data/"); private static final Path metadata = Paths.get("src/test/resources/valid_metadata.json"); private static final Path template = Paths.get("src/main/resources/mapping.ftl"); - private static final Path schema = Paths.get("src/main/resources/measCollec_plusString.xsd"); + private static final Path schema = Paths.get("src/main/resources/schemas/"); private static final String config = "valid_mapper_config.json"; private App objUnderTest; @@ -153,8 +155,9 @@ class AppTest { } @Test - void testHandleBackPressure() { - Event event = utils.EventUtils.makeMockEvent("", mock(EventMetadata.class)); + void testHandleBackPressure() throws Exception{ + Event event = new Event(mock(HttpServerExchange.class, RETURNS_DEEP_STUBS), + "", mock(EventMetadata.class), new HashMap<>(), ""); App.handleBackPressure(event); verify(event.getHttpServerExchange(), times(1)).setStatusCode(StatusCodes.TOO_MANY_REQUESTS); verify(event.getHttpServerExchange(), times(1)).unDispatch(); @@ -166,8 +169,9 @@ class AppTest { } @Test - void testReceiveRequest() { - Event event = utils.EventUtils.makeMockEvent("", mock(EventMetadata.class)); + void testReceiveRequest() throws Exception { + Event event = new Event(mock(HttpServerExchange.class, RETURNS_DEEP_STUBS), + "", mock(EventMetadata.class), new HashMap<>(), ""); App.receiveRequest(event); verify(event.getHttpServerExchange(), times(1)).setStatusCode(StatusCodes.OK); verify(event.getHttpServerExchange(), times(1)).unDispatch(); @@ -212,14 +216,14 @@ class AppTest { } @Test - void testValidateXML_success() throws IOException { + void testValidateXML_success() throws Exception { XMLValidator mockValidator = new XMLValidator(schema); MapperConfig mockConfig = Mockito.mock(MapperConfig.class); - String metadataFileContents = new String(Files.readAllBytes(metadata)); + String metadataFileContents = new String(Files.readAllBytes(Paths.get(dataDirectory + "/32.435/meas_results/metadata.json"))); eventMetadata = new Gson().fromJson(metadataFileContents, EventMetadata.class); - Path testFile = Paths.get(dataDirectory + "/valid_data/meas_results.xml"); + Path testFile = Paths.get(dataDirectory + "/32.435/meas_results/test.xml"); Event mockEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testFile), eventMetadata); boolean result = App.validate(mockValidator, mockEvent, mockConfig); @@ -228,17 +232,16 @@ class AppTest { } @Test - void testValidateXML_failure() throws IOException { + void testValidateXML_failure() throws Exception { XMLValidator mockValidator = new XMLValidator(schema); MapperConfig mockConfig = Mockito.mock(MapperConfig.class); String metadataFileContents = new String(Files.readAllBytes(metadata)); eventMetadata = new Gson().fromJson(metadataFileContents, EventMetadata.class); - - Path testFile = Paths.get("src/test/resources/xml_validator_test/test_data/invalid/no_managed_element.xml"); - Event mockEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testFile), eventMetadata); - - boolean result = App.validate(mockValidator, mockEvent, mockConfig); + Path testFile = Paths.get("src/test/resources/xml_validator_test/test_data/lte/no_managed_element/test.xml"); + Event event = new Event(mock(HttpServerExchange.class, RETURNS_DEEP_STUBS), + EventUtils.fileContentsToString(testFile), eventMetadata, new HashMap<>(), ""); + boolean result = App.validate(mockValidator, event, mockConfig); assertFalse(result); } diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/filtering/MeasFilterHandlerTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/filtering/MeasFilterHandlerTest.java index 34b71f4..5cd1634 100644 --- a/src/test/java/org/onap/dcaegen2/services/pmmapper/filtering/MeasFilterHandlerTest.java +++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/filtering/MeasFilterHandlerTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,78 +26,49 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.List; -import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.onap.dcaegen2.services.pmmapper.model.Event; import org.onap.dcaegen2.services.pmmapper.model.EventMetadata; -import org.onap.dcaegen2.services.pmmapper.model.MeasCollecFile; import org.onap.dcaegen2.services.pmmapper.model.MeasFilterConfig; import org.onap.dcaegen2.services.pmmapper.model.MeasFilterConfig.Filter; +import org.onap.dcaegen2.services.pmmapper.model.measurement.common.MeasurementFile; import org.onap.dcaegen2.services.pmmapper.utils.MeasConverter; import io.undertow.server.HttpServerExchange; +import utils.ArgumentCreator; import utils.EventUtils; @ExtendWith(MockitoExtension.class) class MeasFilterHandlerTest { + private static final Path FILTER_DIRECTORY = Paths.get("src/test/resources/filter_test/"); private static final String baseDir = "src/test/resources/filter_test/"; - private static final Path dataDirectory = Paths.get("src/test/resources/mapper_test/mapping_data/"); private static MeasConverter converter = new MeasConverter(); private MeasFilterHandler objUnderTest; @Mock private HttpServerExchange exchange; - @Mock - private EventMetadata metaData; @BeforeEach void setup() { objUnderTest = new MeasFilterHandler(new MeasConverter()); } - @Test - void measTypes_byCommaSeparation() throws IOException { - String inputPath = baseDir + "meas_results"; - String expected = EventUtils.fileContentsToString(Paths.get(inputPath + "_filtered.xml")); - Event event = generateEvent(inputPath, generateValidFilter()); - - objUnderTest.filterByMeasType(event); - - String actual = converter.convert(event.getMeasCollecFile()); - assertEquals(expected, actual); - } - - @Test - void measType_byID() throws IOException { - String inputPath = baseDir + "meas_type_and_r"; - String filteredString = EventUtils.fileContentsToString(Paths.get(inputPath + "_filtered.xml")); - Event event = generateEvent(inputPath, generateValidFilter()); - MeasCollecFile f = converter.convert(filteredString); - String expected = converter.convert(f); - - objUnderTest.filterByMeasType(event); - - String actual = converter.convert(event.getMeasCollecFile()); - assertEquals(expected, actual); - } - @Test void skip_mapping_when_no_Filters_match() { - String inputPath = baseDir + "meas_results"; + String inputPath = baseDir + "lte/meas_results/test.xml"; Filter noMatchFilter = new MeasFilterConfig().new Filter(); noMatchFilter.setMeasTypes(Arrays.asList("nomatch1", "nomatch2")); Event event = generateEvent(inputPath, noMatchFilter); @@ -111,7 +82,7 @@ class MeasFilterHandlerTest { @Test void remove_events_that_does_not_match_filter() { - String inputPath = baseDir + "meas_type_and_r_manyInfo"; + String inputPath = baseDir + "lte/meas_type_and_r_manyinfo/test.xml"; Filter matchFilter = new MeasFilterConfig().new Filter(); matchFilter.setMeasTypes(Arrays.asList("a", "b")); @@ -129,71 +100,29 @@ class MeasFilterHandlerTest { @Test void skip_mapping_when_MeasData_isEmpty() { - String inputPath = baseDir + "meas_results"; + String inputPath = baseDir + "lte/meas_results/test.xml"; Event event = generateEvent(inputPath, generateValidFilter()); - event.getMeasCollecFile().replaceMeasData(Arrays.asList()); + event.getMeasurement().replacementMeasurementData(Arrays.asList()); assertFalse(objUnderTest.filterByMeasType(event)); } @Test void skip_filtering_if_filter_or_meastypes_isEmpty() { - String inputPath = baseDir + "meas_results"; + String inputPath = baseDir + "lte/meas_results/test.xml"; Filter emptyMeastypesFilter = new MeasFilterConfig().new Filter(); emptyMeastypesFilter.setMeasTypes(Arrays.asList()); Event event = generateEvent(inputPath, emptyMeastypesFilter); - MeasCollecFile originalMeasCollec = event.getMeasCollecFile(); + MeasurementFile originalMeasCollec = event.getMeasurement(); assertTrue(objUnderTest.filterByMeasType(event)); - assertEquals(originalMeasCollec,event.getMeasCollecFile()); + assertEquals(originalMeasCollec,event.getMeasurement()); event.setFilter(null); assertTrue(objUnderTest.filterByMeasType(event)); - assertEquals(originalMeasCollec,event.getMeasCollecFile()); - } - - @Test - void multiple_measInfos_measResults() { - String inputPath = baseDir + "meas_results_manyInfo"; - String filteredString = EventUtils.fileContentsToString(Paths.get(inputPath + "_filtered.xml")); - Event event = generateEvent(inputPath, generateValidFilter()); - - MeasCollecFile f = converter.convert(filteredString); - String expected = converter.convert(f); - objUnderTest.filterByMeasType(event); - - String actual = converter.convert(event.getMeasCollecFile()); - assertEquals(expected, actual); - } - - @Test - void multiple_measInfos_measTypeAndR() { - String inputPath = baseDir + "meas_type_and_r_manyInfo"; - String filteredString = EventUtils.fileContentsToString(Paths.get(inputPath + "_filtered.xml")); - Event event = generateEvent(inputPath, generateValidFilter()); - - MeasCollecFile f = converter.convert(filteredString); - String expected = converter.convert(f); - objUnderTest.filterByMeasType(event); - - String actual = converter.convert(event.getMeasCollecFile()); - assertEquals(expected, actual); - } - - @Test - void multiple_measValues() { - String inputPath = baseDir + "meas_type_and_r_manyMeasvalue"; - String filteredString = EventUtils.fileContentsToString(Paths.get(inputPath + "_filtered.xml")); - Event event = generateEvent(inputPath, generateValidFilter()); - - MeasCollecFile f = converter.convert(filteredString); - String expected = converter.convert(f); - objUnderTest.filterByMeasType(event); - - String actual = converter.convert(event.getMeasCollecFile()); - assertEquals(expected, actual); + assertEquals(originalMeasCollec,event.getMeasurement()); } @Test @@ -208,30 +137,34 @@ class MeasFilterHandlerTest { @Test void invalid_fileType() { Event event = mock(Event.class); - List invalidFiletypes = Arrays.asList("Bpm.xml","Dpm.xml","Apm.xml.gz","Apm.xm1","asdf","bsdf"); + List invalidFileTypes = Arrays.asList("Bpm.xml","Dpm.xml","Apm.xml.gz","Apm.xm1","asdf","bsdf"); when(event.getHttpServerExchange()).thenReturn(exchange); - when(exchange.getRequestPath()) - .thenReturn(invalidFiletypes.toString()); - - invalidFiletypes.forEach(c -> assertFalse(objUnderTest.filterByFileType(event))); + invalidFileTypes.forEach(fileName -> { + when(exchange.getRequestPath()) + .thenReturn(fileName); + assertFalse(objUnderTest.filterByFileType(event)); + }); } - @ParameterizedTest - @MethodSource("getValidMeas") - void applyFilterToValidMeasurements(Event testEvent) { + @MethodSource("getEvents") + void filter_valid_measurements(Event expectedEvent, Event testEvent) { objUnderTest.filterByMeasType(testEvent); + String actual = converter.convert(testEvent.getMeasurement()); + String expected = converter.convert(expectedEvent.getMeasurement()); + assertEquals(expected, actual); + } private Event generateEvent(String inputPath, Filter filter) { - String inputXml = EventUtils.fileContentsToString(Paths.get(inputPath + ".xml")); - Event event = new Event(exchange, inputXml, metaData, new HashMap<>(), ""); - event.setMeasCollecFile(converter.convert(inputXml)); + EventMetadata metadata = new EventMetadata(); + metadata.setFileFormatType(MeasConverter.LTE_FILE_TYPE); + Event event = EventUtils.makeMockEvent(EventUtils.fileContentsToString(Paths.get(inputPath)), metadata); event.setFilter(filter); return event; } - private Filter generateValidFilter() { + private static Filter generateValidFilter() { Filter filter; filter = new MeasFilterConfig().new Filter(); filter.setDictionaryVersion("1.0"); @@ -239,17 +172,17 @@ class MeasFilterHandlerTest { return filter; } - static List getValidMeas() throws IOException { - final Path metadata = Paths.get("src/test/resources/valid_metadata.json"); - List events = EventUtils - .eventsFromDirectory(Paths.get(dataDirectory.toString() + "/valid_data/"), metadata) - .stream() - .map(e -> { - MeasCollecFile m = converter.convert(e.getBody()); - e.setMeasCollecFile(m); - return e; - }) - .collect(Collectors.toList()); - return events; + private static List getEvents() { + ArgumentCreator creator = (Path path, EventMetadata metadata) -> { + Path expectedEventPath = Paths.get(path.toString()+"/expected.xml"); + Path testEventPath = Paths.get(path.toString()+"/test.xml"); + Event expectedEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(expectedEventPath), metadata); + Event testEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testEventPath), metadata); + testEvent.setFilter(generateValidFilter()); + return Arguments.of(expectedEvent, testEvent); + }; + return EventUtils.generateEventArguments(FILTER_DIRECTORY, "/nr", creator); + } + } diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/filtering/MetadataFilterTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/filtering/MetadataFilterTest.java index abe1b39..bf232ea 100644 --- a/src/test/java/org/onap/dcaegen2/services/pmmapper/filtering/MetadataFilterTest.java +++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/filtering/MetadataFilterTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,24 +20,34 @@ package org.onap.dcaegen2.services.pmmapper.filtering; +import com.google.gson.Gson; +import io.undertow.server.HttpServerExchange; +import java.io.IOException; +import java.nio.file.Files; +import java.util.HashMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.junit.jupiter.MockitoExtension; import org.onap.dcaegen2.services.pmmapper.model.Event; +import org.onap.dcaegen2.services.pmmapper.model.EventMetadata; import org.onap.dcaegen2.services.pmmapper.model.MapperConfig; import org.powermock.core.classloader.annotations.PrepareForTest; +import utils.ArgumentCreator; import utils.ConfigUtils; import utils.EventUtils; -import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; @ExtendWith(MockitoExtension.class) @PrepareForTest(MapperConfig.class) @@ -56,7 +66,7 @@ public class MetadataFilterTest { private static MapperConfig multipleFilterConfig; @BeforeEach - void setup() throws Exception { + void setup() { validConfig = ConfigUtils.getMapperConfigFromFile(VALID_MAPPER_CONFIG_FILE); noFilterConfig = ConfigUtils.getMapperConfigFromFile(NO_FILTER_CONFIG_FILE); multipleFilterConfig = ConfigUtils.getMapperConfigFromFile(MULTIPLE_FILTER_CONFIG_FILE); @@ -89,13 +99,30 @@ public class MetadataFilterTest { assertFalse(metadataFilter.filter(testEvent)); } - private static List getEventsWithValidMetadata() throws IOException { - Path validDataDirectory = Paths.get(DATA_DIRECTORY.toString() + "/valid/"); - return EventUtils.eventsFromDirectory(validDataDirectory, VALID_METADATA); + private static List getEventsWithValidMetadata() { + return getEvents(VALID_METADATA); } - private static List getEventsWithInvalidMetadata() throws IOException { - Path validDataDirectory = Paths.get(DATA_DIRECTORY.toString() + "/valid/"); - return EventUtils.eventsFromDirectory(validDataDirectory, INCORRECT_METADATA); + private static List getEventsWithInvalidMetadata() { + return getEvents(INCORRECT_METADATA); + } + + private static List getEvents(Path metadataFile) { + ArgumentCreator creator = (Path path, EventMetadata metadata) -> { + EventMetadata testMetadata = null; + try { + testMetadata = new Gson().fromJson(new String(Files.readAllBytes(metadataFile)), EventMetadata.class); + } catch (IOException e) { + fail("Failed to read contents of metadata file"); + } + testMetadata.setFileFormatType(metadata.getFileFormatType()); + Path testEventPath = Paths.get(path.toString()+"/test.xml"); + Event testEvent = new Event(mock( + HttpServerExchange.class, RETURNS_DEEP_STUBS), + EventUtils.fileContentsToString(testEventPath), testMetadata, new HashMap<>(), ""); + + return Arguments.of(testEvent); + }; + return EventUtils.generateEventArguments(DATA_DIRECTORY, "/nr", creator); } } \ No newline at end of file diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/mapping/MapperTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/mapping/MapperTest.java index f623d57..2356a57 100644 --- a/src/test/java/org/onap/dcaegen2/services/pmmapper/mapping/MapperTest.java +++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/mapping/MapperTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,8 @@ package org.onap.dcaegen2.services.pmmapper.mapping; -import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.doThrow; @@ -37,6 +37,7 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.HashMap; import java.util.List; import org.everit.json.schema.Schema; @@ -47,28 +48,33 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.junit.jupiter.MockitoExtension; import org.onap.dcaegen2.services.pmmapper.exceptions.MappingException; +import org.onap.dcaegen2.services.pmmapper.exceptions.TemplateIdentificationException; import org.onap.dcaegen2.services.pmmapper.model.Event; import org.onap.dcaegen2.services.pmmapper.model.EventMetadata; -import org.onap.dcaegen2.services.pmmapper.model.MeasCollecFile; import org.onap.dcaegen2.services.pmmapper.utils.MeasConverter; import org.powermock.reflect.Whitebox; +import utils.ArgumentCreator; import utils.EventUtils; @ExtendWith(MockitoExtension.class) class MapperTest { - private static EventMetadata eventMetadata; + private static EventMetadata fourthGenerationMetadata; + private static EventMetadata fifthGenerationMetadata; private static Schema vesSchema; private static MeasConverter converter; private Mapper objUnderTest; private static final Path schema = Paths.get("src/test/resources/mapper_test/CommonEventFormat_30.1-ONAP.json"); - private static final Path metadata = Paths.get("src/test/resources/valid_metadata.json"); - private static final Path mapping = Paths.get("src/main/resources/mapping.ftl"); + private static final Path METADATA_DIRECTORY = Paths.get("src/test/resources/metadata/"); + private static final Path FIFTH_GENERATION_METADATA = Paths.get(METADATA_DIRECTORY.toString()+"/valid_5g_metadata.json"); + private static final Path FOURTH_GENERATION_METADATA = Paths.get(METADATA_DIRECTORY.toString()+"/valid_4g_metadata.json"); + private static final Path TEMPLATES_DIRECTORY = Paths.get("src/main/resources/templates/"); private static final Path dataDirectory = Paths.get("src/test/resources/mapper_test/mapping_data/"); @@ -77,40 +83,60 @@ class MapperTest { JSONObject ves = new JSONObject(new String(Files.readAllBytes(schema))); vesSchema = SchemaLoader.load(ves); - String metadataFileContents = new String(Files.readAllBytes(metadata)); - eventMetadata = new Gson().fromJson(metadataFileContents, EventMetadata.class); - converter = mock(MeasConverter.class); + String fourthGenMetadataFileContents = new String(Files.readAllBytes(FOURTH_GENERATION_METADATA)); + fourthGenerationMetadata = new Gson().fromJson(fourthGenMetadataFileContents, EventMetadata.class); + String fifthGenMetadataFileContents = new String(Files.readAllBytes(FIFTH_GENERATION_METADATA)); + fifthGenerationMetadata = new Gson().fromJson(fifthGenMetadataFileContents, EventMetadata.class); + converter = new MeasConverter(); } @BeforeEach void setup() { - objUnderTest = new Mapper(mapping,converter); + objUnderTest = new Mapper(TEMPLATES_DIRECTORY, converter); } @ParameterizedTest @MethodSource("getValidEvents") void testValidEvent(Event testEvent) { - when(converter.convert(any(MeasCollecFile.class))).thenReturn(testEvent.getBody()); vesSchema.validate(new JSONObject(objUnderTest.map(testEvent))); } @Test - void testFailureToProcess() throws IOException, TemplateException { + void testFailureToProcessLte() throws Exception { Template mappingTemplateMock = mock(Template.class, RETURNS_DEEP_STUBS); doThrow(new TemplateException(mock(Environment.class))).when(mappingTemplateMock) .process(any(), any()); - Whitebox.setInternalState(objUnderTest, "mappingTemplate", mappingTemplateMock); - Path testFile = Paths.get(dataDirectory + "/valid_data/no_measdata.xml"); - Event testEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testFile), eventMetadata); + HashMap templates = new HashMap<>(); + templates.put("org.3GPP.32.435#measCollec", mappingTemplateMock); + Whitebox.setInternalState(objUnderTest, "templates", templates); + Path testFile = Paths.get(dataDirectory + "/32.435/no_measdata/test.xml"); + Event testEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testFile), fourthGenerationMetadata); + assertThrows(MappingException.class, () -> objUnderTest.map(testEvent)); + } + + @Test + void testFailureToProcessNr() throws Exception { + Template mappingTemplateMock = mock(Template.class, RETURNS_DEEP_STUBS); + doThrow(new TemplateException(mock(Environment.class))).when(mappingTemplateMock) + .process(any(), any()); + HashMap templates = new HashMap<>(); + templates.put("org.3GPP.28.550#measData", mappingTemplateMock); + Whitebox.setInternalState(objUnderTest, "templates", templates); + Path testFile = Paths.get(dataDirectory + "/28.550/no_measdata/test.xml"); + Event testEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testFile), fifthGenerationMetadata); + assertThrows(MappingException.class, () -> objUnderTest.map(testEvent)); + } + + @Test + void testFailureToParseLte() { assertThrows(MappingException.class, () -> - objUnderTest.map(testEvent)); + objUnderTest.map(EventUtils.makeMockEvent("not xml", fourthGenerationMetadata))); } @Test - void testFailureToParse() { - when(converter.convert(any(MeasCollecFile.class))).thenCallRealMethod(); + void testFailureToParseNr() { assertThrows(MappingException.class, () -> - objUnderTest.map(EventUtils.makeMockEvent("not xml", eventMetadata))); + objUnderTest.map(EventUtils.makeMockEvent("not xml", fifthGenerationMetadata))); } @Test @@ -118,6 +144,19 @@ class MapperTest { assertThrows(IllegalArgumentException.class, () -> new Mapper(Paths.get("not a path"),converter)); } + @Test + void testInvalidTemplateDirectory() { + assertThrows(IllegalArgumentException.class, () -> new Mapper(Paths.get("fake dir"), new MeasConverter())); + } + @Test + void testTemplateNotFound() { + EventMetadata testMetadata = mock(EventMetadata.class); + when(testMetadata.getFileFormatType()).thenReturn(MeasConverter.LTE_FILE_TYPE, "InvalidFormat"); + Path testFile = Paths.get(dataDirectory + "/32.435/no_measdata/test.xml"); + Event testEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testFile), testMetadata); + assertThrows(TemplateIdentificationException.class, () -> objUnderTest.map(testEvent)); + } + @Test void testNullPath() { assertThrows(NullPointerException.class, () -> new Mapper(null,converter)); @@ -133,22 +172,20 @@ class MapperTest { assertThrows(NullPointerException.class, () -> objUnderTest.map(mock(Event.class))); } - @Test - void testMapEvents() throws IOException { - List events = getValidEvents(); - List expectedEvents = objUnderTest.mapEvents(events); - expectedEvents.forEach(event -> { - when(converter.convert(any(MeasCollecFile.class))).thenReturn(event.getBody()); - assertNotNull(event.getVes()); - }); - } - - static List getValidEvents() throws IOException { - return EventUtils.eventsFromDirectory(Paths.get(dataDirectory.toString() + "/valid_data/"), metadata); - } - - static List getInvalidEvents() throws IOException { - return EventUtils.eventsFromDirectory(Paths.get(dataDirectory.toString() + "/invalid_data/"), metadata); + static List getValidEvents() { + ArgumentCreator creator = (Path path, EventMetadata metadata) -> { + Path testEventPath = Paths.get(path.toString()+"/test.xml"); + Path metadataPath = Paths.get(path.toString()+"/metadata.json"); + EventMetadata eventMetadata = null; + try { + eventMetadata = new Gson().fromJson(new String(Files.readAllBytes(metadataPath)), EventMetadata.class); + } catch (IOException e) { + fail("Failed to read contents of Metadata"); + } + Event testEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testEventPath), eventMetadata); + return Arguments.of(testEvent); + }; + return EventUtils.generateEventArguments(dataDirectory, "/28.550", creator); } } diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/DataRouterUtilsTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/DataRouterUtilsTest.java index b2e6308..c308840 100644 --- a/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/DataRouterUtilsTest.java +++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/DataRouterUtilsTest.java @@ -28,6 +28,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.undertow.server.HttpServerExchange; import java.io.ByteArrayInputStream; import java.net.HttpURLConnection; import java.net.URL; @@ -38,6 +39,7 @@ import java.nio.file.Paths; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; +import java.util.HashMap; import org.junit.Test; import org.junit.runner.RunWith; import org.onap.dcaegen2.services.pmmapper.exceptions.ProcessEventException; @@ -162,14 +164,16 @@ public class DataRouterUtilsTest { URL mockURL = mock(URL.class); HttpsURLConnection mockConnection = mock(HttpsURLConnection.class, RETURNS_DEEP_STUBS); when(mockConnection.getResponseCode()).thenReturn(503); - + EventMetadata metadata = new EventMetadata(); + metadata.setFileFormatType(MeasConverter.LTE_FILE_TYPE); when(mockURL.openConnection()).thenReturn(mockConnection); when(mockURL.getProtocol()).thenReturn("https"); when(mockMapperConfig.getDmaapDRDeleteEndpoint()).thenReturn("dmaap-dr-node/delete/"); when(mockMapperConfig.getSubscriberIdentity()).thenReturn("12"); PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL); - Event testEvent = EventUtils.makeMockEvent("", mock(EventMetadata.class)); + Event testEvent = new Event(mock( + HttpServerExchange.class, RETURNS_DEEP_STUBS), "", metadata, new HashMap<>(), "12"); assertThrows(ProcessEventException.class, () -> DataRouterUtils.processEvent(mockMapperConfig, testEvent)); } } diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/MeasConverterTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/MeasConverterTest.java index f51ec5c..c3412eb 100644 --- a/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/MeasConverterTest.java +++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/MeasConverterTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,21 +19,25 @@ */ package org.onap.dcaegen2.services.pmmapper.utils; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; -import java.io.StringReader; +import io.undertow.server.HttpServerExchange; import java.io.StringWriter; +import java.util.HashMap; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.onap.dcaegen2.services.pmmapper.exceptions.MappingException; -import org.onap.dcaegen2.services.pmmapper.model.MeasCollecFile; +import org.onap.dcaegen2.services.pmmapper.model.Event; +import org.onap.dcaegen2.services.pmmapper.model.EventMetadata; +import org.onap.dcaegen2.services.pmmapper.model.measurement.lte.MeasCollecFile; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @@ -68,16 +72,23 @@ public class MeasConverterTest { } @Test - public void convertToMeasCollec_throws_mappingException() throws JAXBException { - PowerMockito.mockStatic(JAXBContext.class); - Unmarshaller unmarshallerMock = PowerMockito.mock(Unmarshaller.class); - JAXBContext jaxbContext = PowerMockito.mock(JAXBContext.class); - PowerMockito.when(JAXBContext.newInstance(MeasCollecFile.class)).thenReturn(jaxbContext); - PowerMockito.when(jaxbContext.createUnmarshaller()).thenReturn(unmarshallerMock); - PowerMockito.when(unmarshallerMock.unmarshal(Mockito.any(StringReader.class))).thenThrow(JAXBException.class); + public void convertToMeasCollec_throws_mappingException() { + EventMetadata metadata = new EventMetadata(); + metadata.setFileFormatType(MeasConverter.LTE_FILE_TYPE); + Event event = new Event(mock(HttpServerExchange.class, RETURNS_DEEP_STUBS), "xmlString", metadata, new HashMap<>(), ""); + assertThrows(MappingException.class, () -> { + objUnderTest.convert(event); + }); + } + @Test + public void convertToMeasData_throws_mappingException() { + EventMetadata metadata = new EventMetadata(); + metadata.setFileFormatType(MeasConverter.NR_FILE_TYPE); + Event event = new Event(mock(HttpServerExchange.class, RETURNS_DEEP_STUBS), "xmlString", metadata, new HashMap<>(), ""); assertThrows(MappingException.class, () -> { - objUnderTest.convert("xmlString"); + objUnderTest.convert(event); }); } -} + +} \ No newline at end of file diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/MeasSplitterTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/MeasSplitterTest.java index 5028464..82921e6 100644 --- a/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/MeasSplitterTest.java +++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/MeasSplitterTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,98 +18,84 @@ * ============LICENSE_END========================================================= */ package org.onap.dcaegen2.services.pmmapper.utils; +import static junit.framework.TestCase.fail; import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Path; import java.nio.file.Paths; -import java.util.HashMap; import java.util.List; import java.util.NoSuchElementException; -import javax.xml.bind.JAXBException; +import java.util.Properties; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.onap.dcaegen2.services.pmmapper.model.Event; import org.onap.dcaegen2.services.pmmapper.model.EventMetadata; -import org.onap.dcaegen2.services.pmmapper.model.MapperConfig; -import org.onap.dcaegen2.services.pmmapper.model.MeasCollecFile; -import io.undertow.server.HttpServerExchange; +import utils.ArgumentCreator; import utils.EventUtils; @ExtendWith(MockitoExtension.class) class MeasSplitterTest { private static final String baseDir = "src/test/resources/split_test/"; private MeasSplitter objUnderTest; - private MeasConverter converter; - @Mock - HttpServerExchange exchange; - @Mock - EventMetadata meta; - @Mock - Event event; - @Mock - MapperConfig config; @BeforeEach void setup() { - converter = new MeasConverter(); - objUnderTest = new MeasSplitter(converter); - } - - void setupBaseEvent() { - Mockito.when(event.getHttpServerExchange()).thenReturn(exchange); - Mockito.when(event.getMetadata()).thenReturn(meta); - Mockito.when(event.getMdc()).thenReturn(new HashMap<>()); - Mockito.when(event.getMetadata()).thenReturn(meta); - Mockito.when(event.getPublishIdentity()).thenReturn(""); + objUnderTest = new MeasSplitter(new MeasConverter()); } - @Test void no_measData() { String inputPath = baseDir + "no_measdata"; + EventMetadata metadata = new EventMetadata(); + metadata.setFileFormatType(MeasConverter.LTE_FILE_TYPE); String inputXml = EventUtils.fileContentsToString(Paths.get(inputPath + ".xml")); - Mockito.when(event.getBody()).thenReturn(inputXml); + Event testEvent = EventUtils.makeMockEvent(inputXml, metadata); - Assertions.assertThrows(NoSuchElementException.class, () -> objUnderTest.split(event)); + assertThrows(NoSuchElementException.class, () -> objUnderTest.split(testEvent)); } - @Test - void typeA_returns_only_one_event() throws JAXBException { - String inputPath = baseDir + "meas_results_typeA"; - String inputXml = EventUtils.fileContentsToString(Paths.get(inputPath + ".xml")); - MeasCollecFile measToBeSplit = converter.convert(inputXml); - setupBaseEvent(); - Mockito.when(event.getBody()).thenReturn(inputXml); - Mockito.when(event.getMeasCollecFile()).thenReturn(measToBeSplit); - - List splitEvents = objUnderTest.split(event); - assertEquals(1,splitEvents.size()); + @ParameterizedTest + @MethodSource("getEvents") + void testSplit(int numberOfEvents, String[] measInfoIds, Event testEvent) { + List splitEvents = objUnderTest.split(testEvent); + assertEquals(numberOfEvents, splitEvents.size()); + for (int i = 0; i splitEvents = objUnderTest.split(event); - assertEquals(3,splitEvents.size()); - for (int i = 0; i < splitEvents.size(); i++) { - String measInfoId = splitEvents.get(i).getMeasCollecFile() - .getMeasData().get(0).getMeasInfo().get(0).getMeasInfoId(); - Assertions.assertEquals(measInfoId, "measInfoId" + (i + 1)); - } + private static List getEvents() { + ArgumentCreator splitterCreator = (Path path, EventMetadata metadata) -> { + Path propsPath = Paths.get(path.toString()+"/split.props"); + Path testEventPath = Paths.get(path.toString()+"/test.xml"); + Properties splitProperties = new Properties(); + try { + splitProperties.load(new FileInputStream(propsPath.toFile())); + } catch (IOException e) { + fail("Failed to load properties for test"); + } + int numberOfEvents = Integer.parseInt(splitProperties.getProperty("eventCount")); + String [] measInfoIds = splitProperties.getProperty("measInfoIds").split(","); + Event testEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testEventPath), metadata); + return Arguments.of(numberOfEvents, measInfoIds, testEvent); + }; + return EventUtils.generateEventArguments(Paths.get(baseDir), "/nr", splitterCreator); } } diff --git a/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/XMLValidatorTest.java b/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/XMLValidatorTest.java index aca0fe6..cc39563 100644 --- a/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/XMLValidatorTest.java +++ b/src/test/java/org/onap/dcaegen2/services/pmmapper/utils/XMLValidatorTest.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019 - 2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,35 +20,43 @@ package org.onap.dcaegen2.services.pmmapper.utils; -import static org.junit.jupiter.api.Assertions.assertFalse; +import static junit.framework.TestCase.fail; +import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; +import io.undertow.server.HttpServerExchange; +import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.HashMap; import java.util.List; +import java.util.Properties; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.junit.jupiter.MockitoExtension; import org.onap.dcaegen2.services.pmmapper.model.Event; +import org.onap.dcaegen2.services.pmmapper.model.EventMetadata; +import utils.ArgumentCreator; import utils.EventUtils; @ExtendWith(MockitoExtension.class) class XMLValidatorTest { - private static final Path metadata = Paths.get("src/test/resources/valid_metadata.json"); private static final Path dataDirectory = Paths.get("src/test/resources/xml_validator_test/test_data/"); - private static final Path xsd = Paths.get("src/main/resources/measCollec_plusString.xsd"); + private static final Path schemas = Paths.get("src/main/resources/schemas/"); private XMLValidator objUnderTest; @BeforeEach void setup() { - objUnderTest = new XMLValidator(xsd); + objUnderTest = new XMLValidator(schemas); } @Test @@ -62,26 +70,38 @@ class XMLValidatorTest { assertThrows(NullPointerException.class, () -> objUnderTest.validate(null)); } - @ParameterizedTest - @MethodSource("getValidEvents") - void testValidEventsPass(Event testEvent) { - assertTrue(objUnderTest.validate(testEvent)); + @Test + void testInvalidSchemaDirectory() { + assertThrows(IllegalArgumentException.class, () -> new XMLValidator(Paths.get("fake dir"))); } - @ParameterizedTest - @MethodSource("getInvalidEvents") - void testInvalidEventsFail(Event testEvent) { - assertFalse(objUnderTest.validate(testEvent)); + @Test + void testInvalidSchemaFormat() { + assertThrows(IllegalArgumentException.class, () -> new XMLValidator(Paths.get("src/test/resources/invalid_configs"))); } - private static List getValidEvents() throws IOException { - Path validDataDirectory = Paths.get(dataDirectory.toString() + "/valid/"); - return EventUtils.eventsFromDirectory(validDataDirectory, metadata); + @ParameterizedTest + @MethodSource("getEvents") + void testXmlValidation(boolean validity, Event testEvent) { + assertEquals(validity, objUnderTest.validate(testEvent)); } - private static List getInvalidEvents() throws IOException { - Path invalidDataDirectory = Paths.get(dataDirectory.toString() + "/invalid/"); - return EventUtils.eventsFromDirectory(invalidDataDirectory, metadata); + private static List getEvents() { + ArgumentCreator creator = (Path path, EventMetadata metadata) -> { + Path props = Paths.get(path.toString()+"/validity.props"); + Path testEventPath = Paths.get(path.toString()+"/test.xml"); + Properties validityProps = new Properties(); + try { + validityProps.load(new FileInputStream(props.toFile())); + } catch (IOException e) { + fail("Failed to load properties for test"); + } + boolean valid = Boolean.parseBoolean(validityProps.getProperty("valid")); + Event testEvent = new Event(mock( + HttpServerExchange.class, RETURNS_DEEP_STUBS), + EventUtils.fileContentsToString(testEventPath), metadata, new HashMap<>(), ""); + return Arguments.of(valid, testEvent); + }; + return EventUtils.generateEventArguments(dataDirectory, "/nr", creator); } - } diff --git a/src/test/java/utils/ArgumentCreator.java b/src/test/java/utils/ArgumentCreator.java new file mode 100644 index 0000000..a552a0c --- /dev/null +++ b/src/test/java/utils/ArgumentCreator.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2019 - 2020 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package utils; + +import java.nio.file.Path; +import org.junit.jupiter.params.provider.Arguments; +import org.onap.dcaegen2.services.pmmapper.model.EventMetadata; + +public interface ArgumentCreator { + + /** + * Makes an Argument containing an event from an path to an XML body and a corresponding metadata object. + * @param path path to file containing xml. + * @param metadata instance of a metadata object with fileFormatType set. + * @return Arguments containing what is necessary for a test to complete its checks. + */ + public Arguments makeArgument(Path path, EventMetadata metadata); +} diff --git a/src/test/java/utils/EventUtils.java b/src/test/java/utils/EventUtils.java index 0051629..ffa02b0 100644 --- a/src/test/java/utils/EventUtils.java +++ b/src/test/java/utils/EventUtils.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * Copyright (C) 2019 Nordix Foundation. + * Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,13 +29,17 @@ import io.undertow.server.HttpServerExchange; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; +import java.util.stream.Stream; +import junit.framework.TestCase; +import org.junit.jupiter.params.provider.Arguments; import org.onap.dcaegen2.services.pmmapper.model.Event; import org.onap.dcaegen2.services.pmmapper.model.EventMetadata; -import org.onap.dcaegen2.services.pmmapper.model.MeasCollecFile; +import org.onap.dcaegen2.services.pmmapper.utils.MeasConverter; public class EventUtils { @@ -55,6 +59,27 @@ public class EventUtils { .map(contents -> EventUtils.makeMockEvent(contents, eventMetadata)) .collect(Collectors.toList()); } + /** + * Create a List of Arguments containing an Event (Defaults to LTE events), and an expected outcome. + * Fails test in the event of failure to read a file. + * @param baseDirectory Directory containing multiple formats of events separated by a directory. + * @param nrQualifier String representing a unique part of the path that will exist only in the NR path. + * @param argCreator Callback to method that will generate the appropriate set of arguments for each test. + */ + public static List generateEventArguments(Path baseDirectory, String nrQualifier, ArgumentCreator argCreator ) { + List events = new ArrayList<>(); + try (Stream paths = Files.list(baseDirectory)) { + paths.filter(Files::isDirectory).forEach(path -> { + String fileFormatType = path.toString().contains(nrQualifier) ? MeasConverter.NR_FILE_TYPE : MeasConverter.LTE_FILE_TYPE; + EventMetadata eventMetadata = new EventMetadata(); + eventMetadata.setFileFormatType(fileFormatType); + events.addAll(getEventsArgument(path, eventMetadata, argCreator)); + }); + } catch (IOException e) { + TestCase.fail("IOException occurred while generating test data"); + } + return events; + } /** * reads contents of file into a string. @@ -75,15 +100,14 @@ public class EventUtils { * Makes an event with a mock http server exchange, empty mdc and publish identity * @param body body for the event. * @param eventMetadata metadata for the event. - * @return event with mock HttpServerExchange + * @return event with mock HttpServerExchange. */ public static Event makeMockEvent(String body, EventMetadata eventMetadata) { Event event = new Event(mock(HttpServerExchange.class, RETURNS_DEEP_STUBS), body, eventMetadata, new HashMap<>(), ""); - event.setMeasCollecFile(new MeasCollecFile()); + event.setMeasurement(new MeasConverter().convert(event)); return event; } - /** * Makes an event with a mock http server exchange and empty mdc * @param body body for the event. @@ -95,5 +119,16 @@ public class EventUtils { return new Event(mockHttpServerExchange, body, eventMetadata, new HashMap<>(), publishIdentity); } + private static List getEventsArgument(Path basePath, EventMetadata metadata, ArgumentCreator argCreator) { + List events = new ArrayList<>(); + try (Stream paths = Files.list(basePath)) { + paths.filter(Files::isDirectory).forEach(path->{ + events.add(argCreator.makeArgument(path, metadata)); + }); + } catch (IOException e) { + TestCase.fail("IOException occurred while generating test data"); + } + return events; + } } -- cgit 1.2.3-korg