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

import com.google.gson.JsonObject;
import io.vavr.collection.Stream;
import org.jetbrains.annotations.NotNull;
import org.junit.Rule;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.onap.dcaegen2.services.sdk.model.streams.RawDataStream;
import org.onap.dcaegen2.services.sdk.model.streams.dmaap.KafkaSink;
import org.onap.dcaegen2.services.sdk.model.streams.dmaap.KafkaSource;
import org.onap.dcaegen2.services.sdk.model.streams.dmaap.MessageRouterSink;
import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.exceptions.HttpException;
import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.test.DummyHttpServer;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClient;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsRequests;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.exceptions.EnvironmentParsingException;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.exceptions.StreamParsingException;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.DataStreams;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParser;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamFromGsonParsers;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsClientConfiguration;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsRequest;
import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.ImmutableCbsClientConfiguration;
import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;

import java.time.Duration;

import static org.assertj.core.api.Assertions.assertThat;
import static org.onap.dcaegen2.services.sdk.model.streams.StreamType.KAFKA;
import static org.onap.dcaegen2.services.sdk.model.streams.StreamType.MESSAGE_ROUTER;
import static org.onap.dcaegen2.services.sdk.rest.services.adapters.http.test.DummyHttpServer.sendResource;
import static org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.streams.StreamPredicates.streamOfType;

/**
 * @author <a href="mailto:piotr.jaszczyk@nokia.com">Piotr Jaszczyk</a>
 * @since February 2019
 */
class CbsClientImplIT {

    private static final String SAMPLE_CONFIG = "/sample_service_config.json";
    private static final String SAMPLE_ALL = "/sample_all.json";
    private static final String SAMPLE_KEY = "/sample_key.json";
    private static final String SAMPLE_CONFIG_KEY = "keystore.path";
    private static final String EXPECTED_CONFIG_VALUE_FROM_CBS = "/var/run/security/keystore.p12";
    private static final String CONFIG_MAP_FILE_PATH = "src/test/resources/application_config.yaml";
    private static CbsClientConfiguration sampleConfigurationCbsSource;
    private static CbsClientConfiguration sampleConfigurationFileSource;
    private static DummyHttpServer server;


    @Rule
    public final EnvironmentVariables envs = new EnvironmentVariables();

    @BeforeAll
    static void setUp() {
        server = DummyHttpServer.start(routes ->
                routes.get("/service_component/dcae-component", (req, resp) -> sendResource(resp, SAMPLE_CONFIG))
                        .get("/service_component_all/dcae-component", (req, resp) -> sendResource(resp, SAMPLE_ALL))
                        .get("/sampleKey/dcae-component", (req, resp) -> sendResource(resp, SAMPLE_KEY))
        );
        ImmutableCbsClientConfiguration.Builder configBuilder = getConfigBuilder();
        sampleConfigurationCbsSource = configBuilder.build();
        sampleConfigurationFileSource = configBuilder.configMapFilePath(CONFIG_MAP_FILE_PATH).build();
    }

    @AfterAll
    static void tearDown() {
        server.close();
    }

    @Test
    void testCbsClientWithSingleCall() {
        // given
        envs.set("AAF_USER", "admin");
        envs.set("AAF_PASSWORD", "admin_secret");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationCbsSource);
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());

        // when
        final Mono<JsonObject> result = sut.flatMap(cbsClient -> cbsClient.get(request));

        // then
        StepVerifier.create(result.map(this::sampleConfigValue))
                .expectNext(EXPECTED_CONFIG_VALUE_FROM_CBS)
                .expectComplete()
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWithPeriodicCall() {
        // given
        envs.set("AAF_USER", "admin");
        envs.set("AAF_PASSWORD", "admin_secret");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationCbsSource);
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());

        // when
        final Flux<JsonObject> result = sut
                .flatMapMany(cbsClient -> cbsClient.get(request, Duration.ZERO, Duration.ofMillis(10)));

        // then
        final int itemsToTake = 5;
        StepVerifier.create(result.take(itemsToTake).map(this::sampleConfigValue))
                .expectNextSequence(Stream.of(EXPECTED_CONFIG_VALUE_FROM_CBS).cycle(itemsToTake))
                .expectComplete()
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWithUpdatesCall() {
        // given
        envs.set("AAF_USER", "admin");
        envs.set("AAF_PASSWORD", "admin_secret");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationCbsSource);
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());
        final Duration period = Duration.ofMillis(10);

        // when
        final Flux<JsonObject> result = sut
                .flatMapMany(cbsClient -> cbsClient.updates(request, Duration.ZERO, period));

        // then
        final Duration timeToCollectItemsFor = period.multipliedBy(50);
        StepVerifier.create(result.take(timeToCollectItemsFor).map(this::sampleConfigValue))
                .expectNext(EXPECTED_CONFIG_VALUE_FROM_CBS)
                .expectComplete()
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWithConfigRetrievedFromFileMissingEnv() {
        // given
        envs.set("AAF_USER", "");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationFileSource);
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());

        // when
        final Mono<JsonObject> result = sut.flatMap(cbsClient -> cbsClient.get(request));

        // then
        StepVerifier.create(result)
                .expectErrorSatisfies(ex -> {
                    assertThat(ex).isInstanceOf(EnvironmentParsingException.class);
                    assertThat(ex).hasMessageContaining("Cannot read AAF_USER from environment.");
                })
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWithConfigRetrievedFromFile() {
        // given
        envs.set("AAF_USER", "admin");
        envs.set("AAF_PASSWORD", "admin_secret");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationFileSource);
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());

        // when
        final Mono<JsonObject> result = sut.flatMap(cbsClient -> cbsClient.get(request));

        // then
        StepVerifier.create(result.map(this::sampleConfigValue))
                .expectNext(EXPECTED_CONFIG_VALUE_FROM_CBS)
                .expectComplete()
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWithStreamsParsing() {
        // given
        envs.set("AAF_USER", "admin");
        envs.set("AAF_PASSWORD", "admin_secret");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationCbsSource);
        final StreamFromGsonParser<KafkaSink> kafkaSinkParser = StreamFromGsonParsers.kafkaSinkParser();
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());

        // when
        final Mono<KafkaSink> result = sut.flatMap(cbsClient -> cbsClient.get(request))
                .map(json ->
                        DataStreams.namedSinks(json).map(kafkaSinkParser::unsafeParse).head()
                );

        // then
        StepVerifier.create(result)
                .consumeNextWith(kafkaSink -> {
                    assertThat(kafkaSink.name()).isEqualTo("perf3gpp");
                    assertThat(kafkaSink.bootstrapServers()).isEqualTo("dmaap-mr-kafka:6060");
                    assertThat(kafkaSink.topicName()).isEqualTo("HVVES_PERF3GPP");
                })
                .expectComplete()
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWithStreamsParsingUsingSwitch() {
        // given
        envs.set("AAF_USER", "admin");
        envs.set("AAF_PASSWORD", "admin_secret");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationCbsSource);
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());
        // TODO: Use these parsers below
        final StreamFromGsonParser<KafkaSink> kafkaSinkParser = StreamFromGsonParsers.kafkaSinkParser();
        final StreamFromGsonParser<MessageRouterSink> mrSinkParser = StreamFromGsonParsers.messageRouterSinkParser();

        // when
        final Mono<Void> result = sut.flatMap(cbsClient -> cbsClient.get(request))
                .map(json -> {
                    final Stream<RawDataStream<JsonObject>> sinks = DataStreams.namedSinks(json);

                    final Stream<KafkaSink> allKafkaSinks = sinks.filter(streamOfType(KAFKA))
                            .map(kafkaSinkParser::unsafeParse);
                    final Stream<MessageRouterSink> allMrSinks = sinks.filter(streamOfType(MESSAGE_ROUTER))
                            .map(mrSinkParser::unsafeParse);

                    assertThat(allKafkaSinks.size())
                            .describedAs("Number of kafka sinks")
                            .isEqualTo(2);
                    assertThat(allMrSinks.size())
                            .describedAs("Number of DMAAP-MR sinks")
                            .isEqualTo(1);

                    return true;
                })
                .then();

        // then
        StepVerifier.create(result)
                .expectComplete()
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWithStreamsParsingWhenUsingInvalidParser() {
        // given
        envs.set("AAF_USER", "admin");
        envs.set("AAF_PASSWORD", "admin_secret");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationCbsSource);
        final StreamFromGsonParser<KafkaSource> kafkaSourceParser = StreamFromGsonParsers.kafkaSourceParser();
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());

        // when
        final Mono<KafkaSource> result = sut.flatMap(cbsClient -> cbsClient.get(request))
                .map(json ->
                        DataStreams.namedSources(json).map(kafkaSourceParser::unsafeParse).head()
                );

        // then
        StepVerifier.create(result)
                .expectErrorSatisfies(ex -> {
                    assertThat(ex).isInstanceOf(StreamParsingException.class);
                    assertThat(ex).hasMessageContaining("Invalid stream type");
                    assertThat(ex).hasMessageContaining(MESSAGE_ROUTER.toString());
                    assertThat(ex).hasMessageContaining(KAFKA.toString());
                })
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWithSingleAllRequest() {
        // given
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationCbsSource);
        final CbsRequest request = CbsRequests.getAll(RequestDiagnosticContext.create());

        // when
        final Mono<JsonObject> result = sut.flatMap(cbsClient -> cbsClient.get(request));

        // then
        StepVerifier.create(result)
                .assertNext(json -> {
                    assertThat(json.get("config")).isNotNull();
                    assertThat(json.get("policies")).isNotNull();
                    assertThat(json.get("sampleKey")).isNotNull();
                })
                .expectComplete()
                .verify(Duration.ofSeconds(5));
    }


    @Test
    void testCbsClientWithSingleKeyRequest() {
        // given
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(sampleConfigurationCbsSource);
        final CbsRequest request = CbsRequests.getByKey(RequestDiagnosticContext.create(), "sampleKey");

        // when
        final Mono<JsonObject> result = sut.flatMap(cbsClient -> cbsClient.get(request));

        // then
        StepVerifier.create(result)
                .assertNext(json -> {
                    assertThat(json.get("key")).isNotNull();
                    assertThat(json.get("key").getAsString()).isEqualTo("value");
                })
                .expectComplete()
                .verify(Duration.ofSeconds(5));
    }

    @Test
    void testCbsClientWhenTheConfigurationWasNotFound() {
        // given
        final CbsClientConfiguration unknownAppEnv = ImmutableCbsClientConfiguration.copyOf(sampleConfigurationCbsSource).withAppName("unknown_app");
        final Mono<CbsClient> sut = CbsClientFactory.createCbsClient(unknownAppEnv);
        final CbsRequest request = CbsRequests.getConfiguration(RequestDiagnosticContext.create());

        // when
        final Mono<JsonObject> result = sut.flatMap(cbsClient -> cbsClient.get(request));

        // then
        StepVerifier.create(result)
                .expectError(HttpException.class)
                .verify(Duration.ofSeconds(5));
    }

    @NotNull
    private static ImmutableCbsClientConfiguration.Builder getConfigBuilder() {
        return ImmutableCbsClientConfiguration.builder()
                .protocol("http")
                .appName("dcae-component")
                .hostname(server.host())
                .port(server.port());
    }

    private String sampleConfigValue(JsonObject obj) {
        return obj.get(SAMPLE_CONFIG_KEY).getAsString();
    }

}