eedc961cd8cd258083200524ed8a0e95c2f5d2b7
[cps.git] /
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (c) 2023-2025 OpenInfra Foundation Europe. All rights reserved.
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an 'AS IS' BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.ncmp.impl.datajobs.subscription.cmavc
22
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import io.cloudevents.CloudEvent
25 import io.cloudevents.core.builder.CloudEventBuilder
26 import io.cloudevents.kafka.CloudEventDeserializer
27 import io.cloudevents.kafka.impl.KafkaHeaders
28 import org.apache.kafka.clients.consumer.ConsumerRecord
29 import org.apache.kafka.clients.consumer.KafkaConsumer
30 import org.onap.cps.events.EventsProducer
31 import org.onap.cps.ncmp.api.inventory.models.CompositeState
32 import org.onap.cps.ncmp.events.avc1_0_0.AvcEvent
33 import org.onap.cps.ncmp.impl.inventory.InventoryPersistence
34 import org.onap.cps.ncmp.utils.events.MessagingBaseSpec
35 import org.onap.cps.utils.JsonObjectMapper
36 import org.spockframework.spring.SpringBean
37 import org.springframework.beans.factory.annotation.Autowired
38 import org.springframework.boot.test.context.SpringBootTest
39 import org.springframework.test.annotation.DirtiesContext
40 import org.testcontainers.spock.Testcontainers
41
42 import java.nio.charset.Charset
43 import java.time.Duration
44
45 import static org.onap.cps.ncmp.utils.TestUtils.getResourceFileContent
46 import static org.onap.cps.ncmp.utils.events.CloudEventMapper.toTargetEvent
47
48 @SpringBootTest(classes = [EventsProducer, CmAvcEventConsumer, ObjectMapper, JsonObjectMapper])
49 @Testcontainers
50 @DirtiesContext
51 class CmAvcEventConsumerSpec extends MessagingBaseSpec {
52
53     @SpringBean
54     EventsProducer eventsProducer = new EventsProducer(legacyEventKafkaTemplate, cloudEventKafkaTemplate, cloudEventKafkaTemplateForEos)
55
56     def mockCmAvcEventService = Mock(CmAvcEventService)
57     def mockInventoryPersistence = Mock(InventoryPersistence)
58
59     @SpringBean
60     CmAvcEventConsumer objectUnderTest = new CmAvcEventConsumer(eventsProducer, mockCmAvcEventService, mockInventoryPersistence)
61
62     @Autowired
63     JsonObjectMapper jsonObjectMapper
64
65     def cloudEventKafkaConsumer = new KafkaConsumer<>(eventConsumerConfigProperties('group for Test A', CloudEventDeserializer))
66
67     def testEventKey = 'sample-key'
68     def validAvcEventAsJson
69     def onapDmiSourceSystem = 'ONAP-DMI-PLUGIN'
70
71     def setup() {
72         validAvcEventAsJson = jsonObjectMapper.convertJsonString(getResourceFileContent('sampleAvcInputEvent.json'), AvcEvent.class)
73     }
74
75     def 'Consume and forward avc event [test A, using specific topic].'() {
76         given: 'a cloud event'
77             def testCloudEventSent = buildCloudEvent('sample-source', 'test-cmhandle1', validAvcEventAsJson)
78         and: 'consumer has a subscription on the target topic for this test'
79             objectUnderTest.cmEventsTopicName = 'target-topic-for-Test-A'
80             cloudEventKafkaConsumer.subscribe([objectUnderTest.cmEventsTopicName])
81         and: 'event is wrapped in a consumer record with message key(cmHandleId) and value as cloud event'
82             def consumerRecordReceived = new ConsumerRecord<String, CloudEvent>(objectUnderTest.cmEventsTopicName, 0, 0, testEventKey, testCloudEventSent)
83         when: 'the event is consumed and forwarded to target topic'
84             objectUnderTest.consumeAndForward(consumerRecordReceived)
85         then: 'the consumer record can be read from the target topic within 2 seconds'
86             def consumerRecordOnTargetTopic = cloudEventKafkaConsumer.poll(Duration.ofMillis(2000)).iterator().next()
87         and: 'the target event has the same key as the source event to maintain the ordering in a partition'
88             def cloudEventFromTargetTopic = consumerRecordOnTargetTopic.value() as CloudEvent
89             def avcEventFromTargetTopic = toTargetEvent(cloudEventFromTargetTopic, AvcEvent.class)
90             assert consumerRecordOnTargetTopic.key() == consumerRecordReceived.key()
91         and: 'we have correct headers forwarded where correlation id matches'
92             assert KafkaHeaders.getParsedKafkaHeader(consumerRecordOnTargetTopic.headers(), 'ce_correlationid') == 'test-cmhandle1'
93         and: 'event id is same between consumed and forwarded'
94             assert KafkaHeaders.getParsedKafkaHeader(consumerRecordOnTargetTopic.headers(), 'ce_id') == 'sample-eventid'
95         and: 'the event payload still matches'
96             assert avcEventFromTargetTopic == validAvcEventAsJson
97     }
98
99     def 'Consume and process CM Avc Event with #scenario. [test B, using specific topic]'() {
100         given: 'a cloud event is created with source ONAP-DMI-PLUGIN'
101             def testCloudEventSent = buildCloudEvent(sourceSystem, 'some-cmhandle-id', validAvcEventAsJson)
102         and: 'a separate topic for this test'
103             objectUnderTest.cmEventsTopicName = 'some-topic-for-Test-B'
104         and: 'inventory persistence service has #scenario'
105             def compositeState = new CompositeState(dataSyncEnabled: dataSyncEnabled)
106             mockInventoryPersistence.getCmHandleState(_) >> compositeState
107         and: 'event has source system as ONAP-DMI-PLUGIN and key(cmHandleId) and value as cloud event'
108             def consumerRecord = new ConsumerRecord<String, CloudEvent>(objectUnderTest.cmEventsTopicName, 0, 0, testEventKey, testCloudEventSent)
109             if (sourceSystem!=null) {
110                 consumerRecord.headers().add('ce_source', sourceSystem.getBytes(Charset.defaultCharset()))
111             }
112         when: 'the event is consumed'
113             objectUnderTest.consumeAndForward(consumerRecord)
114         then: 'cm avc event is processed for updating the cached data'
115             expectedCallToProcessCmAvcEvent * mockCmAvcEventService.processCmAvcEvent(testEventKey, _) >> {args ->
116                 {  assert args[1] instanceof AvcEvent }
117             }
118         where: 'following scenarios are used'
119             scenario                          | sourceSystem      | dataSyncEnabled || expectedCallToProcessCmAvcEvent
120             'source ONAP, data sync enabled'  | 'ONAP-DMI-PLUGIN' | true            || 1
121             'source ONAP, data sync disabled' | 'ONAP-DMI-PLUGIN' | false           || 0
122             'other source, data sync enabled' | 'other'           | true            || 0
123     }
124
125     def 'Forward non-avc invalid event with source ONAP-DMI-PLUGIN. [test C, using specific topic]'() {
126         given: 'an non-avc cloud event'
127             def someJsonForOtherStructure = '{"some attribute":"for other event"}'
128             def testCloudEventSent = buildCloudEvent(onapDmiSourceSystem, 'some-cmhandle-id', someJsonForOtherStructure)
129         and: 'a separate topic for this test'
130             objectUnderTest.cmEventsTopicName = 'some-topic-for-Test-C'
131         and: 'inventory persistence service has data sync enabled for any node'
132             def compositeState = new CompositeState(dataSyncEnabled: true)
133             mockInventoryPersistence.getCmHandleState(_) >> compositeState
134         and: 'event has source system as ONAP-DMI-PLUGIN and key(cmHandleId) and value as cloud event'
135             def consumerRecord = new ConsumerRecord<String, CloudEvent>(objectUnderTest.cmEventsTopicName, 0, 0, testEventKey, testCloudEventSent)
136             consumerRecord.headers().add('ce_source', onapDmiSourceSystem.getBytes(Charset.defaultCharset()))
137         when: 'the event is consumed'
138             objectUnderTest.consumeAndForward(consumerRecord)
139         then: 'no AVC event processing takes place'
140             0 * mockCmAvcEventService.processCmAvcEvent(testEventKey, _)
141     }
142
143     def buildCloudEvent(sourceSystem, cmHandleId, sourceEvent) {
144         return CloudEventBuilder.v1()
145             .withData(jsonObjectMapper.asJsonBytes(sourceEvent))
146             .withId('sample-eventid')
147             .withType('sample-test-type')
148             .withSource(URI.create(sourceSystem as String))
149             .withExtension('correlationid', cmHandleId).build()
150     }
151 }