Best Kotest code snippet using io.kotest.matchers.file.content.test
HttpApiTest.kt
Source:HttpApiTest.kt
...15 *16 */17package org.jitsi.jibri.api.http18import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper19import io.kotest.core.spec.IsolationMode20import io.kotest.core.spec.style.ShouldSpec21import io.kotest.core.spec.style.scopes.ShouldSpecContextScope22import io.kotest.core.test.TestContext23import io.kotest.core.test.createTestName24import io.kotest.matchers.shouldBe25import io.kotest.matchers.string.shouldContain26import io.kotest.matchers.string.shouldNotContain27import io.ktor.http.ContentType28import io.ktor.http.HttpHeaders29import io.ktor.http.HttpMethod30import io.ktor.http.HttpStatusCode31import io.ktor.server.testing.TestApplicationEngine32import io.ktor.server.testing.handleRequest33import io.ktor.server.testing.setBody34import io.mockk.Runs35import io.mockk.every36import io.mockk.just37import io.mockk.mockk38import io.mockk.slot39import io.mockk.verify40import kotlinx.coroutines.runBlocking41import org.jitsi.jibri.CallUrlInfo42import org.jitsi.jibri.JibriManager43import org.jitsi.jibri.RecordingSinkType44import org.jitsi.jibri.config.XmppCredentials45import org.jitsi.jibri.health.EnvironmentContext46import org.jitsi.jibri.health.JibriHealth47import org.jitsi.jibri.selenium.CallParams48import org.jitsi.jibri.service.ServiceParams49import org.jitsi.jibri.status.ComponentBusyStatus50import org.jitsi.jibri.status.ComponentHealthStatus51import org.jitsi.jibri.status.JibriStatus52import org.jitsi.jibri.status.JibriStatusManager53import org.jitsi.jibri.status.OverallHealth54import org.jitsi.jibri.webhooks.v1.WebhookClient55class HttpApiTest : ShouldSpec() {56 override fun isolationMode(): IsolationMode = IsolationMode.InstancePerLeaf57 private val jibriManager: JibriManager = mockk()58 private val jibriStatusManager: JibriStatusManager = mockk()59 private val webhookClient: WebhookClient = mockk()60 private val api = HttpApi(jibriManager, jibriStatusManager, webhookClient)61 init {62 context("health") {63 context("when jibri isn't busy") {64 val expectedStatus =65 JibriStatus(ComponentBusyStatus.IDLE, OverallHealth(ComponentHealthStatus.HEALTHY, mapOf()))66 val expectedHealth = JibriHealth(expectedStatus)67 every { jibriManager.currentEnvironmentContext } returns null68 every { jibriStatusManager.overallStatus } returns expectedStatus69 apiTest {70 with(handleRequest(HttpMethod.Get, "/jibri/api/v1.0/health")) {71 shouldb("call JibriStatusManager#overallStatus") {72 verify { jibriStatusManager.overallStatus }73 }74 shouldb("call JibriManager#currentEnvironmentContext") {75 verify { jibriManager.currentEnvironmentContext }76 }77 shouldb("return a status of 200") {78 response.status() shouldBe HttpStatusCode.OK79 }80 shouldb("return the right json body") {81 // The json should not include the 'environmentContext' field at all, since it82 // will be null83 response.content shouldNotContain "environmentContext"84 val health = jacksonObjectMapper().readValue(response.content, JibriHealth::class.java)85 health shouldBe expectedHealth86 }87 }88 }89 }90 context("when jibri is busy and has an environmentContext") {91 val expectedStatus =92 JibriStatus(ComponentBusyStatus.BUSY, OverallHealth(ComponentHealthStatus.HEALTHY, mapOf()))93 val expectedEnvironmentContext = EnvironmentContext("meet.jit.si")94 val expectedHealth = JibriHealth(expectedStatus, expectedEnvironmentContext)95 every { jibriManager.currentEnvironmentContext } returns expectedEnvironmentContext96 every { jibriStatusManager.overallStatus } returns expectedStatus97 apiTest {98 with(handleRequest(HttpMethod.Get, "/jibri/api/v1.0/health")) {99 shouldb("return a status of 200") {100 response.status() shouldBe HttpStatusCode.OK101 }102 shouldb("return the right json body") {103 response.content shouldContain "environmentContext"104 val health = jacksonObjectMapper().readValue(response.content, JibriHealth::class.java)105 health shouldBe expectedHealth106 }107 }108 }109 }110 }111 context("startService") {112 context("start file recording") {113 val capturedServiceParams = slot<ServiceParams>()114 every {115 jibriManager.startFileRecording(116 capture(capturedServiceParams),117 any(),118 any(),119 any()120 )121 } just Runs122 val startServiceRequest = StartServiceParams(123 sessionId = "session_id",124 callParams = CallParams(125 callUrlInfo = CallUrlInfo("https://meet.jit.si", "callName")126 ),127 callLoginParams = XmppCredentials(128 domain = "xmpp_domain",129 username = "xmpp_username",130 password = "xmpp_password"131 ),132 sinkType = RecordingSinkType.FILE133 )134 val json = jacksonObjectMapper().writeValueAsString(startServiceRequest)135 apiTest {136 handleRequest(HttpMethod.Post, "/jibri/api/v1.0/startService") {137 addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())138 setBody(json)139 }.apply {140 shouldb("call JibriManager#startFileRecording with the right params") {141 capturedServiceParams.captured.usageTimeoutMinutes shouldBe 0142 }143 }144 }145 }146 }147 }148 private fun <R> apiTest(block: TestApplicationEngine.() -> R) {149 with(api) {150 io.ktor.server.testing.withTestApplication({151 apiModule()152 }) {153 block()154 }155 }156 }157}158/**159 * A non-suspend version of `should` so that it can be called from within the KTOR test harness160 * scope161 */162fun ShouldSpecContextScope.shouldb(name: String, test: suspend TestContext.() -> Unit) =163 runBlocking { addTest(createTestName("should ", name, true), xdisabled = false, test = test) }...
WebhookClientTest.kt
Source:WebhookClientTest.kt
...14 * limitations under the License.15 */16package org.jitsi.jibri.webhooks.v117import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper18import io.kotest.core.spec.IsolationMode19import io.kotest.core.spec.style.ShouldSpec20import io.kotest.matchers.collections.shouldHaveSize21import io.kotest.matchers.should22import io.kotest.matchers.shouldBe23import io.kotest.matchers.shouldNotBe24import io.kotest.matchers.string.shouldContain25import io.kotest.matchers.types.beInstanceOf26import io.ktor.client.HttpClient27import io.ktor.client.engine.mock.MockEngine28import io.ktor.client.engine.mock.MockEngineConfig29import io.ktor.client.engine.mock.MockRequestHandler30import io.ktor.client.engine.mock.respondError31import io.ktor.client.engine.mock.respondOk32import io.ktor.client.request.HttpRequestData33import io.ktor.content.TextContent34import io.ktor.http.ContentType35import io.ktor.http.HttpMethod36import io.ktor.http.HttpStatusCode37import io.mockk.every38import io.mockk.slot39import io.mockk.spyk40import kotlinx.coroutines.delay41import org.jitsi.jibri.status.ComponentBusyStatus42import org.jitsi.jibri.status.ComponentHealthStatus43import org.jitsi.jibri.status.JibriStatus44import org.jitsi.jibri.status.OverallHealth45import org.jitsi.jibri.util.TaskPools46import org.jitsi.test.concurrent.FakeExecutorService47class WebhookClientTest : ShouldSpec({48 isolationMode = IsolationMode.InstancePerLeaf49 val requests = mutableListOf<HttpRequestData>()50 val goodStatus = JibriStatus(51 ComponentBusyStatus.IDLE,52 OverallHealth(53 ComponentHealthStatus.HEALTHY,54 mapOf()55 )56 )57 val badStatus = JibriStatus(58 ComponentBusyStatus.IDLE,59 OverallHealth(60 ComponentHealthStatus.UNHEALTHY,61 mapOf()62 )63 )64 val client = WebhookClient(65 "test",66 client = HttpClient(MockEngine) {67 engine {68 addHandler { request ->69 requests += request70 with(request.url.toString()) {71 when {72 contains("success") -> {73 respondOk()74 }75 contains("delay") -> {76 delay(1000)77 respondOk()78 }79 contains("error") -> {80 respondError(HttpStatusCode.BadRequest)81 }82 else -> error("Unsupported URL")83 }84 }85 }86 }87 }88 )89 // Coroutines will sometimes try to execute a launch in the calling thread, so the normal FakeExecutorService90 // doesn't work as it relies on the calling code finishing and then the test code being able to call runOne91 // or runAll, etc. This overrides the execute method (which is what gets used by coroutine dispatchers) and92 // executes the Runnable immediately.93 val ioExecutor: FakeExecutorService = spyk {94 val runnable = slot<Runnable>()95 every { execute(capture(runnable)) } answers {96 runnable.captured.run()97 }98 }99 beforeSpec {100 TaskPools.ioPool = ioExecutor101 }102 afterSpec {103 TaskPools.Companion.ioPool = TaskPools.DefaultIoPool104 }105 context("when the client") {106 context("has a valid subscriber") {107 client.addSubscriber("success")108 context("calling updateStatus") {109 client.updateStatus(goodStatus)110 should("send a POST to the subscriber at the proper url") {111 requests shouldHaveSize 1112 with(requests[0]) {113 url.toString() shouldContain "/v1/status"114 method shouldBe HttpMethod.Post115 }116 }117 should("send the correct data") {118 requests[0].body.contentType shouldBe ContentType.Application.Json119 with(requests[0].body) {120 this should beInstanceOf<TextContent>()121 this as TextContent122 this.text shouldBe jacksonObjectMapper().writeValueAsString(123 JibriEvent.HealthEvent("test", goodStatus)124 )125 text shouldContain """126 "jibriId":"test"127 """.trimIndent()128 }129 }130 context("and calling updateStatus again") {131 client.updateStatus(badStatus)132 should("send another request with the new status") {133 requests shouldHaveSize 2134 with(requests[1].body) {135 this should beInstanceOf<TextContent>()136 this as TextContent137 this.text shouldContain jacksonObjectMapper().writeValueAsString(138 JibriEvent.HealthEvent("test", badStatus)139 )140 }141 }142 }143 }144 }145 context("has multiple subscribers") {146 client.addSubscriber("https://success")147 client.addSubscriber("https://delay")148 client.addSubscriber("https://error")149 context("calling updateStatus") {150 client.updateStatus(goodStatus)151 should("send a POST to the subscribers at the proper url") {152 requests shouldHaveSize 3...
S3FileLineRewriterTest.kt
Source:S3FileLineRewriterTest.kt
...21import com.amazonaws.services.s3.model.ObjectTagging22import com.amazonaws.services.s3.model.S3Object23import com.amazonaws.services.s3.model.SetObjectTaggingRequest24import com.amazonaws.services.s3.model.Tag25import io.kotest.assertions.throwables.shouldThrow26import io.kotest.core.spec.style.FunSpec27import io.kotest.matchers.collections.shouldContainAll28import io.kotest.matchers.shouldBe29import io.kotest.matchers.throwable.shouldHaveMessage30@ExperimentalStdlibApi31class S3FileLineRewriterTest : FunSpec() {32 private val s3Client by lazy { s3Listener.client("bucket") }33 init {34 test("Rewriting a single line with intended modification") {35 createFile("abc\nXXX\n123")36 rewriteLines { seq -> 37 seq.map { it.replace("XXX", "YYY") }38 }39 getFile().contentString shouldBe "abc\nYYY\n123"40 }41 42 test("Rewriting multiple lines with intended modification") {43 createFile("abc\nXXX\nXXX\n123")44 45 rewriteLines { seq ->46 seq.map { it.replace("XXX", "YYY") }47 }48 49 getFile().contentString shouldBe "abc\nYYY\nYYY\n123"50 }51 52 test("Rewriting should preserve metadata") {53 createFile("A", ObjectMetadata().also { it.addUserMetadata("a", "b") })54 rewriteLines { it }55 56 getFile().objectMetadata.getUserMetaDataOf("a") shouldBe "b"57 }58 59 test("Rewriting should preserve tags") {60 createFile("A", ObjectMetadata(), listOf(Tag("a", "b"), Tag("C", "D")))61 rewriteLines { it }62 63 getFileTags().shouldContainAll(Tag("a", "b"), Tag("C", "D"))64 }65 66 test("Rewriting should remove a line if it's empty") {67 createFile("A\nB\nC")68 rewriteLines { seq ->69 seq.map { it.replace("B", "") } 70 }71 72 getFile().contentString shouldBe "A\nC"73 }74 75 test("Should run (and do nothing) in an empty file") {76 createFile("")77 78 rewriteLines { seq -> 79 seq.map { it.replace("Foo", "BAR") } 80 }81 82 getFile().contentString shouldBe ""83 }84 85 test("Should allow rewriting of more than one file") {86 // Need >= 1000 objects to ensure we make enough requests for all of them87 repeat(501) { 88 createFile("A\nB\nC", key="$it", directory = "dir/subdir/")89 createFile("A\nB\nC", key = "$it", directory = "dir/subdir/otherdir/")90 }91 92 rewriteAll("dir/subdir/") { seq ->93 seq.map { it.replace("B", "") }94 }95 96 repeat(501) { 97 getFile("dir/subdir/$it").contentString shouldBe "A\nC"98 getFile("dir/subdir/otherdir/$it").contentString shouldBe "A\nC"99 }100 }101 102 test("Should throw an error when trying to rewrite with empty parameters") {103 val rewriter = S3FileLineRewriter(s3Client)104 105 shouldThrow<IllegalArgumentException> { 106 rewriter.rewriteAll("", "nonEmpty") { it }107 }.shouldHaveMessage("Bucket must be non-empty string, but was.")108 109 shouldThrow<IllegalArgumentException> { 110 rewriter.rewriteAll("nonEmpty", "") { it }111 }.shouldHaveMessage("Prefix must be non-empty string, but was.")112 113 shouldThrow<IllegalArgumentException> { 114 rewriter.rewriteFile("", "nonEmpty") { it } 115 }.shouldHaveMessage("Bucket must be non-empty string, but was.")116 117 shouldThrow<IllegalArgumentException> { 118 rewriter.rewriteFile("nonEmpty", "") { it } 119 }.shouldHaveMessage("Key must be non-empty string, but was.")120 }121 test("Should allow rewriting line sequences") {122 createFile("abc\nXXX\nXXX\n123")123 rewriteLines { seq: Sequence<String> ->124 seq.map { it.replace("XXX", "YYY") }125 }126 getFile().contentString shouldBe "abc\nYYY\nYYY\n123"127 }128 }129 130 private val S3Object.contentString get() = objectContent.readBytes().decodeToString()131 @JvmName("rewriteLinesSequence") 132 private fun rewriteLines(change: (Sequence<String>) -> Sequence<String>) =133 S3FileLineRewriter(s3Client).rewriteFile("bucket", "key", change)134 135 private fun rewriteAll(directory: String, change: (Sequence<String>) -> Sequence<String>) =...
S3StorageServiceSpec.kt
Source:S3StorageServiceSpec.kt
1package network.as2.persistence.s32import com.amazonaws.services.s3.AmazonS33import com.fasterxml.jackson.databind.ObjectMapper4import com.freighttrust.testing.generators.textDataHandlerGenerator5import com.freighttrust.testing.listeners.FlywayTestListener6import com.freighttrust.testing.listeners.PostgresTestListener7import com.freighttrust.testing.listeners.S3TestListener8import com.github.javafaker.Faker9import io.kotest.core.listeners.TestListener10import io.kotest.core.spec.Spec11import io.kotest.core.spec.style.BehaviorSpec12import io.kotest.koin.KoinLifecycleMode13import io.kotest.koin.KoinListener14import io.kotest.matchers.shouldBe15import io.kotest.matchers.shouldNotBe16import io.kotest.property.RandomSource17import kotlinx.coroutines.Dispatchers18import kotlinx.coroutines.withContext19import network.as2.common.AppConfigModule20import network.as2.jooq.enums.FileProvider21import network.as2.persistence.extensions.metadataForS322import network.as2.persistence.postgres.PostgresPersistenceModule23import network.as2.serialisation.JsonModule24import org.koin.core.context.stopKoin25import org.koin.test.KoinTest26import org.koin.test.inject27import kotlin.random.asJavaRandom28@Suppress("BlockingMethodInNonBlockingContext")29class S3StorageServiceSpec : BehaviorSpec(), KoinTest {30 private val bucket = "s3-file-service-spec"31 override fun listeners(): List<TestListener> =32 listOf(33 listOf(34 S3TestListener(bucket)35 .apply { listener(this) }36 ),37 PostgresTestListener()38 .let { postgresListener ->39 listOf(40 postgresListener,...
LocalStorageServiceSpec.kt
Source:LocalStorageServiceSpec.kt
1package network.as2.persistence.local2import com.fasterxml.jackson.databind.ObjectMapper3import com.freighttrust.testing.generators.textDataHandlerGenerator4import com.freighttrust.testing.listeners.FlywayTestListener5import com.freighttrust.testing.listeners.PostgresTestListener6import com.github.javafaker.Faker7import io.kotest.core.listeners.TestListener8import io.kotest.core.spec.Spec9import io.kotest.core.spec.style.BehaviorSpec10import io.kotest.koin.KoinLifecycleMode11import io.kotest.koin.KoinListener12import io.kotest.matchers.shouldBe13import io.kotest.matchers.shouldNotBe14import io.kotest.property.RandomSource15import kotlinx.coroutines.Dispatchers16import kotlinx.coroutines.withContext17import network.as2.common.AppConfigModule18import network.as2.jooq.enums.FileProvider19import network.as2.persistence.extensions.metadataForLocal20import network.as2.persistence.postgres.PostgresPersistenceModule21import network.as2.serialisation.JsonModule22import org.koin.core.context.stopKoin23import org.koin.test.KoinTest24import org.koin.test.inject25import java.io.BufferedInputStream26import java.io.FileInputStream27import kotlin.random.asJavaRandom28@Suppress("BlockingMethodInNonBlockingContext")29class LocalStorageServiceSpec : BehaviorSpec(), KoinTest {30 override fun listeners(): List<TestListener> =31 listOf(32 PostgresTestListener()33 .let { postgresListener ->34 listOf(35 postgresListener,36 FlywayTestListener(postgresListener.container)37 )38 },...
BagRegulationCheckerTest.kt
Source:BagRegulationCheckerTest.kt
1package me.advent.of.code.problems.day72import io.kotest.matchers.collections.shouldBeEmpty3import io.kotest.matchers.collections.shouldContainExactly4import io.kotest.matchers.collections.shouldHaveSize5import io.kotest.matchers.nulls.shouldNotBeNull6import io.kotest.matchers.shouldBe7import me.advent.of.code.reader.readFile8import org.junit.jupiter.api.Test9internal class BagRegulationCheckerTest {10 private val initialInput = readFile("src/test/resources/inputs/day7/input_AoC.txt")11 private var sut = BagRegulationChecker(initialInput)12 @Test13 internal fun `Should split string correctly`() {14 val regulation = "light red bags contain 1 bright white bag, 2 muted yellow bags."15 val extractedRegulation: BagRegulation = sut.extractRegulationFromText(regulation)16 extractedRegulation.bag.colorCode shouldBe "light red"17 val acceptedContent = extractedRegulation.contentRegulation18 acceptedContent shouldHaveSize 219 acceptedContent[0].quantity shouldBe 120 acceptedContent[0].bag shouldBe Bag("bright white", 0)21 acceptedContent[1].quantity shouldBe 222 acceptedContent[1].bag shouldBe Bag("muted yellow", 0)23 }24 @Test...
PublishToMavenCentralTest.kt
Source:PublishToMavenCentralTest.kt
1package it.nicolasfarabegoli.gradle.central2import io.kotest.core.spec.style.WordSpec3import io.kotest.matchers.file.shouldBeAFile4import io.kotest.matchers.file.shouldExist5import io.kotest.matchers.shouldBe6import io.kotest.matchers.string.shouldContain7import org.gradle.testkit.runner.GradleRunner8import org.gradle.testkit.runner.TaskOutcome9import java.io.File10class PublishToMavenCentralTest : WordSpec({11 val projectDir = File("build/gradleTest")12 fun setupTest() {13 projectDir.mkdirs()14 projectDir.resolve("settings.gradle.kts").writeText("")15 projectDir.resolve("build.gradle.kts").writeText(16 """17 plugins {18 `java-library`19 `java-gradle-plugin`20 id("it.nicolasfarabegoli.publish-to-maven-central")21 }22 ...
FileWriterTest.kt
Source:FileWriterTest.kt
1package br.com.colman.petals.use.io2import androidx.test.platform.app.InstrumentationRegistry3import io.kotest.matchers.file.shouldExist4import io.kotest.matchers.file.shouldNotExist5import io.kotest.matchers.shouldBe6import io.kotest.matchers.string.shouldEndWith7import org.junit.Before8import org.junit.Test9import java.io.File10class FileWriterTest {11 val context = InstrumentationRegistry.getInstrumentation().targetContext12 val exportsDirectory = File(context.filesDir, "exports")13 val target = FileWriter(context)14 @Before15 fun deleteExportsDirectory() {16 exportsDirectory.deleteRecursively()17 }18 @Test19 fun createsExportsDirectory() {20 exportsDirectory.shouldNotExist()...
test
Using AI Code Generation
1fun test ( name : String , test : suspend TestContext . () -> Unit ) : Unit2fun test ( name : String , test : suspend TestContext . () -> Unit , config : TestCaseConfig ) : Unit3fun test ( name : String , test : suspend TestContext . () -> Unit , tags : Set < Tag > ) : Unit4fun test ( name : String , test : suspend TestContext . () -> Unit , tags : Set < Tag > , config : TestCaseConfig ) : Unit5fun test ( name : String , test : suspend TestContext . () -> Unit , vararg tags : Tag ) : Unit6fun test ( name : String , test : suspend TestContext . () -> Unit , vararg tags : String ) : Unit7fun test ( name : String , test : suspend TestContext . () -> Unit , tags
test
Using AI Code Generation
1test("file should have content") {2val file = File("test.txt")3file.writeText("Hello World")4file should haveContent("Hello World")5}6})7test("file should not have content") {8val file = File("test.txt")9file.writeText("Hello World")10file shouldNot haveContent("Hello")11}12})13test("file should have content ignoring case") {14val file = File("test.txt")15file.writeText("Hello World")16file should haveContentIgnoringCase("HELLO WORLD")17}18})19test("file should not have content ignoring case") {20val file = File("test.txt")21file.writeText("Hello World")22file shouldNot haveContentIgnoringCase("HELLO WORLD")23}24})
test
Using AI Code Generation
1test("test file exist") { val file = File( "src/test/resources/test.txt" ) file should exist } Enter fullscreen mode Exit fullscreen mode2test("test file does not exist") { val file = File( "src/test/resources/test.txt" ) file shouldNot exist } Enter fullscreen mode Exit fullscreen mode3test("test file is empty") { val file = File( "src/test/resources/test.txt" ) file should beEmpty } Enter fullscreen mode Exit fullscreen mode4test("test file is not empty") { val file = File( "src/test/resources/test.txt" ) file shouldNot beEmpty } Enter fullscreen mode Exit fullscreen mode5test("test file has the given extension") { val file = File( "src/test/resources/test.txt" ) file should haveExtension( "txt" ) } Enter fullscreen mode Exit fullscreen mode6test("test file does not have the given extension") { val file = File( "src/test/resources/test.txt" ) file shouldNot haveExtension( "txt" ) } Enter fullscreen mode Exit fullscreen mode7test("test file has the given name") { val file =
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!!