summaryrefslogtreecommitdiffstats
path: root/src/test/java/org/onap/dcaegen2/services/pmmapper/AppTest.java
blob: ce051e49ec67791c94c1983605dee2e4ea407bcc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*-
 * ============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 org.onap.dcaegen2.services.pmmapper;

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;
import static org.mockito.Mockito.when;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpResponse.response;
import static utils.ConfigUtils.getMapperConfigFromFile;

import java.io.IOException;
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;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.StatusCodes;
import org.junit.jupiter.api.BeforeEach;
import org.onap.dcaegen2.services.pmmapper.config.ConfigHandler;
import org.onap.dcaegen2.services.pmmapper.exceptions.CBSServerError;
import org.onap.dcaegen2.services.pmmapper.exceptions.EnvironmentConfigException;
import org.onap.dcaegen2.services.pmmapper.exceptions.MapperConfigException;

import org.onap.dcaegen2.services.pmmapper.utils.XMLValidator;
import reactor.core.publisher.Flux;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockserver.client.server.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.HttpRequest;
import org.onap.dcaegen2.services.pmmapper.filtering.MeasFilterHandler;
import org.onap.dcaegen2.services.pmmapper.mapping.Mapper;
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.utils.MeasConverter;
import org.onap.dcaegen2.services.pmmapper.utils.MeasSplitter;
import utils.EventUtils;


@ExtendWith(MockitoExtension.class)
class AppTest {

    static ClientAndServer mockServer;
    static MockServerClient client;

    private static EventMetadata eventMetadata;
    private static MapperConfig mapperConfig;
    private static ConfigHandler configHandler;

    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/schemas/");
    private static final String config = "valid_mapper_config.json";

    private App objUnderTest;


    @BeforeAll
    static void setup() {
        mockServer =  startClientAndServer(35454);
        client = new MockServerClient("127.0.0.1", 35454);
        mapperConfig = getMapperConfigFromFile(config);
    }

    @AfterAll
    static void teardown() {
        mockServer.stop();
    }

    @BeforeEach
    void beforeEach() {
        configHandler = mock(ConfigHandler.class);
    }

    @Test
    void testDisabledHTTPServer() throws Exception {

        MapperConfig mockConfig = Mockito.spy(mapperConfig);
        when(mockConfig.getEnableHttp()).thenReturn(false);
        when(configHandler.getMapperConfig()).thenReturn(mockConfig);
        objUnderTest = new App(template, schema, 0, 0, configHandler);
        objUnderTest.start();
        assertEquals(1, objUnderTest.getApplicationServer().getListenerInfo().size());
        assertEquals("https", objUnderTest.getApplicationServer().getListenerInfo().get(0).getProtcol());
        objUnderTest.stop();
    }

    @Test
    void testEnabledHTTPServer() throws Exception {
        MapperConfig mockConfig = Mockito.spy(mapperConfig);
        when(mockConfig.getEnableHttp()).thenReturn(true);
        when(configHandler.getMapperConfig()).thenReturn(mockConfig);
        objUnderTest = new App(template, schema, 0, 0, configHandler);
        objUnderTest.start();
        assertEquals(2, objUnderTest.getApplicationServer().getListenerInfo().size());
        assertEquals("http", objUnderTest.getApplicationServer().getListenerInfo().get(0).getProtcol());
        objUnderTest.stop();
    }

    @Test
    void testConfigFailure() throws EnvironmentConfigException, CBSServerError, MapperConfigException {
        when(configHandler.getMapperConfig()).thenThrow(MapperConfigException.class);
        assertThrows(IllegalStateException.class, () -> new App(template, schema, 0, 0, configHandler));

    }

    @Test
    void testServerCreationFailure() throws EnvironmentConfigException, CBSServerError, MapperConfigException {
        MapperConfig mockConfig = Mockito.spy(mapperConfig);
        when(mockConfig.getKeyStorePath()).thenReturn("not_a_file");
        when(configHandler.getMapperConfig()).thenReturn(mockConfig);
        assertThrows(IllegalStateException.class, () -> new App(template, schema, 0, 0, configHandler));

    }

    @Test
    void testHandleBackPressureNullValue() {
        assertThrows(NullPointerException.class, () -> App.handleBackPressure(null));
    }

    @Test
    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();
    }

    @Test
    void testReceiveRequestNullValue() {
        assertThrows(NullPointerException.class, () -> App.receiveRequest(null));
    }

    @Test
    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();
    }

    @Test
    void testFilterByFileType_success() {
        Event mockEvent = Mockito.mock(Event.class);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);

        HttpServerExchange exchange = Mockito.mock(HttpServerExchange.class);
        when(mockEvent.getHttpServerExchange()).thenReturn(exchange);
        when(exchange.getRequestPath()).thenReturn("ATEST.xml");

        boolean result = App.filterByFileType(new MeasFilterHandler(new MeasConverter()), mockEvent, mockConfig);
        assertTrue(result);
    }

    @Test
    void testFilterByFileType_NonXML() {
        Event mockEvent = Mockito.mock(Event.class);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);

        HttpServerExchange exchange = Mockito.mock(HttpServerExchange.class);
        when(mockEvent.getHttpServerExchange()).thenReturn(exchange);
        when(exchange.getRequestPath()).thenReturn("ATEST.png");

        boolean result = App.filterByFileType(new MeasFilterHandler(new MeasConverter()), mockEvent, mockConfig);
        assertFalse(result);
    }

    @Test
    void testFilterByFileType_throwException() {
        Event mockEvent = Mockito.mock(Event.class);
        MeasFilterHandler mockFilter = Mockito.mock(MeasFilterHandler.class);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);

        Mockito.when(mockFilter.filterByFileType(mockEvent)).thenThrow(RuntimeException.class);

        boolean result = App.filterByFileType(mockFilter, mockEvent, mockConfig);
        assertFalse(result);
    }

    @Test
    void testValidateXML_success() throws Exception {
        XMLValidator mockValidator = new XMLValidator(schema);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);

        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 + "/32.435/meas_results/test.xml");
        Event mockEvent = EventUtils.makeMockEvent(EventUtils.fileContentsToString(testFile), eventMetadata);

        boolean result = App.validate(mockValidator, mockEvent, mockConfig);

        assertTrue(result);
    }

    @Test
    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/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);
    }

    @Test
    void testValidateXML_throwException() {
        Event mockEvent = Mockito.mock(Event.class);
        XMLValidator mockValidator = Mockito.mock(XMLValidator.class);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);

        Mockito.when(mockValidator.validate(mockEvent)).thenThrow(RuntimeException.class);
        boolean result = App.validate(mockValidator, mockEvent, mockConfig);

        assertFalse(result);
    }

    @Test
    void testFilter_success() {
        Event mockEvent = Mockito.mock(Event.class);
        List<Event> mockEvents = Arrays.asList(mockEvent);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);
        boolean result = App.filter(new MeasFilterHandler(new MeasConverter()), mockEvents, mockConfig);
        assertTrue(result);
    }

    @Test
    void testFilter_throwException() {
        HttpRequest req = HttpRequest.request();
        client.when(req).respond( response().withStatusCode(200));

        Event mockEvent = Mockito.mock(Event.class);
        List<Event> mockEvents = Arrays.asList(mockEvent);
        MeasFilterHandler mockFilter = Mockito.mock(MeasFilterHandler.class);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);

        Mockito.when(mockConfig.getDmaapDRDeleteEndpoint()).thenReturn("http://127.0.0.1:35454");
        Mockito.when(mockConfig.getSubscriberIdentity()).thenReturn("sid");
        Mockito.when(mockEvent.getPublishIdentity()).thenReturn("pid");
        Mockito.when(mockFilter.filterByMeasType(mockEvent)).thenThrow(RuntimeException.class);

        boolean x = App.filter(mockFilter, mockEvents, mockConfig);
        assertFalse(x);

        client.clear(req);
    }

    @Test
    void testSplit_empty_success() {
        Event mockEvent = Mockito.mock(Event.class);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);
        MeasConverter mockMeasConverter = Mockito.mock(MeasConverter.class);
        Flux<List<Event>> splitResult = App.split(new MeasSplitter(mockMeasConverter), mockEvent, mockConfig);
        assertEquals(splitResult, Flux.<List<Event>>empty());
    }

    @Test
    void testSplit_success() {
        Event mockEvent = Mockito.mock(Event.class);
        List<Event> mockEvents = Arrays.asList(mockEvent,mockEvent);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);
        MeasSplitter mockSplitter  = Mockito.mock(MeasSplitter.class);
        Mockito.when(mockSplitter.split(mockEvent)).thenReturn(mockEvents);
        Flux<List<Event>> splitResult = App.split(mockSplitter, mockEvent, mockConfig);
        assertEquals(splitResult.toString(), Flux.just(mockEvents).toString());
    }

    @Test
    void testMapping_empty_success() {
        Event mockEvent = Mockito.mock(Event.class);
        MeasConverter mockMeasConverter = Mockito.mock(MeasConverter.class);
        List<Event> mockEvents = Arrays.asList(mockEvent);
        MapperConfig mockConfig = Mockito.mock(MapperConfig.class);
        Path mappingTemplate = Paths.get("src/main/resources/mapping.ftl");
        Flux<List<Event>> mappingResult = App.map(new Mapper(mappingTemplate,mockMeasConverter), mockEvents, mockConfig);
        assertEquals(mappingResult, Flux.<List<Event>>empty());
    }
}