9cf36848320e1faeb78d95faee8fc296929da0a7
[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.cmnotificationsubscription.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<CloudEvent>(legacyEventKafkaTemplate, cloudEventKafkaTemplate)
55
56     def mockCmAvcEventService = Mock(CmAvcEventService)
57     def mockInventoryPersistence = Mock(InventoryPersistence)
58
59     @SpringBean
60     CmAvcEventConsumer cmAvcEventConsumer = 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 testAvcEvent
68     def testEventKey
69
70     def setup() {
71         testEventKey = 'sample-key'
72         testAvcEvent = jsonObjectMapper.convertJsonString(getResourceFileContent('sampleAvcInputEvent.json'), AvcEvent.class)
73     }
74
75     def 'Test A : Consume and forward valid message'() {
76         given: 'a cloud event'
77             def testCloudEventSent = buildCloudEvent('sample-source', 'test-cmhandle1')
78         and: 'consumer has a subscription on the target topic for this test'
79             cmAvcEventConsumer.cmEventsTopicName = 'target-topic-for-Test-A'
80             cloudEventKafkaConsumer.subscribe([cmAvcEventConsumer.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>(cmAvcEventConsumer.cmEventsTopicName, 0, 0, testEventKey, testCloudEventSent)
83         when: 'the event is consumed and forwarded to target topic'
84             cmAvcEventConsumer.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 == testAvcEvent
97     }
98
99     def 'Test B : Consume and process CM Avc Event when #scenario'() {
100         given: 'a cloud event is created(what we get from ONAP-DMI-PLUGIN)'
101             def sourceSystem = 'ONAP-DMI-PLUGIN'
102             def testCloudEventSent = buildCloudEvent(sourceSystem, 'some-cmhandle-id')
103         and: 'a separate topic for this test'
104             cmAvcEventConsumer.cmEventsTopicName =  'some-topic-for-Test-B'
105         and: 'inventory persistence service has #scenario'
106             def compositeState = new CompositeState(dataSyncEnabled: dataSyncFlag)
107             1 * mockInventoryPersistence.getCmHandleState(_) >> compositeState
108         and: 'event has source system as ONAP-DMI-PLUGIN and key(cmHandleId) and value as cloud event'
109             def consumerRecord = new ConsumerRecord<String, CloudEvent>(cmAvcEventConsumer.cmEventsTopicName, 0, 0, testEventKey, testCloudEventSent)
110             consumerRecord.headers().add('ce_source', sourceSystem.getBytes(Charset.defaultCharset()))
111         when: 'the event is consumed'
112             cmAvcEventConsumer.consumeAndForward(consumerRecord)
113         then: 'cm avc event is processed for updating the cached data'
114             expectedCallToProcessCmAvcEvent * mockCmAvcEventService.processCmAvcEvent(testEventKey, _) >> { args ->
115                 {
116                     assert args[1] instanceof AvcEvent
117                 }
118             }
119         where: 'following scenarios are used'
120             scenario                  | dataSyncFlag || expectedCallToProcessCmAvcEvent
121             'data sync flag enabled'  | true         || 1
122             'data sync flag disabled' | false        || 0
123
124     }
125
126     def buildCloudEvent(sourceSystem, cmHandleId){
127
128         return CloudEventBuilder.v1()
129             .withData(jsonObjectMapper.asJsonBytes(testAvcEvent))
130             .withId('sample-eventid')
131             .withType('sample-test-type')
132             .withSource(URI.create(sourceSystem as String))
133             .withExtension('correlationid', cmHandleId).build()
134
135     }
136 }