summaryrefslogtreecommitdiffstats
path: root/ms/blueprintsprocessor/application/src/test/kotlin/org/onap/ccsdk/cds/blueprintsprocessor/uat/UatServicesTest.kt
blob: fe2d539e34b901402bdef19178fe1ef931ac0a01 (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
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2019 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.ccsdk.cds.blueprintsprocessor.uat

import com.fasterxml.jackson.databind.ObjectMapper
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.MappingBuilder
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder
import com.github.tomakehurst.wiremock.client.VerificationException
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.equalTo
import com.github.tomakehurst.wiremock.client.WireMock.equalToJson
import com.github.tomakehurst.wiremock.client.WireMock.request
import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo
import com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig
import com.github.tomakehurst.wiremock.http.HttpHeader
import com.github.tomakehurst.wiremock.http.HttpHeaders
import org.apache.http.HttpStatus
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.ContentType
import org.apache.http.entity.mime.HttpMultipartMode
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder
import org.apache.http.message.BasicHeader
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.equalToIgnoringCase
import org.onap.ccsdk.cds.blueprintsprocessor.uat.logging.LogColor.COLOR_WIREMOCK
import org.onap.ccsdk.cds.blueprintsprocessor.uat.logging.LogColor.markerOf
import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.MarkedSlf4jNotifier
import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.ServiceDefinition
import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.TestSecuritySettings
import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.UatDefinition
import org.onap.ccsdk.cds.controllerblueprints.core.BluePrintConstants.UAT_SPECIFICATION_FILE
import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils.Companion.compressToBytes
import org.skyscreamer.jsonassert.JSONAssert
import org.skyscreamer.jsonassert.JSONCompareMode
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.core.env.ConfigurableEnvironment
import org.springframework.core.env.MapPropertySource
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.support.TestPropertySourceUtils.INLINED_PROPERTIES_PROPERTY_SOURCE_NAME
import org.yaml.snakeyaml.Yaml
import java.nio.file.Paths
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertNotNull

fun String.prefixIfNot(prefix: String) =
    if (this.startsWith(prefix)) this else "$prefix$this"

@ActiveProfiles("uat")
@Suppress("MemberVisibilityCanBePrivate")
class UatServicesTest : BaseUatTest() {

    companion object {

        private const val BLUEPRINT_NAME = "pnf_config"
        private val BLUEPRINT_BASE_DIR = Paths.get(UAT_BLUEPRINTS_BASE_DIR, BLUEPRINT_NAME)
        private val UAT_PATH = BLUEPRINT_BASE_DIR.resolve(UAT_SPECIFICATION_FILE)
        private val wireMockMarker = markerOf(COLOR_WIREMOCK)
    }

    @Autowired
    lateinit var mapper: ObjectMapper

    @Autowired
    lateinit var environment: ConfigurableEnvironment

    private val ephemeralProperties = mutableSetOf<String>()
    private val startedMockServers = mutableListOf<WireMockServer>()

    private fun setProperties(properties: Map<String, String>) {
        inlinedPropertySource().putAll(properties)
        ephemeralProperties += properties.keys
    }

    @AfterTest
    fun resetProperties() {
        val source = inlinedPropertySource()
        ephemeralProperties.forEach { key -> source.remove(key) }
        ephemeralProperties.clear()
    }

    @AfterTest
    fun stopMockServers() {
        startedMockServers.forEach { mockServer ->
            try {
                mockServer.checkForUnmatchedRequests()
            } finally {
                mockServer.stop()
            }
        }
        startedMockServers.clear()
    }

    private fun inlinedPropertySource(): MutableMap<String, Any> =
        (environment.propertySources[INLINED_PROPERTIES_PROPERTY_SOURCE_NAME] as MapPropertySource).source

    @LocalServerPort
    var localServerPort: Int = 0

    // use lazy evaluation to postpone until localServerPort is injected by Spring
    val baseUrl: String by lazy {
        "http://127.0.0.1:$localServerPort"
    }

    lateinit var httpClient: CloseableHttpClient

    @BeforeTest
    fun setupHttpClient() {
        val defaultHeaders = listOf(
            BasicHeader(
                org.apache.http.HttpHeaders.AUTHORIZATION,
                TestSecuritySettings.clientAuthToken()
            )
        )
        httpClient = HttpClientBuilder.create()
            .setDefaultHeaders(defaultHeaders)
            .build()
    }

    @Test
    fun `verify service validates candidate UAT`() {
        // GIVEN
        val cbaBytes = compressToBytes(BLUEPRINT_BASE_DIR)
        val multipartEntity = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("cba", cbaBytes, ContentType.DEFAULT_BINARY, "cba.zip")
            .build()
        val request = HttpPost("$baseUrl/api/v1/uat/verify").apply {
            entity = multipartEntity
        }

        // WHEN
        httpClient.execute(request) { response ->

            // THEN
            val statusLine = response.statusLine
            assertThat(statusLine.statusCode, CoreMatchers.equalTo(HttpStatus.SC_OK))
        }
    }

    @Test
    fun `spy service generates complete UAT from bare UAT`() {
        // GIVEN
        val uatSpec = UAT_PATH.toFile().readText()
        val fullUat = UatDefinition.load(mapper, uatSpec)
        val expectedJson = mapper.writeValueAsString(fullUat)

        val bareUatBytes = fullUat.toBare().dump(mapper).toByteArray()

        fullUat.externalServices.forEach { service ->
            val mockServer = createMockServer(service)
            mockServer.start()
            startedMockServers += mockServer
            setPropertiesForMockServer(service, mockServer)
        }

        val cbaBytes = compressToBytes(BLUEPRINT_BASE_DIR)
        val multipartEntity = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("cba", cbaBytes, ContentType.DEFAULT_BINARY, "cba.zip")
            .addBinaryBody("uat", bareUatBytes, ContentType.DEFAULT_BINARY, "uat.yaml")
            .build()
        val request = HttpPost("$baseUrl/api/v1/uat/spy").apply {
            entity = multipartEntity
        }

        // WHEN
        httpClient.execute(request) { response ->

            // THEN
            val statusLine = response.statusLine
            assertThat(statusLine.statusCode, CoreMatchers.equalTo(HttpStatus.SC_OK))
            val entity = response.entity
            assertNotNull(entity)
            val contentType = ContentType.get(entity)
            assertThat(contentType.mimeType, equalToIgnoringCase("text/vnd.yaml"))
            val yamlResponse = entity.content.bufferedReader().readText()
            val jsonResponse = yamlToJson(yamlResponse)
            JSONAssert.assertEquals(expectedJson, jsonResponse, JSONCompareMode.LENIENT)
        }
    }

    private fun createMockServer(service: ServiceDefinition): WireMockServer {
        val mockServer = WireMockServer(
            wireMockConfig()
                .dynamicPort()
                .notifier(MarkedSlf4jNotifier(wireMockMarker))
        )
        service.expectations.forEach { expectation ->

            val request = expectation.request
            // WebTestClient always use absolute path, prefixing with "/" if necessary
            val urlPattern = urlEqualTo(request.path.prefixIfNot("/"))
            val mappingBuilder: MappingBuilder = request(request.method, urlPattern)
            request.headers.forEach { (key, value) ->
                mappingBuilder.withHeader(key, equalTo(value))
            }
            if (request.body != null) {
                mappingBuilder.withRequestBody(equalToJson(mapper.writeValueAsString(request.body), true, true))
            }

            for (response in expectation.responses) {
                val responseDefinitionBuilder: ResponseDefinitionBuilder = aResponse()
                    .withStatus(response.status)
                if (response.body != null) {
                    responseDefinitionBuilder.withBody(mapper.writeValueAsBytes(response.body))
                        .withHeaders(
                            HttpHeaders(
                                response.headers.entries.map { e -> HttpHeader(e.key, e.value) }
                            )
                        )
                }

                // TODO: MockServer verification for multiple responses should be done using Wiremock scenarios
                mappingBuilder.willReturn(responseDefinitionBuilder)
            }

            mockServer.stubFor(mappingBuilder)
        }
        return mockServer
    }

    private fun setPropertiesForMockServer(service: ServiceDefinition, mockServer: WireMockServer) {
        val selector = service.selector
        val httpPort = mockServer.port()
        val properties = mapOf(
            "blueprintsprocessor.restclient.$selector.type" to "basic-auth",
            "blueprintsprocessor.restclient.$selector.url" to "http://localhost:$httpPort/",
            // TODO credentials should be validated
            "blueprintsprocessor.restclient.$selector.username" to "admin",
            "blueprintsprocessor.restclient.$selector.password" to "Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U"
        )
        setProperties(properties)
    }

    /**
     * Borrowed from com.github.tomakehurst.wiremock.junit.WireMockRule.checkForUnmatchedRequests
     */
    private fun WireMockServer.checkForUnmatchedRequests() {
        val unmatchedRequests = findAllUnmatchedRequests()
        if (unmatchedRequests.isNotEmpty()) {
            val nearMisses = findNearMissesForAllUnmatchedRequests()
            if (nearMisses.isEmpty()) {
                throw VerificationException.forUnmatchedRequests(unmatchedRequests)
            } else {
                throw VerificationException.forUnmatchedNearMisses(nearMisses)
            }
        }
    }

    private fun yamlToJson(yaml: String): String {
        val map: Map<String, Any> = Yaml().load(yaml)
        return mapper.writeValueAsString(map)
    }
}