Best Kotest code snippet using io.kotest.engine.test.names.paths
JUnitTestEngineListenerTest.kt
Source:JUnitTestEngineListenerTest.kt
...286 TestExecutionResult.Status.SUCCESSFUL287 ),288 )289 }290 test("listener should support full test paths") {291 val track = EventTrackingEngineExecutionListener()292 val conf = ProjectConfiguration()293 conf.displayFullTestPath = true294 val listener = JUnitTestEngineListener(track, root)295 listener.engineInitialized(EngineContext(TestSuite.empty, NoopTestEngineListener, TagExpression.Empty, conf))296 listener.specStarted(MySpec::class)297 listener.testStarted(tc1)298 listener.testStarted(tc2)299 listener.testFinished(tc2, TestResult.Success(3.milliseconds))300 listener.testFinished(tc1, TestResult.Success(7.milliseconds))301 listener.specFinished(MySpec::class, TestResult.Success(0.seconds))302 track.events shouldBe listOf(303 EventTrackingEngineExecutionListener.Event.TestRegistered("com.sksamuel.kotest.runner.junit5.MySpec", TestDescriptor.Type.CONTAINER),304 EventTrackingEngineExecutionListener.Event.ExecutionStarted("com.sksamuel.kotest.runner.junit5.MySpec"),...
TestPackTexturesTask.kt
Source:TestPackTexturesTask.kt
1import com.github.blueboxware.gdxplugin.GdxPlugin2import io.kotest.common.ExperimentalKotest3import io.kotest.core.spec.style.BehaviorSpec4import io.kotest.engine.spec.tempdir5import org.gradle.internal.impldep.junit.framework.TestCase6/*7 * Copyright 2021 Blue Box Ware8 *9 * Licensed under the Apache License, Version 2.0 (the "License");10 * you may not use this file except in compliance with the License.11 * You may obtain a copy of the License at12 *13 * http://www.apache.org/licenses/LICENSE-2.014 *15 * Unless required by applicable law or agreed to in writing, software16 * distributed under the License is distributed on an "AS IS" BASIS,17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.18 * See the License for the specific language governing permissions and19 * limitations under the License.20 */21@OptIn(ExperimentalKotest::class)22@Suppress("unused")23internal object TestPackTexturesTask: BehaviorSpec({24 lateinit var fixture: ProjectFixture25 beforeContainer {26 fixture = ProjectFixture(tempdir())27 fixture.copyFiles {28 from(fixture.testDataDir.absolutePath) {29 it.exclude("etc")30 it.exclude("ninePatch")31 }32 }33 }34 given("nothing") {35 `when`("running the texturePackerSettingsHelp task") {36 fixture.buildFile("")37 print(fixture.build("texturePackerSettingsHelp").output)38 then("outputs the available settings") {39 fixture.assertBuildOutputContains("stripWhitespaceY")40 fixture.assertBuildOutputContains("atlasExtension")41 fixture.assertBuildOutputContains("legacyOutput")42 }43 }44 }45 given("a minimal packTextures task") {46 beforeContainer {47 fixture.buildFile("""48 packTextures {49 from 'in'50 into 'out'51 }52 """)53 }54 `when`("building") {55 fixture.build("packTextures")56 then("should successfully build") {57 fixture.assertBuildSuccess()58 }59 then("should create a correct .atlas") {60 fixture.assertFileEquals("packTextures/minimalSpec.atlas", "pack.atlas")61 }62 }63 `when`("building twice") {64 fixture.build("packTextures")65 fixture.build("packTextures")66 then("should be up-to-date the second time") {67 fixture.assertBuildUpToDate()68 }69 }70 `when`("changing the input directory after build") {71 fixture.build("packTextures")72 fixture.input["images1/sub/image.png"].delete()73 fixture.build("packTextures")74 then("should build again") {75 fixture.assertBuildSuccess()76 }77 then("should create a new atlas") {78 fixture.assertFileEquals("packTextures/minimalSpecAfterDeletingImage.atlas", "pack.atlas")79 }80 }81 `when`("changing the atlas after build") {82 fixture.build("packTextures")83 fixture.output["pack.atlas"].appendText(" ")84 fixture.build("packTextures")85 then("should build again") {86 fixture.assertBuildSuccess()87 }88 }89 `when`("changing the spec after the build") {90 fixture.build("packTextures")91 fixture.buildFile("""92 packTextures {93 from 'in/images1'94 into 'out'95 }96 """)97 fixture.build("packTextures")98 then("should build again") {99 fixture.assertBuildSuccess()100 }101 }102 }103 given("a packTextures task with legacyOutput=false") {104 beforeContainer {105 fixture.buildFile(106 """107 packTextures {108 from 'in'109 into 'out'110 111 settings {112 legacyOutput = false113 }114 115 solid {116 name = "solid"117 width = 3118 height = 4119 }120 }121 """122 )123 }124 `when`("building") {125 fixture.build("packTextures")126 then("should create a correct .atlas") {127 fixture.assertFileEquals("packTextures/noLegacyOutput.atlas", "pack.atlas")128 }129 }130 }131 given("a packTextures task with a settingsFile specified") {132 beforeContainer {133 fixture.buildFile("""134 packTextures {135 from 'in/images2'136 into 'out'137 settingsFile = file('in/images1/sub/pack.json')138 }139 """)140 }141 `when`("building") {142 fixture.build("packTextures")143 then("should create a correct atlas with the settings from the settings file") {144 fixture.assertFileEquals("packTextures/withSettingsFile.atlas", "pack.atlas")145 }146 }147 }148 given("a packTextures task with usePackJson") {149 beforeContainer {150 fixture.buildFile("""151 packTextures {152 from 'in'153 into 'out'154 usePackJson = true155 }156 """)157 }158 `when`("building") {159 fixture.build("packTextures")160 then("should create a correct atlas with the settings from the pack.json files") {161 fixture.assertFileEquals("packTextures/withUsePackJson.atlas", "pack.atlas")162 }163 }164 }165 given("a packTextures task with a settings block and a custom name") {166 beforeContainer {167 fixture.buildFile("""168 packTextures {169 from 'in'170 into 'out'171 packFileName = 'textures.custom'172 settings {173 filterMin = "MipMapLinearNearest"174 filterMag = "MipMap"175 format = "RGB565"176 useIndexes = false177 atlasExtension = ".custom"178 }179 }180 """)181 }182 `when`("building") {183 fixture.build("packTextures")184 then("should create a correct atlas with the custom name") {185 fixture.assertFileEquals("packTextures/withSettingsAndCustomName.atlas", "textures.custom")186 }187 }188 `when`("building twice") {189 fixture.build("packTextures")190 fixture.build("packTextures")191 then("should be up-to-date the second time") {192 fixture.assertBuildUpToDate()193 }194 }195 `when`("changing the settings after the build") {196 fixture.build("packTextures")197 fixture.buildFile(fixture.getBuildFile().replace("MipMapLinearNearest", "Linear"))198 fixture.build("packTextures")199 then("should build again") {200 fixture.assertBuildSuccess()201 }202 then("should create a correct new atlas") {203 fixture.assertFileEquals("packTextures/withSettingsAndCustomName2.atlas", "textures.custom")204 }205 }206 `when`("deleting the atlas after the build") {207 fixture.build("packTextures")208 fixture.output["textures.custom"].delete()209 fixture.build("packTextures")210 then("should build again") {211 fixture.assertBuildSuccess()212 }213 }214 }215 given("a named container") {216 val taskNames = arrayOf("packPack1Textures", "packPack2Textures", "packPack3Textures")217 beforeContainer {218 fixture.buildFile("""219 texturePacks {220 pack1 {221 from 'in/images1'222 into 'out/pack1'223 }224 pack2 {225 from 'in/images2'226 into 'out/pack2'227 packFileName = "test.assets"228 settings {229 atlasExtension = ".assets"230 filterMin = "MipMapLinearLinear"231 }232 }233 pack3 {234 from 'in'235 into 'out/pack3'236 }237 }238 """)239 }240 `when`("listing tasks") {241 fixture.build("tasks")242 then("should contain the declared tasks") {243 taskNames.forEach {244 fixture.assertBuildOutputContains(it)245 }246 }247 }248 `when`("building") {249 fixture.build(extraArguments = *taskNames)250 then("should create the correct packs") {251 fixture.assertFileEquals("packTextures/namedContainerPack1.atlas", "pack1/pack1.atlas")252 fixture.assertFileEquals("packTextures/namedContainerPack2.atlas", "pack2/test.assets")253 fixture.assertFileEquals("packTextures/namedContainerPack3.atlas","pack3/pack3.atlas")254 }255 }256 `when`("changing one of the tasks after build") {257 fixture.build(extraArguments = *taskNames)258 fixture.buildFile(fixture.getBuildFile().replace("MipMapLinearLinear", "Nearest"))259 fixture.build(extraArguments = *taskNames)260 then("should only build the changed task again") {261 fixture.assertBuildUpToDate("packPack1Textures")262 fixture.assertBuildSuccess("packPack2Textures")263 fixture.assertBuildUpToDate("packPack3Textures")264 }265 }266 `when`("running ${GdxPlugin.ALL_PACKS_TASK_NAME}") {267 fixture.build(GdxPlugin.ALL_PACKS_TASK_NAME)268 then("should run all texture pack tasks") {269 fixture.assertBuildSuccess("packPack1Textures")270 fixture.assertBuildSuccess("packPack2Textures")271 fixture.assertBuildSuccess("packPack3Textures")272 }273 }274 `when`("running ${GdxPlugin.ALL_PACKS_TASK_NAME}, changing one of the tasks after build and running ${GdxPlugin.ALL_PACKS_TASK_NAME} again") {275 fixture.build(GdxPlugin.ALL_PACKS_TASK_NAME)276 fixture.buildFile(fixture.getBuildFile().replace("MipMapLinearLinear", "Nearest"))277 fixture.build(GdxPlugin.ALL_PACKS_TASK_NAME)278 then("should only build the changed task again") {279 fixture.assertBuildUpToDate("packPack1Textures")280 fixture.assertBuildSuccess("packPack2Textures")281 fixture.assertBuildUpToDate("packPack3Textures")282 }283 }284 }285 given("a task with multiple scales with suffixes") {286 beforeContainer {287 fixture.buildFile("""288 packTextures {289 from 'in'290 into 'out'291 settings {292 scale = [1, 2, 3]293 scaleSuffix = ["one", "two", "three"]294 scaleResampling = ["bilinear", "nearest", "bicubic"]295 }296 }297 """.trimIndent())298 }299 `when`("building") {300 fixture.build("packTextures")301 then("should create the correct packs") {302 fixture.assertFileEquals("packTextures/multipleScales1.atlas", "packone.atlas")303 fixture.assertFileEquals("packTextures/multipleScales2.atlas", "packtwo.atlas")304 fixture.assertFileEquals("packTextures/multipleScales3.atlas", "packthree.atlas")305 }306 }307 `when`("removing one of the atlases and building again") {308 fixture.build("packTextures")309 fixture.output["packone.atlas"].delete()310 fixture.output["packtwo.atlas"].delete()311 fixture.output["packthree.atlas"].delete()312 fixture.build("packTextures")313 then("should build again") {314 fixture.assertBuildSuccess()315 }316 }317 `when`("removing the suffix spec and building again") {318 fixture.build("packTextures")319 fixture.buildFile(fixture.getBuildFile().replace("one\", \"two\", \"three", "\", \"\", \""))320 fixture.build("packTextures")321 then("should create the packs in subdirectories") {322 fixture.assertFileEquals("packTextures/multipleScalesSubdir1.atlas", "1/pack.atlas")323 fixture.assertFileEquals("packTextures/multipleScalesSubdir2.atlas", "2/pack.atlas")324 fixture.assertFileEquals("packTextures/multipleScalesSubdir3.atlas", "3/pack.atlas")325 }326 }327 }328 given("a custom task") {329 beforeContainer {330 fixture.buildFile("""331 import com.github.blueboxware.gdxplugin.tasks.PackTextures332 task('customTask', type: PackTextures) {333 into 'out'334 from 'in/images2'335 settings {336 atlasExtension = ".assets"337 filterMin = "MipMapLinearLinear"338 }339 }340 """)341 }342 `when`("building") {343 fixture.build("customTask")344 then("should create a correct atlas") {345 fixture.assertFileEquals("packTextures/customTask.atlas", "customTask.assets")346 }347 }348 `when`("changing the pack name after build") {349 fixture.build("customTask")350 fixture.buildFile(fixture.getBuildFile().replace("settings", "packFileName = 'foo'\nsettings"))351 fixture.build("customTask")352 then("should build again") {353 fixture.assertBuildSuccess()354 }355 then("should use the new name") {356 TestCase.assertTrue(fixture.output["foo.assets"].exists())357 }358 }359 `when`("running ${GdxPlugin.ALL_PACKS_TASK_NAME}") {360 fixture.build(GdxPlugin.ALL_PACKS_TASK_NAME)361 then("should run the custom task") {362 fixture.assertBuildSuccess()363 }364 }365 }366 given("a packTextures task with filtering and renaming") {367 beforeContainer {368 fixture.buildFile("""369 def d = copySpec {370 from('in/images2') {371 include 'b*'372 rename 'ba(.*)\\.(.*)', 'ba$1$1.$2'373 }374 }375 packTextures {376 from('in/images1') {377 exclude('sub/subsub')378 }379 into 'out'380 exclude '**/empty*'381 with d382 }383 """)384 }385 `when`("building") {386 fixture.build("packTextures")387 then("should create the correct atlas") {388 fixture.assertFileEquals("packTextures/filteringAndRenaming.atlas", "pack.atlas")389 }390 }391 `when`("removing an excluded file after building") {392 fixture.build("packTextures")393 fixture.input["images2/add.png"].delete()394 fixture.build("packTextures")395 then("should be up-to-date the second time") {396 fixture.assertBuildUpToDate()397 }398 }399 `when`("removing an included file after building") {400 fixture.build("packTextures")401 fixture.input["images2/back.png"].delete()402 fixture.build("packTextures")403 then("should build again the second time") {404 fixture.assertBuildSuccess()405 }406 }407 }408 given("a packTextures with (almost) all settings used") {409 beforeContainer {410 fixture.buildFile("""411 packTextures {412 from 'in'413 into 'out'414 settings {415 paddingX = 4416 paddingY = 6417 edgePadding = false418 duplicatePadding = true419 rotation = true420 minWidth = 32421 minHeight = 128422 maxWidth = 2048423 maxHeight = 1024424 square = true425 stripWhitespaceX = true426 stripWhitespaceY = true427 alphaThreshold = 2428 filterMin = "MipMap"429 filterMag = "Linear"430 wrapX = "Repeat"431 wrapY = "MirroredRepeat"432 format = "RGBA4444"433 alias = false434 outputFormat = "jpg"435 jpegQuality = 0.1436 ignoreBlankImages = false437 fast = true438 debug = true439 combineSubdirectories = true440 flattenPaths = true441 premultiplyAlpha = true442 useIndexes = false443 bleed = true444 bleedIterations = 8445 limitMemory = true446 grid = true447 scale = [1, 2]448 scaleSuffix = ["1", "2"]449 scaleResampling = ["bilinear", "nearest"]450 atlasExtension = ".atlas"451 }452 }453 """)454 }455 `when`("building") {456 fixture.build("packTextures")457 then("should create correct results") {458 fixture.assertFileEquals("packTextures/withAllSettings1.atlas", "pack1.atlas")459 fixture.assertFileEquals("packTextures/withAllSettings2.atlas", "pack2.atlas")460 }461 then("should create correct images") {462 fixture.assertFileEqualsBinary("packTextures/withAllSettings1.jpg", "pack1.jpg")463 fixture.assertFileEqualsBinary("packTextures/withAllSettings2.jpg", "pack2.jpg")464 }465 }466 }467 given("some custom settings objects (using PackTextures.createSettings)") {468 beforeContainer {469 fixture.buildFile("""470 import com.github.blueboxware.gdxplugin.tasks.PackTextures471 def packSettings = PackTextures.createSettings {472 filterMin = 'MipMapLinearNearest'473 filterMag = 'Nearest'474 maxWidth = 2048475 maxHeight = 2048476 scale = [1, 2, 3]477 outputFormat = "jpg"478 }479 def scaledPackSettings = PackTextures.createSettings(packSettings) {480 scaleSuffix = ["Normal", "Scaled", "Foo"]481 scaleResampling = ["bicubic", "bicubic", "bicubic"]482 filterMag = 'Linear'483 }484 texturePacks {485 pack1 {486 from 'in/images2'487 into 'out/pack1'488 settings = scaledPackSettings489 }490 pack2 {491 from 'in/images1'492 into 'out/pack2'493 settings = PackTextures.createSettings(scaledPackSettings) {494 debug = true495 }496 }497 }498 """)499 }500 `when`("building") {501 fixture.build("packPack1Textures", "packPack2Textures")502 then("should create the correct atlases and images") {503 fixture.assertFileEquals("packTextures/customSettings/pack1Foo.atlas", "pack1/pack1Foo.atlas")504 fixture.assertFileEquals("packTextures/customSettings/pack2Scaled.atlas", "pack2/pack2Scaled.atlas")505 fixture.assertFileEqualsBinary("packTextures/customSettings/pack1Scaled.jpg", "pack1/pack1Scaled.jpg")506 fixture.assertFileEqualsBinary("packTextures/customSettings/pack2Normal2.jpg", "pack2/pack2Normal2.jpg")507 }508 }509 }510 given("some custom settings objects (using packSettings)") {511 beforeContainer {512 fixture.buildFile("""513 import static com.github.blueboxware.gdxplugin.dsl.Utils.*514 def baseSettings = packSettings {515 filterMin = 'MipMapLinearNearest'516 filterMag = 'Nearest'517 maxWidth = 2048518 maxHeight = 2048519 scale = [1, 2, 3]520 outputFormat = "jpg"521 }522 def scaledPackSettings = packSettings(baseSettings) {523 scaleSuffix = ["Normal", "Scaled", "Foo"]524 scaleResampling = ["bicubic", "bicubic", "bicubic"]525 filterMag = 'Linear'526 }527 texturePacks {528 pack1 {529 from 'in/images2'530 into 'out/pack1'531 settings = scaledPackSettings532 }533 pack2 {534 from 'in/images1'535 into 'out/pack2'536 settings = packSettings(scaledPackSettings) {537 debug = true538 }539 }540 }541 """)542 }543 `when`("building") {544 fixture.build("packPack1Textures", "packPack2Textures")545 then("should create the correct atlases and images") {546 fixture.assertFileEquals("packTextures/customSettings/pack1Foo.atlas", "pack1/pack1Foo.atlas")547 fixture.assertFileEquals("packTextures/customSettings/pack2Scaled.atlas", "pack2/pack2Scaled.atlas")548 fixture.assertFileEqualsBinary("packTextures/customSettings/pack1Scaled.jpg", "pack1/pack1Scaled.jpg")549 fixture.assertFileEqualsBinary("packTextures/customSettings/pack2Normal2.jpg", "pack2/pack2Normal2.jpg")550 }551 }552 }553 given("a pack textures task with solids") {554 beforeContainer {555 fixture.buildFile("""556 packTextures {557 into 'out'558 solid {559 name = "white"560 }561 solid {562 name = "red"563 color = color("#ff0000");564 width = 3565 height = 4566 }567 solid {568 name = "green"569 color = color("#00ff00ff");570 height = 4571 }572 }573 """)574 }575 `when`("building") {576 fixture.build("packTextures")577 then("should create the correct atlas") {578 fixture.assertFileEquals("packTextures/solids.atlas", "pack.atlas")579 fixture.assertFileEqualsBinary("packTextures/solids.png", "pack.png")580 }581 }582 }583})...
AEntryPointTest.kt
Source:AEntryPointTest.kt
1/*2 * Copyright (c) 2021. Tran Phan3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 *16 */17package io.github.phantran.integration18import io.kotest.core.spec.style.AnnotationSpec19import io.kotest.matchers.ints.shouldBeInRange20import io.mockk.unmockkAll21import io.github.phantran.engine.Configuration22import io.github.phantran.engine.MoCoEntryPoint23import io.github.phantran.engine.operator.Operator24import io.github.phantran.persistence.H2Database25import io.github.phantran.utils.MoCoLogger26import org.apache.commons.io.FileUtils27import java.io.File28import java.nio.file.Paths29import kotlin.math.roundToInt30class AEntryPointTest : AnnotationSpec() {31 private val baseDir = Paths.get("").toAbsolutePath().toString()32 private val buildRoot = "$baseDir/src/test/resources/test-artifacts/"33 private val codeRoot = "$baseDir/src/test/resources/test-artifacts/sources"34 private val testRoot = "$baseDir/src/test/resources/test-artifacts/tests"35 private val classpath =36 System.getProperty("java.class.path") + File.pathSeparator + codeRoot + File.pathSeparator + testRoot37 private val jvm = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"38 @BeforeEach39 fun init() {40 unmockkAll()41 FileUtils.deleteDirectory(File(buildRoot + "moco"))42 }43 @AfterAll44 fun cleanUp() {45 unmockkAll()46 FileUtils.deleteDirectory(File(buildRoot + "moco"))47 }48 @Test49 fun testEntryPoint1() {50 try {51 val excluded = ""52 val fOpNames = Operator.supportedOperatorNames.filter { !excluded.contains(it) }53 val configuration = Configuration(54 baseDir,55 System.currentTimeMillis().toString(),56 buildRoot,57 codeRoot,58 testRoot,59 codeRoot,60 testRoot,61 "$buildRoot${File.separator}moco",62 "dev.Hihi",63 "",64 "dev.HihiTest",65 "io/moco/integration/",66 classpath,67 jvm,68 "preprocess",69 "mutation",70 excluded,71 fOpNames,72 buildRoot,73 listOf(),74 "dev",75 "m0c0-maven-plugin",76 false,77 "200",78 0,79 true,80 debugEnabled = false,81 verbose = false,82 2,83 noLogAtAll = true,84 enableMetrics = true,85 mocoPluginVersion = "1.0-SNAPSHOT"86 )87 Configuration.currentConfig = configuration88 MoCoLogger.useKotlinLog()89 MoCoLogger.noLogAtAll = true90 MoCoLogger.debugEnabled = Configuration.currentConfig!!.debugEnabled91 H2Database.initPool(92 url = "jdbc:h2:file:${Configuration.currentConfig?.mocoBuildPath}" +93 "${File.separator}/persistence/moco;mode=MySQL",94 user = "moco",95 password = "moco",96 )97 H2Database().initDBTablesIfNotExists()98 MoCoEntryPoint(configuration).execute()99 MoCoEntryPoint.runScore.roundToInt() shouldBeInRange IntRange(50, 60)100 } finally {101 H2Database.shutDownDB()102 }103 }104 @Test105 fun testEntryPoint2() {106 try {107 val excluded = ""108 val fOpNames = Operator.supportedOperatorNames.filter { !excluded.contains(it) }109 val configuration = Configuration(110 baseDir,111 System.currentTimeMillis().toString(),112 buildRoot,113 codeRoot,114 testRoot,115 codeRoot,116 testRoot,117 "$buildRoot${File.separator}moco",118 "dev.Hihi",119 "",120 "dev.HihiTest",121 "io/moco/integration/",122 classpath,123 jvm,124 "preprocess",125 "mutation",126 excluded,127 fOpNames,128 buildRoot,129 listOf(),130 "dev",131 "m0c0-maven-plugin",132 false,133 "200",134 0,135 false,136 debugEnabled = false,137 verbose = false,138 2,139 noLogAtAll = true,140 enableMetrics = true,141 mocoPluginVersion = "1.0-SNAPSHOT"142 )143 Configuration.currentConfig = configuration144 MoCoLogger.useKotlinLog()145 MoCoLogger.noLogAtAll = true146 MoCoLogger.debugEnabled = Configuration.currentConfig!!.debugEnabled147 H2Database.initPool(148 url = "jdbc:h2:file:${Configuration.currentConfig?.mocoBuildPath}" +149 "${File.separator}/persistence/moco;mode=MySQL",150 user = "moco",151 password = "moco",152 )153 H2Database().initDBTablesIfNotExists()154 MoCoEntryPoint(configuration).execute()155 MoCoEntryPoint.runScore.roundToInt() shouldBeInRange IntRange(55, 60)156 } finally {157 H2Database.shutDownDB()158 }159 }160 @Test161 fun testEntryPoint3() {162 try {163 val excluded = ""164 val fOpNames = Operator.supportedOperatorNames.filter { !excluded.contains(it) }165 val configuration = Configuration(166 baseDir,167 System.currentTimeMillis().toString(),168 buildRoot,169 codeRoot,170 testRoot,171 codeRoot,172 testRoot,173 "$buildRoot${File.separator}moco",174 "dev.Hihi",175 "",176 "dev.HihiTest",177 "io/moco/integration/",178 classpath,179 jvm,180 "preprocess",181 "mutation",182 excluded,183 fOpNames,184 buildRoot,185 listOf(),186 "dev",187 "m0c0-maven-plugin",188 true,189 "200",190 0,191 true,192 debugEnabled = false,193 verbose = false,194 2,195 noLogAtAll = true,196 enableMetrics = true,197 mocoPluginVersion = "1.0-SNAPSHOT"198 )199 Configuration.currentConfig = configuration200 MoCoLogger.useKotlinLog()201 MoCoLogger.noLogAtAll = true202 MoCoLogger.debugEnabled = Configuration.currentConfig!!.debugEnabled203 H2Database.initPool(204 url = "jdbc:h2:file:${Configuration.currentConfig?.mocoBuildPath}" +205 "${File.separator}/persistence/moco;mode=MySQL",206 user = "moco",207 password = "moco",208 )209 H2Database().initDBTablesIfNotExists()210 MoCoEntryPoint(configuration).execute()211 MoCoEntryPoint.runScore.roundToInt() shouldBeInRange IntRange(55, 60)212 MoCoEntryPoint(configuration).execute()213 MoCoEntryPoint.runScore.roundToInt() shouldBeInRange IntRange(55, 60)214 } finally {215 H2Database.shutDownDB()216 }217 }218}...
JunitXmlReporter.kt
Source:JunitXmlReporter.kt
1package io.kotest.extensions.junitxml2import io.kotest.core.config.ProjectConfiguration3import io.kotest.core.listeners.FinalizeSpecListener4import io.kotest.core.listeners.PrepareSpecListener5import io.kotest.core.spec.Spec6import io.kotest.core.test.TestCase7import io.kotest.core.test.TestResult8import io.kotest.core.test.TestType9import io.kotest.engine.test.names.formatTestPath10import io.kotest.engine.test.names.getDisplayNameFormatter11import org.jdom2.Document12import org.jdom2.Element13import org.jdom2.output.Format14import org.jdom2.output.XMLOutputter15import java.net.InetAddress16import java.net.UnknownHostException17import java.nio.file.Files18import java.nio.file.Path19import java.nio.file.Paths20import java.nio.file.StandardOpenOption21import java.time.Clock22import java.time.LocalDateTime23import java.time.format.DateTimeFormatter.ISO_LOCAL_DATE_TIME24import java.util.concurrent.ConcurrentHashMap25import kotlin.reflect.KClass26import kotlin.time.Duration27import kotlin.time.DurationUnit28@Deprecated("Now called JunitXmlReporter. Deprecated since 4.6.")29typealias JunitXmlListener = JunitXmlReporter30/**31 * A JUnit xml legacy format writer.32 *33 * This implementation handles nesting, whereas the junit implementation will only output for leaf tests.34 *35 * @param includeContainers when true, all intermediate tests are included in the report as36 * tests in their own right. Defaults to false.37 *38 * @param useTestPathAsName when true, the full test path will be used as the name. In other39 * words the name will include the name of any parent tests as a single string.40 */41class JunitXmlReporter(42 private val includeContainers: Boolean = false,43 private val useTestPathAsName: Boolean = true,44 private val outputDir: String = "test-results/test"45) : PrepareSpecListener, FinalizeSpecListener {46 companion object {47 const val DefaultBuildDir = "./build"48 // sets the build directory, to which test-results will be appended49 const val BuildDirKey = "gradle.build.dir"50 const val AttributeName = "name"51 }52 private val formatter = getDisplayNameFormatter(ProjectConfiguration().registry, ProjectConfiguration())53 private var marks = ConcurrentHashMap<KClass<out Spec>, Long>()54 private fun outputDir(): Path {55 val buildDir = System.getProperty(BuildDirKey)56 return if (buildDir != null)57 Paths.get(buildDir).resolve(outputDir)58 else59 Paths.get(DefaultBuildDir).resolve(outputDir)60 }61 override suspend fun prepareSpec(kclass: KClass<out Spec>) {62 marks[kclass] = System.currentTimeMillis()63 }64 private fun filterResults(results: Map<TestCase, TestResult>) = when (includeContainers) {65 true -> results66 false -> results.filter { it.key.type == TestType.Test }67 }68 override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) {69 val start = marks[kclass] ?: System.currentTimeMillis()70 val duration = System.currentTimeMillis() - start71 val filtered = filterResults(results)72 val document = Document()73 val testSuite = Element("testsuite")74 testSuite.setAttribute("timestamp", ISO_LOCAL_DATE_TIME.format(getCurrentDateTime()))75 testSuite.setAttribute("time", (Duration.milliseconds(duration).toDouble(DurationUnit.SECONDS)).toString())76 testSuite.setAttribute("hostname", hostname())77 testSuite.setAttribute("errors", filtered.filter { it.value.isError }.size.toString())78 testSuite.setAttribute("failures", filtered.filter { it.value.isFailure }.size.toString())79 testSuite.setAttribute("skipped", filtered.filter { it.value.isIgnored }.size.toString())80 testSuite.setAttribute("tests", filtered.size.toString())81 testSuite.setAttribute(AttributeName, formatter.format(kclass))82 document.addContent(testSuite)83 filtered.map { (testcase, result) ->84 val name = when (useTestPathAsName) {85 true -> formatter.formatTestPath(testcase, " -- ")86 false -> formatter.format(testcase)87 }88 val e = Element("testcase")89 e.setAttribute(AttributeName, name)90 e.setAttribute("classname", kclass.java.canonicalName)91 e.setAttribute("time", result.duration.toDouble(DurationUnit.SECONDS).toString())92 when (result) {93 is TestResult.Error -> {94 val err = Element("error")95 result.errorOrNull?.let {96 err.setAttribute("type", it.javaClass.name)97 err.setText(it.message)98 }99 e.addContent(err)100 }101 is TestResult.Failure -> {102 val failure = Element("failure")103 result.errorOrNull?.let {104 failure.setAttribute("type", it.javaClass.name)105 failure.setText(it.message)106 }107 e.addContent(failure)108 }109 else -> Unit110 }111 testSuite.addContent(e)112 }113 write(kclass, document)114 }115 private fun write(kclass: KClass<*>, document: Document) {116 val path = outputDir().resolve("TEST-" + formatter.format(kclass) + ".xml")117 path.parent.toFile().mkdirs()118 val outputter = XMLOutputter(Format.getPrettyFormat())119 val writer = Files.newBufferedWriter(path, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE)120 outputter.output(document, writer)121 writer.flush()122 writer.close()123 }124 private fun hostname(): String? {125 return try {126 InetAddress.getLocalHost().hostName127 } catch (e: UnknownHostException) {128 null129 }130 }131 private fun getCurrentDateTime(): LocalDateTime {132 return LocalDateTime.now(Clock.systemDefaultZone()).withNano(0)133 }134}...
PreprocessWorkerTest.kt
Source:PreprocessWorkerTest.kt
1/*2 * Copyright (c) 2021. Tran Phan3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 *16 */17package io.github.phantran.integration18import io.kotest.core.spec.style.AnnotationSpec19import io.kotest.matchers.shouldNotBe20import io.mockk.unmockkAll21import io.github.phantran.engine.Codebase22import io.github.phantran.engine.Configuration23import io.github.phantran.engine.operator.Operator24import io.github.phantran.engine.preprocessing.Preprocessor25import io.github.phantran.engine.preprocessing.PreprocessorTracker26import io.github.phantran.engine.preprocessing.PreprocessorWorker27import org.apache.commons.io.FileUtils28import java.io.File29import java.nio.file.Paths30class PreprocessWorkerTest : AnnotationSpec() {31 private val baseDir = Paths.get("").toAbsolutePath().toString()32 private val buildRoot = "$baseDir/src/test/resources/test-artifacts/"33 private val codeRoot = "$baseDir/src/test/resources/test-artifacts/sources"34 private val testRoot = "$baseDir/src/test/resources/test-artifacts/tests"35 private val classpath =36 System.getProperty("java.class.path") + File.pathSeparator + codeRoot + File.pathSeparator + testRoot37 private val jvm = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java"38 private val excluded = ""39 private val fOpNames = Operator.supportedOperatorNames.filter { !excluded.contains(it) }40 private val configuration = Configuration(41 "/Users/phantran/Study/Passau/Thesis/TestGamekins/test/",42 System.currentTimeMillis().toString(),43 buildRoot,44 codeRoot,45 testRoot,46 codeRoot,47 testRoot,48 "$buildRoot${File.separator}moco",49 "dev.Hihi",50 "",51 "dev.HihiTest",52 "",53 classpath,54 jvm,55 "preprocess",56 "mutation",57 excluded,58 fOpNames,59 buildRoot,60 listOf(),61 "dev",62 "m0c0-maven-plugin",63 false,64 "200",65 0,66 true,67 debugEnabled = true,68 verbose = true,69 2,70 noLogAtAll = true,71 mocoPluginVersion = "1.0-SNAPSHOT"72 )73 @AfterAll74 fun cleanUp() {75 unmockkAll()76 FileUtils.deleteDirectory(File(buildRoot + "moco"));77 Configuration.currentConfig = null78 }79 @Test80 fun testMain() {81 val args = arrayOf("0", *configuration.getPreprocessProcessArgs().toTypedArray(), "", "", "false")82 PreprocessorWorker.prepareWorker(args)83 val analysedCodeBase = Codebase(84 PreprocessorWorker.codeRoot,85 PreprocessorWorker.testRoot,86 PreprocessorWorker.codeRoot,87 PreprocessorWorker.testRoot,88 PreprocessorWorker.excludedSourceClasses,89 PreprocessorWorker.excludedSourceFolders,90 PreprocessorWorker.excludedTestClasses,91 PreprocessorWorker.excludedTestFolders92 )93 val relevantTests = PreprocessorWorker.getRelevantTests(94 PreprocessorWorker.filteredClsByGitCommit,95 analysedCodeBase,96 PreprocessorWorker.recordedTestMapping97 )98 Preprocessor(relevantTests).preprocessing(PreprocessorWorker.isRerun, PreprocessorWorker.jsonConverter)99 PreprocessorTracker.getPreprocessResults() shouldNotBe null100 }101}...
CacheTests.kt
Source:CacheTests.kt
1/*2 * Copyright (c) 2021. The Meowool Organization Open Source Project3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 *16 * In addition, if you modified the project, you must include the Meowool17 * organization URL in your code file: https://github.com/meowool18 *19 * å¦ææ¨ä¿®æ¹äºæ¤é¡¹ç®ï¼åå¿
须确ä¿æºæ件ä¸å
å« Meowool ç»ç» URL: https://github.com/meowool20 */21@file:Suppress("EXPERIMENTAL_API_USAGE")22import com.meowool.gradle.toolkit.internal.DependencyMapperExtensionImpl23import com.meowool.gradle.toolkit.internal.DependencyMapperInternal.CacheDir24import com.meowool.gradle.toolkit.internal.DependencyMapperInternal.CacheJarsDir25import io.kotest.assertions.forEachAsClue26import io.kotest.core.spec.style.StringSpec27import io.kotest.engine.spec.tempdir28import io.kotest.matchers.shouldBe29import io.kotest.matchers.string.shouldStartWith30import org.gradle.testfixtures.ProjectBuilder31/**32 * @author å (RinOrz)33 */34class CacheTests : StringSpec({35 val project = ProjectBuilder.builder().withProjectDir(tempdir()).build()36 val dependencyMapper = DependencyMapperExtensionImpl(project).apply {37 val p = plugins("PluginMapped")38 libraries("Libraries") {39 transferPluginIds(p)40 map("foo:bar", "a.B.C:dd")41 map(42 "com.foo.bar:v" to "Foo",43 "test:test.plugin" to "Test.Plugin"44 )45 searchDefaultOptions {46 filter { true }47 }48 search("meowool")49 searchGroups("com.google.android") {50 fromGoogle()51 filter { false }52 }53 searchPrefixes("org.jetbrains.anko", "org.apache.avro") {54 fromMavenCentral()55 fromGradlePluginPortal()56 }57 }58 projects("PATHS")59 }60 fun checkUsingCache() {61 dependencyMapper.mapping() shouldBe false62 }63 fun checkRemapping() {64 dependencyMapper.mapping() shouldBe true65 }66 "initial cache" {67 checkRemapping()68 }69 "remapping" {70 println("============== using cache ==============")71 checkUsingCache()72 dependencyMapper.apply {73 libraries("Libraries") {74 map("new.group:id")75 }76 }77 checkRemapping()78 println("============== using cache ==============")79 checkUsingCache()80 dependencyMapper.apply {81 plugins("AdditionalPlugins") {82 map("addition.plugin")83 }84 }85 checkRemapping()86 }87 "clear cache" {88 checkUsingCache()89 // Ensure that some cache names remain unchanged90 val cacheJarsDir = project.projectDir.resolve("$CacheDir/$CacheJarsDir")91 val cacheJars = cacheJarsDir.listFiles()!!92 // Clear `AdditionalPlugins`93 cacheJars.filter { it.name.startsWith("AdditionalPlugins") }.forEach { it.delete() }94 checkRemapping()95 val newCacheJars = cacheJarsDir.listFiles()!!96 // Only `AdditionalPlugins` re-cached97 newCacheJars.filter { new ->98 // Filter out names that do not exist in the old `cacheJars`99 cacheJars.none { old -> new == old }100 }.forEachAsClue { it.name.shouldStartWith("AdditionalPlugins") }101 }102})...
CodebaseTest.kt
Source:CodebaseTest.kt
1/*2 * Copyright (c) 2021. Tran Phan3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 *16 */17package io.github.phantran.engine18import io.kotest.core.spec.style.AnnotationSpec19import io.kotest.matchers.shouldBe20import io.kotest.matchers.shouldNotBe21import io.mockk.unmockkAll22import java.nio.file.Paths23class CodebaseTest : AnnotationSpec() {24 @BeforeEach25 fun init() {26 }27 @AfterAll28 fun cleanUp() {29 unmockkAll()30 }31 @Test32 fun testCodeBase() {33 val excludedSourceClasses = mutableListOf("")34 val excludedSourceFolders = mutableListOf("io/moco/engine/mutator")35 val excludedTestClasses = mutableListOf("")36 val excludedTestFolders = mutableListOf("")37 val codePath = Paths.get("").toAbsolutePath().toString() + "/target/classes/io/moco/engine"38 val testPath = Paths.get("").toAbsolutePath().toString() + "/target/test-classes/io/moco/engine"39 val codeBase = Codebase(40 codePath, testPath, codePath, testPath, excludedSourceClasses, excludedSourceFolders,41 excludedTestClasses, excludedTestFolders42 )43 codeBase.sourceClassNames.size shouldBe 044 codeBase.toString() shouldNotBe ""45 }46}...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!