2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
20 package org.onap.ccsdk.cds.blueprintsprocessor
22 import com.fasterxml.jackson.databind.ObjectMapper
23 import com.nhaarman.mockitokotlin2.any
24 import com.nhaarman.mockitokotlin2.argThat
25 import com.nhaarman.mockitokotlin2.atLeast
26 import com.nhaarman.mockitokotlin2.atLeastOnce
27 import com.nhaarman.mockitokotlin2.eq
28 import com.nhaarman.mockitokotlin2.mock
29 import com.nhaarman.mockitokotlin2.verify
30 import com.nhaarman.mockitokotlin2.verifyNoMoreInteractions
31 import com.nhaarman.mockitokotlin2.whenever
32 import org.junit.ClassRule
34 import org.junit.runner.RunWith
35 import org.junit.runners.Parameterized
36 import org.onap.ccsdk.cds.blueprintsprocessor.rest.RestLibConstants
37 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BluePrintRestLibPropertyService
38 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService
39 import org.onap.ccsdk.cds.blueprintsprocessor.rest.service.BlueprintWebClientService.WebClientResponse
40 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils.Companion.compressToBytes
41 import org.skyscreamer.jsonassert.JSONAssert
42 import org.skyscreamer.jsonassert.JSONCompareMode
43 import org.slf4j.Logger
44 import org.slf4j.LoggerFactory
45 import org.springframework.beans.factory.annotation.Autowired
46 import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient
47 import org.springframework.boot.test.context.SpringBootTest
48 import org.springframework.boot.test.mock.mockito.MockBean
49 import org.springframework.core.io.ByteArrayResource
50 import org.springframework.core.io.Resource
51 import org.springframework.http.MediaType
52 import org.springframework.test.context.ContextConfiguration
53 import org.springframework.test.context.TestPropertySource
54 import org.springframework.test.context.junit4.rules.SpringClassRule
55 import org.springframework.test.context.junit4.rules.SpringMethodRule
56 import org.springframework.test.web.reactive.server.WebTestClient
57 import org.yaml.snakeyaml.Yaml
58 import reactor.core.publisher.Mono
60 import java.nio.file.Path
61 import java.nio.file.Paths
62 import kotlin.test.BeforeTest
63 import kotlin.test.Test
65 @RunWith(Parameterized::class)
66 // Set blueprintsprocessor.httpPort=0 to trigger a random port selection
67 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
68 @AutoConfigureWebTestClient(timeout = "PT10S")
69 @ContextConfiguration(initializers = [
70 WorkingFoldersInitializer::class,
71 TestSecuritySettings.ServerContextInitializer::class
73 @TestPropertySource(locations = ["classpath:application-test.properties"])
74 @Suppress("UNCHECKED_CAST")
75 class BlueprintsAcceptanceTests(private val blueprintName: String, private val filename: String) {
78 const val UAT_BLUEPRINTS_BASE_DIR = "../../../components/model-catalog/blueprint-model/uat-blueprints"
79 const val EMBEDDED_UAT_FILE = "Tests/uat.yaml"
83 val springClassRule = SpringClassRule()
85 val log: Logger = LoggerFactory.getLogger(BlueprintsAcceptanceTests::class.java)
87 @Parameterized.Parameters(name = "{index} {0}")
89 fun filenames(): List<Array<String>> {
90 return File(UAT_BLUEPRINTS_BASE_DIR)
91 .listFiles { file -> file.isDirectory && File(file, EMBEDDED_UAT_FILE).isFile }
92 ?.map { file -> arrayOf(file.nameWithoutExtension, file.canonicalPath) }
99 val springMethodRule = SpringMethodRule()
101 @MockBean(name = RestLibConstants.SERVICE_BLUEPRINT_REST_LIB_PROPERTY)
102 lateinit var restClientFactory: BluePrintRestLibPropertyService
105 // Bean is created programmatically by {@link WorkingFoldersInitializer#initialize(String)}
106 @Suppress("SpringJavaInjectionPointsAutowiringInspection")
107 lateinit var tempFolder: ExtendedTemporaryFolder
110 lateinit var webTestClient: WebTestClient
113 lateinit var mapper: ObjectMapper
116 fun cleanupTemporaryFolder() {
117 tempFolder.deleteAllFiles()
121 fun testBlueprint() {
122 val yaml: Map<String, *> = loadYaml(Paths.get(filename, EMBEDDED_UAT_FILE))
124 uploadBlueprint(blueprintName)
126 // Configure mocked external services
127 val services = yaml["external-services"] as List<Map<String, *>>? ?: emptyList()
128 val expectationPerClient = services.map { service ->
129 val selector = service["selector"] as String
130 val expectations = (service["expectations"] as List<Map<String, *>>).map {
133 val mockClient = createRestClientMock(selector, expectations)
134 mockClient to expectations
138 for (process in (yaml["processes"] as List<Map<String, *>>)) {
139 val processName = process["name"]
140 log.info("Executing process '$processName'")
141 val request = mapper.writeValueAsString(process["request"])
142 val expectedResponse = mapper.writeValueAsString(process["expectedResponse"])
143 processBlueprint(request, expectedResponse)
146 // Validate request payloads
147 for ((mockClient, expectations) in expectationPerClient) {
148 expectations.forEach { expectation ->
149 verify(mockClient, atLeastOnce()).exchangeResource(
150 eq(expectation.method),
151 eq(expectation.path),
152 argThat { assertJsonEqual(expectation.expectedRequestBody, this) },
153 expectation.requestHeadersMatcher())
155 // Don't mind the invocations to the overloaded exchangeResource(String, String, String)
156 verify(mockClient, atLeast(0)).exchangeResource(any(), any(), any())
157 verifyNoMoreInteractions(mockClient)
161 private fun createRestClientMock(selector: String, restExpectations: List<RestExpectation>): BlueprintWebClientService {
162 val restClient = mock<BlueprintWebClientService>(verboseLogging = true)
164 // Delegates to overloaded exchangeResource(String, String, String, Map<String, String>)
165 whenever(restClient.exchangeResource(any(), any(), any()))
166 .thenAnswer { invocation ->
167 val method = invocation.arguments[0] as String
168 val path = invocation.arguments[1] as String
169 val request = invocation.arguments[2] as String
170 restClient.exchangeResource(method, path, request, emptyMap())
172 for (expectation in restExpectations) {
173 whenever(restClient.exchangeResource(
174 eq(expectation.method),
175 eq(expectation.path),
178 .thenReturn(WebClientResponse(expectation.statusCode, expectation.responseBody))
181 whenever(restClientFactory.blueprintWebClientService(selector))
182 .thenReturn(restClient)
186 private fun uploadBlueprint(blueprintName: String) {
187 val body = toMultiValueMap("file", getBlueprintAsResource(blueprintName))
190 .uri("/api/v1/execution-service/upload")
191 .header("Authorization", TestSecuritySettings.clientAuthToken())
197 private fun processBlueprint(request: String, expectedResponse: String) {
200 .uri("/api/v1/execution-service/process")
201 .header("Authorization", TestSecuritySettings.clientAuthToken())
202 .contentType(MediaType.APPLICATION_JSON_UTF8)
203 .body(Mono.just(request), String::class.java)
207 .json(expectedResponse)
210 private fun getBlueprintAsResource(blueprintName: String): Resource {
211 val baseDir = Paths.get(UAT_BLUEPRINTS_BASE_DIR, blueprintName)
212 val zipBytes = compressToBytes(baseDir)
213 return object : ByteArrayResource(zipBytes) {
214 // Filename has to be returned in order to be able to post
215 override fun getFilename() = "$blueprintName.zip"
219 private fun loadYaml(path: Path): Map<String, Any> {
220 return path.toFile().reader().use { reader ->
225 private fun assertJsonEqual(expected: Any, actual: String): Boolean {
226 if (actual != expected) {
227 // assertEquals throws an exception whenever match fails
228 JSONAssert.assertEquals(mapper.writeValueAsString(expected), actual, JSONCompareMode.LENIENT)
233 private fun parseExpectation(expectation: Map<String, *>): RestExpectation {
234 val request = expectation["request"] as Map<String, Any>
235 val method = request["method"] as String
236 val path = joinPath(request.getValue("path"))
237 val contentType = request["content-type"] as String?
238 val requestBody = request.getOrDefault("body", "")
240 val response = expectation["response"] as Map<String, Any>? ?: emptyMap()
241 val status = response["status"] as Int? ?: 200
242 val responseBody = when (val body = response["body"] ?: "") {
244 else -> mapper.writeValueAsString(body)
247 return RestExpectation(method, path, contentType, requestBody, status, responseBody)
251 * Join a multilevel lists of strings.
252 * Example: joinPath(listOf("a", listOf("b", "c"), "d")) will result in "a/b/c/d".
254 private fun joinPath(any: Any): String {
255 fun recursiveJoin(any: Any, sb: StringBuilder): StringBuilder {
257 is List<*> -> any.filterNotNull().forEach { recursiveJoin(it, sb) }
259 if (sb.isNotEmpty()) {
264 else -> throw IllegalArgumentException("Unsupported type: ${any.javaClass}")
269 return recursiveJoin(any, StringBuilder()).toString()
272 data class RestExpectation(val method: String, val path: String, val contentType: String?,
273 val expectedRequestBody: Any,
274 val statusCode: Int, val responseBody: String) {
276 fun requestHeadersMatcher(): Map<String, String> {
277 return if (contentType != null) eq(mapOf("Content-Type" to contentType)) else any()