How to use logs class of io.kotest.engine.test.logging package

Best Kotest code snippet using io.kotest.engine.test.logging.logs

build.gradle.kts

Source:build.gradle.kts Github

copy

Full Screen

1import org.jetbrains.kotlin.gradle.tasks.KotlinCompile2import org.springframework.boot.gradle.tasks.bundling.BootBuildImage3plugins {4 java5 idea6 id("org.springframework.boot") version "2.5.4"7 id("io.spring.dependency-management") version "1.0.11.RELEASE"8 kotlin("jvm") version "1.5.30"9 kotlin("plugin.spring") version "1.5.30"10 id("org.jlleitschuh.gradle.ktlint") version "10.1.0"11 id("org.jlleitschuh.gradle.ktlint-idea") version "10.1.0"12 id("org.liquibase.gradle") version "2.0.4"13 jacoco14 id("org.sonarqube") version "3.3"15}16group = "br.com.quanto.tsp.template"17version = "0.0.3"18java.sourceCompatibility = JavaVersion.VERSION_1619val ghPkgUsername by extra(System.getenv("GH_PACKAGES_USERNAME") ?: project.property("github.username").toString())20val ghPkgPassword by extra(System.getenv("GH_PACKAGES_PASSWORD") ?: project.property("github.token").toString())21val sonarquebeKey by extra(System.getenv("SONAR_KEY") ?: "tsp-kotlin-ms-template")22val protobucketVersion = "1.20.6"23val tagVersion by extra(System.getenv("BUILD_TAG_VERSION") ?: version)24val exposedVersion = "0.34.1"25val liquibaseVersion = "4.4.3"26val testContainerVersion = "1.16.0"27repositories {28 mavenCentral()29 maven {30 url = uri("https://plugins.gradle.org/m2/")31 }32 maven {33 url = uri("https://maven.pkg.github.com/contaquanto/tspprotobucket")34 credentials {35 username = ghPkgUsername36 password = ghPkgPassword37 }38 }39 maven {40 url = uri("https://maven.pkg.github.com/contaquanto/tsp-logpose")41 credentials {42 username = ghPkgUsername43 password = ghPkgPassword44 }45 }46}47springBoot {48 buildInfo {49 properties {50 additional = mapOf(51 "tagVersion" to tagVersion,52 )53 }54 }55}56extra["springCloudVersion"] = "2020.0.3"57dependencies {58 // Kotlin59 implementation("org.jetbrains.kotlin:kotlin-reflect")60 implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")61 // Spring REST62 implementation("org.springframework.boot:spring-boot-starter")63 implementation("org.springframework.boot:spring-boot-starter-web")64 // REST Client65 implementation("org.springframework.cloud:spring-cloud-starter-openfeign")66 // Kafka67 implementation("org.springframework.kafka:spring-kafka")68 // Logs in JSON Format69 implementation("org.springframework.boot:spring-boot-starter-log4j2")70 implementation("com.fasterxml.jackson.module:jackson-module-kotlin")71 implementation("com.lmax:disruptor:3.4.4")72 // YAML log4 config73 implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml")74 // Idiomatic Logging in Kotlin75 implementation("io.github.microutils:kotlin-logging:2.0.11")76 // Tracing - Open Tracing77 implementation("org.springframework.cloud:spring-cloud-starter-sleuth")78 implementation("org.springframework.cloud:spring-cloud-sleuth-zipkin")79 implementation("io.opentracing:opentracing-api:0.33.0")80 // Grpc - Tracing81 implementation("io.zipkin.brave:brave-instrumentation-grpc:5.13.3")82 // Health and Metrics83 implementation("org.springframework.boot:spring-boot-starter-actuator")84 runtimeOnly("io.micrometer:micrometer-registry-prometheus")85 // GRPC86 // Se você for só usar o GRPC cliente use :87 // implementation("net.devh:grpc-client-spring-boot-starter:2.12.0.RELEASE")88 // Se você for usar tanto cliente quanto server grpc use:89 implementation("net.devh:grpc-spring-boot-starter:2.12.0.RELEASE")90 // GRPC Kafka Serializer/Deserializers91 implementation("com.github.daniel-shuy:kafka-protobuf-serde:2.2.0")92 // GRPC ProtoBuf from ProtoBucket import93 implementation("br.com.quanto.tsp.protobucket:event:$protobucketVersion")94 implementation("br.com.quanto.tsp.protobucket:template:$protobucketVersion")95 implementation("br.com.quanto.tsp.protobucket:templatethirdparty:$protobucketVersion")96 implementation("br.com.quanto.tsp.protobucket:action:$protobucketVersion")97 // AuditLogLibrary - LOGPOSE98 implementation("br.com.quanto.tsp:logpose:2.2.1")99 // Vault100 implementation("org.springframework.cloud:spring-cloud-starter-vault-config")101 implementation("org.springframework.cloud:spring-cloud-starter-bootstrap")102 // SQL103 implementation("org.postgresql:postgresql:42.2.23")104 implementation("org.springframework.boot:spring-boot-starter-jdbc")105 implementation("org.jetbrains.exposed:exposed-core:$exposedVersion")106 implementation("org.jetbrains.exposed:exposed-jdbc:$exposedVersion")107 implementation("org.jetbrains.exposed:exposed-java-time:$exposedVersion")108 implementation("org.jetbrains.exposed:spring-transaction:$exposedVersion")109 // SQL VAULT110 implementation("org.springframework.cloud:spring-cloud-vault-config-databases")111 // LIQUIBASE112 implementation("org.liquibase:liquibase-core:$liquibaseVersion")113 liquibaseRuntime("org.liquibase:liquibase-core:$liquibaseVersion")114 liquibaseRuntime("org.liquibase:liquibase-groovy-dsl:3.0.2")115 liquibaseRuntime("org.postgresql:postgresql:42.2.23")116 liquibaseRuntime("org.yaml:snakeyaml:1.29")117 // Test118 testImplementation("org.springframework.boot:spring-boot-starter-test") {119 exclude("org.junit.vintage", "junit-vintage-engine")120 exclude("org.mockito", "mockito-core")121 exclude("org.mockito", "mockito-junit-jupiter")122 }123 // Cuidado ao aumentar a versão dessa dependencia, pois pode gerar conflito com o tspprotobucket124 // Fortemente recomendado manter a mesma versão do io.grpc do build.gradle do repositorio tspprotobucket125 testImplementation("io.grpc:grpc-testing")126 // INTEGRATION TESTS TESTCONTAINERS127 testImplementation("org.testcontainers:testcontainers:$testContainerVersion")128 testImplementation("org.testcontainers:junit-jupiter:$testContainerVersion")129 testImplementation("org.testcontainers:kafka:$testContainerVersion")130 // SQL131 testImplementation("org.testcontainers:postgresql:$testContainerVersion")132 // VAULT133 testImplementation("org.testcontainers:vault:$testContainerVersion")134 // REST INTEGRATION TESTS135 testImplementation("org.springframework.cloud:spring-cloud-starter-contract-stub-runner")136 // GRPC INTEGRATION TESTS137 testImplementation("org.grpcmock:grpcmock-spring-boot:0.6.0")138 // FAKER139 testImplementation("io.github.serpro69:kotlin-faker:1.7.1")140 // KOTEST141 testImplementation("io.kotest:kotest-assertions-core-jvm:4.6.2")142 // MOCKK143 testImplementation("io.mockk:mockk:1.12.0")144 testImplementation("com.ninja-squad:springmockk:3.0.1")145}146configurations.all {147 exclude(group = "org.springframework.boot", module = "spring-boot-starter-logging")148 resolutionStrategy.eachDependency {149 if (requested.group == "io.grpc") {150 useVersion("1.37.0")151 because("Guarantee of use the same version that are in use in tspprotobucket")152 }153 }154}155dependencyManagement.imports {156 mavenBom("org.springframework.cloud:spring-cloud-dependencies:${property("springCloudVersion")}")157}158tasks.withType<KotlinCompile> {159 kotlinOptions {160 freeCompilerArgs = listOf("-Xjsr305=strict", "-Xemit-jvm-type-annotations")161 jvmTarget = "16"162 }163}164tasks.withType<Test> {165 useJUnitPlatform()166 finalizedBy("jacocoTestReport")167 doLast {168 println("View code coverage at:")169 println("file://$buildDir/reports/jacoco/test/html/index.html")170 }171}172apply(plugin = "org.jlleitschuh.gradle.ktlint")173apply(plugin = "org.jlleitschuh.gradle.ktlint-idea")174tasks.getByName<JacocoReport>("jacocoTestReport") {175 classDirectories.setFrom(176 files(177 classDirectories.files.map {178 fileTree(it) {179 exclude(180 "**/TemplateApplication.class",181 "**/TemplateApplicationKt.class",182 "**/Database.class",183 "**/DatabaseKt.class",184 "**/DatabaseConfig.class",185 "**/DatabaseConfigKt.class",186 "**/KafkaConsumerConfig.class",187 "**/KafkaConsumerConfigKt.class"188 )189 }190 }191 )192 )193 reports {194 html.outputLocation.set(File("$buildDir/jacocoHtml"))195 html.required.set(true)196 xml.required.set(true)197 csv.required.set(true)198 }199}200tasks.withType<BootBuildImage> {201 builder = "paketobuildpacks/builder:base"202}203jacoco {204 toolVersion = "0.8.7"205}206sonarqube.properties {207 property("sonar.projectKey", sonarquebeKey)208 property("sonar.organization", "contaquanto")209 property("sonar.host.url", "https://sonarcloud.io")210}...

Full Screen

Full Screen

CoroutineLoggingInterceptorTest.kt

Source:CoroutineLoggingInterceptorTest.kt Github

copy

Full Screen

...17import kotlin.coroutines.coroutineContext18@ExperimentalKotest19class DatabaseLogExtension : LogExtension {20 val database = mutableListOf<String>()21 override suspend fun handleLogs(testCase: TestCase, logs: List<LogEntry>) {22 database.addAll(logs.map { it.message.toString() })23 }24}25@ExperimentalKotest26object FailingLogExtension : LogExtension {27 var invoked = false28 override suspend fun handleLogs(testCase: TestCase, logs: List<LogEntry>) {29 invoked = true30 throw CannotLogException("danger zone")31 }32}33@ExperimentalKotest34class TestWithFailingLog : FunSpec() {35 init {36 register(FailingLogExtension)37 beforeTest {38 FailingLogExtension.invoked shouldBe false39 coroutineContext.configuration.logLevel = LogLevel.Debug40 }41 test("should suppress exceptions thrown by log extensions") {42 debug { "wobble" }43 }44 afterTest { FailingLogExtension.invoked shouldBe true }45 }46}47@ExperimentalKotest48class ShouldLogWithTestAndProjectLevelExtensions : FunSpec() {49 init {50 val db1 = DatabaseLogExtension()51 val db2 = DatabaseLogExtension()52 register(db1)53 beforeTest {54 coroutineContext.configuration.logLevel = LogLevel.Debug55 coroutineContext.configuration.registry.add(db2)56 }57 test("should log to project and test extensions") {58 debug { "wobble" }59 }60 afterTest {61 db1.database.shouldContain("wobble")62 db2.database.shouldContain("wobble")63 }64 }65}66@ExperimentalKotest67class TestIgnoreWhenLoggingOff : FunSpec() {68 init {69 val database = DatabaseLogExtension()70 register(database)71 beforeTest {72 coroutineContext.configuration.logLevel = LogLevel.Off73 }74 test("ignores all logs when logging is OFF by config") {75 info { "info" }76 warn { "warn" }77 error { "error" }78 debug { "debug" }79 }80 afterTest {81 database.database.shouldBeEmpty()82 }83 }84}85@ExperimentalKotest86class TestErrorLogLevel : FunSpec() {87 init {88 val database = DatabaseLogExtension()89 register(database)90 beforeTest {91 coroutineContext.configuration.logLevel = LogLevel.Error92 }93 test("ignores logs lower priority than ERROR by config") {94 info { "info" }95 warn { "warn" }96 error { "error" }97 debug { "debug" }98 trace { "trace" }99 }100 afterTest {101 database.database.shouldBe(listOf("error"))102 }103 }104}105@ExperimentalKotest106class TestDebugLogLevel : FunSpec() {107 init {108 val database = DatabaseLogExtension()109 register(database)110 beforeTest {111 coroutineContext.configuration.logLevel = LogLevel.Debug112 }113 test("ignores logs lower priority than DEBUG by config") {114 info { "info" }115 warn { "warn" }116 error { "error" }117 debug { "debug" }118 trace { "trace" }119 }120 afterTest {121 database.database.shouldBe(listOf("info", "warn", "error", "debug"))122 }123 }124}125@ExperimentalKotest126class TestTraceLogLevel : FunSpec() {127 init {128 val database = DatabaseLogExtension()129 register(database)130 beforeTest {131 coroutineContext.configuration.logLevel = LogLevel.Trace132 }133 test("ignores logs lower priority than TRACE by config") {134 info { "info" }135 warn { "warn" }136 error { "error" }137 debug { "debug" }138 trace { "trace" }139 }140 afterTest {141 database.database.shouldBe(listOf("info", "warn", "error", "debug", "trace"))142 }143 }144}145@ExperimentalKotest146class TestInfoLogLevel : FunSpec() {147 init {148 val database = DatabaseLogExtension()149 register(database)150 beforeTest {151 coroutineContext.configuration.logLevel = LogLevel.Info152 }153 test("ignores logs lower priority than INFO by config") {154 info { "info" }155 warn { "warn" }156 error { "error" }157 debug { "debug" }158 trace { "trace" }159 }160 afterTest {161 database.database.shouldBe(listOf("info", "warn", "error"))162 }163 }164}165@ExperimentalKotest166class TestWarnLogLevel : FunSpec() {167 init {168 val database = DatabaseLogExtension()169 register(database)170 beforeTest {171 coroutineContext.configuration.logLevel = LogLevel.Warn172 }173 test("ignores logs lower priority than INFO by config") {174 info { "info" }175 warn { "warn" }176 error { "error" }177 debug { "debug" }178 trace { "trace" }179 }180 afterTest {181 database.database.shouldBe(listOf("warn", "error"))182 }183 }184}185private class CannotLogException(override val message: String) : Exception()...

Full Screen

Full Screen

SuspektLoggingTest.kt

Source:SuspektLoggingTest.kt Github

copy

Full Screen

...43 HttpStatusCode.Forbidden,44 ) { statusCode ->45 context("when a $statusCode is returned") {46 whenResponseStatus(statusCode)47 it("logs $statusCode as sus") {48 verify {49 spiedOnLogger.error(50 withArg { it shouldContain "suspekt oppførsel" },51 statusCode,52 any(),53 )54 }55 }56 it("increments gauge value") {57 val suspektGauge = meterRegistry.get("suspekt.antall").gauge()58 suspektGauge.value() shouldBe 159 }60 }61 }...

Full Screen

Full Screen

CoroutineLoggingInterceptor.kt

Source:CoroutineLoggingInterceptor.kt Github

copy

Full Screen

...31 test(testCase, scope.withCoroutineContext(coroutineContext))32 }.apply {33 extensions.map { SerialLogExtension(it) }.forEach { extension ->34 runCatching {35 extension.handleLogs(testCase, logger.logs.filter { it.level >= configuration.logLevel })36 }37 }38 }39 }40 }41 }42}...

Full Screen

Full Screen

ProjectConfig.kt

Source:ProjectConfig.kt Github

copy

Full Screen

...10object ProjectConfig : AbstractProjectConfig() {11 override val logLevel: LogLevel = LogLevel.Debug12 override fun extensions(): List<Extension> = listOf(13 object : LogExtension {14 override suspend fun handleLogs(testCase: TestCase, logs: List<LogEntry>) {15 logs.forEach { println(it.level.name + " - " + it.message) }16 }17 }18 )19}...

Full Screen

Full Screen

SerialLogExtension.kt

Source:SerialLogExtension.kt Github

copy

Full Screen

...9 */10@ExperimentalKotest11internal class SerialLogExtension constructor(private val logExtension: LogExtension) {12 private val mutex = Mutex()13 suspend fun handleLogs(testCase: TestCase, logs: List<LogEntry>) = mutex.withLock {14 runCatching {15 logExtension.handleLogs(testCase, logs)16 }17 }18}...

Full Screen

Full Screen

LogExtension.kt

Source:LogExtension.kt Github

copy

Full Screen

...5/**6 * An extension that is invoked when a test completes, logging any values that were logged using7 * by way of [trace], [debug], [info], [warn], and [error] during that test.8 *9 * Users can use testId on [TestCase.descriptor] to cross-reference the [TestResult] with the provided logs.10 */11@ExperimentalKotest12interface LogExtension : Extension {13 suspend fun handleLogs(testCase: TestCase, logs: List<LogEntry>)14}...

Full Screen

Full Screen

logger.kt

Source:logger.kt Github

copy

Full Screen

...4typealias LogFn = () -> Any5data class LogEntry(val level: LogLevel, val message: Any)6@ExperimentalKotest7class TestLogger(private val logLevel: LogLevel) {8 internal val logs = mutableListOf<LogEntry>()9 internal fun maybeLog(message: LogFn, level: LogLevel) {10 if (level >= logLevel) {11 logs.add(LogEntry(level, message()))12 }13 }14}...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful