Make UatExecutor accessible inside a CBA JUnit test
[ccsdk/cds.git] / components / model-catalog / blueprint-model / archetype-blueprint / src / main / resources / archetype-resources / Tests / kotlin / org / onap / ccsdk / cds / blueprintsprocessor / uat / base / BaseBlueprintsAcceptanceTest.kt
1 package org.onap.ccsdk.cds.blueprintsprocessor.uat.base
2
3 import kotlinx.coroutines.runBlocking
4 import org.junit.runner.RunWith
5 import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.MessagePrioritizationStateService
6 import org.onap.ccsdk.cds.blueprintsprocessor.functions.message.prioritization.service.SampleMessagePrioritizationService
7 import org.onap.ccsdk.cds.blueprintsprocessor.uat.base.BaseBlueprintsAcceptanceTest.TestSecuritySettings
8 import org.onap.ccsdk.cds.blueprintsprocessor.uat.base.BaseBlueprintsAcceptanceTest.WorkingFoldersInitializer
9 import org.onap.ccsdk.cds.blueprintsprocessor.uat.logging.LogColor
10 import org.onap.ccsdk.cds.blueprintsprocessor.uat.utils.UatExecutor
11 import org.onap.ccsdk.cds.controllerblueprints.core.utils.BluePrintArchiveUtils.Companion.compressToBytes
12 import org.slf4j.Logger
13 import org.slf4j.LoggerFactory
14 import org.springframework.beans.factory.annotation.Autowired
15 import org.springframework.beans.factory.support.BeanDefinitionBuilder
16 import org.springframework.beans.factory.support.BeanDefinitionRegistry
17 import org.springframework.boot.test.context.SpringBootTest
18 import org.springframework.context.ApplicationContextInitializer
19 import org.springframework.context.ConfigurableApplicationContext
20 import org.springframework.stereotype.Component
21 import org.springframework.stereotype.Service
22 import org.springframework.test.context.ContextConfiguration
23 import org.springframework.test.context.TestPropertySource
24 import org.springframework.test.context.junit4.SpringRunner
25 import org.springframework.test.context.support.TestPropertySourceUtils
26 import org.springframework.util.Base64Utils
27 import java.io.File
28 import java.io.IOException
29 import java.nio.file.*
30 import java.nio.file.attribute.BasicFileAttributes
31 import javax.annotation.PreDestroy
32 import kotlin.test.BeforeTest
33 import kotlin.test.AfterTest
34
35
36 /**
37  * This is a SpringBootTest abstract Base class, that executes UAT (User Acceptance Tests) by calling
38  * callRunUat in an implementation class.
39  * See https://docs.onap.org/projects/onap-ccsdk-cds/en/latest/modelingconcepts/test.html and
40  * https://github.com/onap/ccsdk-cds/blob/master/components/model-catalog/blueprint-model/uat-blueprints/README.md
41  * for further information concerning the CDS UAT concept.
42  */
43
44 @RunWith(SpringRunner::class)
45 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
46 @ContextConfiguration(
47     initializers = [
48         WorkingFoldersInitializer::class,
49         TestSecuritySettings.ServerContextInitializer::class
50     ]
51 )
52 @TestPropertySource(locations = ["classpath:application-test.properties"])
53 abstract class BaseBlueprintsAcceptanceTest() {
54     @BeforeTest
55     fun setScope() {
56         LogColor.setContextColor(LogColor.COLOR_TEST_CLIENT)
57     }
58
59     @AfterTest
60     fun clearScope() {
61         LogColor.resetContextColor()
62     }
63
64     companion object {
65         private val log: Logger = LoggerFactory.getLogger(BaseBlueprintsAcceptanceTest::class.java)
66     }
67
68     @Autowired
69     // Bean is created programmatically by {@link WorkingFoldersInitializer#initialize(String)}
70     @Suppress("SpringJavaInjectionPointsAutowiringInspection")
71     lateinit var tempFolder: ExtendedTemporaryFolder
72
73     @Autowired
74     lateinit var uatExecutor: UatExecutor
75
76     @BeforeTest
77     fun cleanupTemporaryFolder() {
78         tempFolder.deleteAllFiles()
79     }
80
81     protected suspend fun callRunUat(pathName: String, uatFilename: String) {
82         runBlocking {
83             val dir = File(pathName)
84             val rootFs =  FileSystems.newFileSystem(dir.canonicalFile.toPath(), null)
85             log.info("dirname: ${dir.toString()} rootFs ${rootFs}")
86
87             val uatSpec = rootFs.getPath(uatFilename).toFile().readText()
88             val cbaBytes = compressToBytes(rootFs.getPath("/"))
89             uatExecutor.execute(uatSpec, cbaBytes)
90         }
91     }
92
93     @Service
94     open class TestMessagePrioritizationService(messagePrioritizationStateService: MessagePrioritizationStateService) :
95         SampleMessagePrioritizationService(messagePrioritizationStateService)
96     @Component
97     class WorkingFoldersInitializer : ApplicationContextInitializer<ConfigurableApplicationContext> {
98
99         override fun initialize(context: ConfigurableApplicationContext) {
100             val tempFolder = ExtendedTemporaryFolder()
101             val properties = listOf("Deploy", "Archive", "Working")
102                 .map { "blueprintsprocessor.blueprint${it}Path=${tempFolder.newFolder(it).absolutePath.replace("\\", "/")}" }
103                 .toTypedArray()
104             TestPropertySourceUtils.addInlinedPropertiesToEnvironment(context, *properties)
105             // Expose tempFolder as a bean so it can be accessed via DI
106             registerSingleton(context, "tempFolder", ExtendedTemporaryFolder::class.java, tempFolder)
107         }
108
109         @Suppress("SameParameterValue")
110         private fun <T> registerSingleton(
111             context: ConfigurableApplicationContext,
112             beanName: String,
113             beanClass: Class<T>,
114             instance: T
115         ) {
116             val builder = BeanDefinitionBuilder.genericBeanDefinition(beanClass) { instance }
117             (context.beanFactory as BeanDefinitionRegistry).registerBeanDefinition(beanName, builder.beanDefinition)
118         }
119     }
120
121     class ExtendedTemporaryFolder {
122
123         private val tempFolder = createTempDir("uat")
124
125         @PreDestroy
126         fun delete() = tempFolder.deleteRecursively()
127
128         /**
129          * A delegate to org.junit.rules.TemporaryFolder.TemporaryFolder.newFolder(String).
130          */
131         fun newFolder(folderName: String): File {
132             val dir = File(tempFolder, folderName)
133             if (!dir.mkdir()) {
134                 throw IOException("Unable to create temporary directory $dir.")
135             }
136             return dir
137         }
138
139         /**
140          * Delete all files under the root temporary folder recursively. The folders are preserved.
141          */
142         fun deleteAllFiles() {
143             Files.walkFileTree(
144                 tempFolder.toPath(),
145                 object : SimpleFileVisitor<Path>() {
146                     @Throws(IOException::class)
147                     override fun visitFile(file: Path?, attrs: BasicFileAttributes?): FileVisitResult {
148                         file?.toFile()?.delete()
149                         return FileVisitResult.CONTINUE
150                     }
151                 }
152             )
153         }
154     }
155     class TestSecuritySettings {
156         companion object {
157
158             private const val authUsername = "walter.white"
159             private const val authPassword = "Heisenberg"
160
161             fun clientAuthToken() =
162                 "Basic " + Base64Utils.encodeToString("$authUsername:$authPassword".toByteArray())
163         }
164
165         class ServerContextInitializer : ApplicationContextInitializer<ConfigurableApplicationContext> {
166
167             override fun initialize(context: ConfigurableApplicationContext) {
168                 TestPropertySourceUtils.addInlinedPropertiesToEnvironment(
169                     context,
170                     "security.user.name=$authUsername",
171                     "security.user.password={noop}$authPassword"
172                 )
173             }
174         }
175     }
176
177 }