8382f67f9db03a2c1c4ca1e9659ef87d2e0c850b
[cps/ncmp-dmi-plugin.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2023 Nordix Foundation
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.dmi.notifications.avcsubscription
22
23 import com.fasterxml.jackson.databind.ObjectMapper
24 import io.cloudevents.CloudEvent
25 import io.cloudevents.core.builder.CloudEventBuilder
26 import org.apache.kafka.clients.consumer.ConsumerRecord
27 import org.onap.cps.ncmp.dmi.TestUtils
28 import org.onap.cps.ncmp.dmi.api.kafka.MessagingBaseSpec
29 import org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.CmHandle
30 import org.onap.cps.ncmp.events.avcsubscription1_0_0.ncmp_to_dmi.SubscriptionEvent
31 import org.onap.cps.ncmp.events.avcsubscription1_0_0.dmi_to_ncmp.Data
32 import org.onap.cps.ncmp.events.avcsubscription1_0_0.dmi_to_ncmp.SubscriptionEventResponse
33 import org.onap.cps.ncmp.events.avcsubscription1_0_0.dmi_to_ncmp.SubscriptionStatus
34 import org.spockframework.spring.SpringBean
35 import org.springframework.boot.test.context.SpringBootTest
36 import org.springframework.test.annotation.DirtiesContext
37 import org.testcontainers.spock.Testcontainers
38
39 import java.sql.Timestamp
40 import java.time.Duration
41 import java.time.OffsetDateTime
42 import java.time.ZoneId
43
44 @SpringBootTest(classes = [SubscriptionEventConsumer])
45 @Testcontainers
46 @DirtiesContext
47 class SubscriptionEventConsumerSpec extends MessagingBaseSpec {
48
49     def objectMapper = new ObjectMapper()
50     def testTopic = 'dmi-ncmp-cm-avc-subscription'
51
52     @SpringBean
53     SubscriptionEventConsumer objectUnderTest = new SubscriptionEventConsumer(cloudEventKafkaTemplate)
54
55     def 'Sends subscription cloud event response successfully.'() {
56         given: 'an subscription event response'
57             objectUnderTest.dmiName = 'test-ncmp-dmi'
58             objectUnderTest.cmAvcSubscriptionResponseTopic = testTopic
59             def responseStatus = SubscriptionStatus.Status.ACCEPTED
60             def subscriptionStatuses = [new SubscriptionStatus(id: 'CmHandle1', status: responseStatus),
61                                         new SubscriptionStatus(id: 'CmHandle2', status: responseStatus)]
62             def subscriptionEventResponseData = new Data(subscriptionName: 'cm-subscription-001',
63                 clientId: 'SCO-9989752', dmiName: 'ncmp-dmi-plugin', subscriptionStatus: subscriptionStatuses)
64             def subscriptionEventResponse =
65                     new SubscriptionEventResponse().withData(subscriptionEventResponseData)
66         and: 'consumer has a subscription'
67             kafkaConsumer.subscribe([testTopic] as List<String>)
68         when: 'an event is published'
69             def eventKey = UUID.randomUUID().toString()
70             objectUnderTest.sendSubscriptionResponseMessage(eventKey, "subscriptionCreatedStatus", subscriptionEventResponse)
71         and: 'topic is polled'
72             def records = kafkaConsumer.poll(Duration.ofMillis(1500))
73         then: 'poll returns one record'
74             assert records.size() == 1
75             def record = records.iterator().next()
76         and: 'the record value matches the expected event value'
77             def expectedValue = objectMapper.writeValueAsString(subscriptionEventResponse)
78             assert expectedValue == record.value
79             assert eventKey == record.key
80     }
81
82     def 'Consume valid message.'() {
83         given: 'an event'
84             objectUnderTest.dmiName = 'test-ncmp-dmi'
85             def eventKey = UUID.randomUUID().toString()
86             def timestamp = new Timestamp(1679521929511)
87             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
88             def subscriptionEvent = objectMapper.readValue(jsonData, SubscriptionEvent.class)
89             objectUnderTest.cmAvcSubscriptionResponseTopic = testTopic
90             def cloudEvent = CloudEventBuilder.v1().withId(UUID.randomUUID().toString()).withSource(URI.create('test-ncmp-dmi'))
91                     .withType(subscriptionType)
92                     .withDataSchema(URI.create("urn:cps:" + SubscriptionEvent.class.getName() + ":1.0.0"))
93                     .withExtension("correlationid", eventKey)
94                     .withTime(OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.of("UTC")))
95                     .withData(objectMapper.writeValueAsBytes(subscriptionEvent)).build()
96             def testEventSent = new ConsumerRecord<String, CloudEvent>('topic-name', 0, 0, eventKey, cloudEvent)
97         when: 'the valid event is consumed'
98             objectUnderTest.consumeSubscriptionEvent(testEventSent)
99         then: 'no exception is thrown'
100             noExceptionThrown()
101         where: 'given #senario'
102             scenario                    | subscriptionType
103             'Subscription Create Event' | "subscriptionCreated"
104             'Subscription Delete Event' | "subscriptionDeleted"
105     }
106
107     def 'Consume invalid message.'() {
108         given: 'an invalid event type'
109             objectUnderTest.dmiName = 'test-ncmp-dmi'
110             def eventKey = UUID.randomUUID().toString()
111             def timestamp = new Timestamp(1679521929511)
112             objectUnderTest.cmAvcSubscriptionResponseTopic = testTopic
113             def cloudEvent = CloudEventBuilder.v1().withId(UUID.randomUUID().toString()).withSource(URI.create('test-ncmp-dmi'))
114                 .withType("subscriptionCreated")
115                 .withDataSchema(URI.create("urn:cps:" + SubscriptionEventResponse.class.getName() + ":1.0.0"))
116                 .withTime(OffsetDateTime.ofInstant(timestamp.toInstant(), ZoneId.of("UTC")))
117                 .withExtension("correlationid", eventKey).build()
118             def testEventSent = new ConsumerRecord<String, CloudEvent>('topic-name', 0, 0, eventKey, cloudEvent)
119         when: 'the invalid event is consumed'
120             objectUnderTest.consumeSubscriptionEvent(testEventSent)
121         then: 'no exception is thrown and event is logged'
122             noExceptionThrown()
123     }
124
125     def 'Form a SubscriptionEventResponse from a SubscriptionEvent.'() {
126         given: 'a SubscriptionEvent'
127             def jsonData = TestUtils.getResourceFileContent('avcSubscriptionCreationEvent.json')
128             def subscriptionEvent = objectMapper.readValue(jsonData, SubscriptionEvent.class)
129         when: 'a SubscriptionResponseEvent is formed'
130             def result = objectUnderTest.formSubscriptionEventResponse(subscriptionEvent)
131         then: 'Confirm SubscriptionEventResponse was formed as expected'
132             assert result.data.clientId == "SCO-9989752"
133             assert result.data.subscriptionName == "cm-subscription-001"
134     }
135
136     def 'Extract cm handle ids from cm handle successfully.'() {
137         given: 'a list of cm handles'
138             def cmHandleIds =
139                 [new CmHandle(id:'CmHandle1', additionalProperties: ['prop-x':'prop-valuex']),
140                  new CmHandle(id:'CmHandle2', additionalProperties: ['prop-y':'prop-valuey'])]
141         when: 'extract the cm handle ids'
142             def result = objectUnderTest.extractCmHandleIds(cmHandleIds)
143         then: 'cm handle ids are extracted as expected'
144             def expectedCmHandleIds = ['CmHandle1', 'CmHandle2'] as Set
145             assert expectedCmHandleIds == result
146     }
147
148     def 'Populate cm handle id to subscriptionStatus successfully.'() {
149         given: 'a set of cm handle id'
150             def cmHandleIds = ['CmHandle1', 'CmHandle2'] as Set
151             def responseStatus = SubscriptionStatus.Status.ACCEPTED
152         when: 'populate cm handle id to subscriptionStatus'
153             def result = objectUnderTest.populateSubscriptionStatus(cmHandleIds).status
154         then: 'cm handle id to subscriptionStatus populated as expected'
155             def expectedStatus = [responseStatus,responseStatus]
156             expectedStatus == result
157     }
158 }