Best Kotest code snippet using io.kotest.matchers.string.matchers.include
TestSchedule.kt
Source: TestSchedule.kt
1import com.fasterxml.jackson.annotation.JsonInclude2import com.fasterxml.jackson.databind.ObjectMapper3import edu.illinois.cs.cs125.cisapi.Course4import edu.illinois.cs.cs125.cisapi.CourseSummary5import edu.illinois.cs.cs125.cisapi.Schedule6import edu.illinois.cs.cs125.cisapi.ScheduleYear7import edu.illinois.cs.cs125.cisapi.ScheduleYearSemester8import edu.illinois.cs.cs125.cisapi.ScheduleYearSemesterDepartment9import edu.illinois.cs.cs125.cisapi.Section10import edu.illinois.cs.cs125.cisapi.fromXml11import io.kotest.core.spec.style.StringSpec12import io.kotest.matchers.collections.shouldContainInOrder13import io.kotest.matchers.collections.shouldHaveAtLeastSize14import io.kotest.matchers.collections.shouldHaveSize15import io.kotest.matchers.ints.shouldBeGreaterThan16import io.kotest.matchers.shouldBe17import io.kotest.matchers.shouldNotBe18import io.kotest.matchers.string.shouldEndWith19import io.kotest.matchers.string.shouldStartWith20import java.io.File21private fun String.load() = TestSchedule::class.java.getResource("/$this").readText()22@Suppress("BlockingMethodInNonBlockingContext")23class TestSchedule : StringSpec({24 "should load local schedule.xml properly" {25 "schedule.xml".load().fromXml<Schedule>().also { schedule ->26 schedule.calendarYears shouldHaveSize 1727 schedule.calendarYears.map { year -> year.id }.sorted() shouldContainInOrder (2004..2020).toList()28 schedule.calendarYears.forEach {29 it.href.toString() shouldEndWith "${it.year}.xml"30 }31 }32 }33 "should load remote schedule.xml properly" {34 Schedule.fetch().also { schedule ->35 schedule.calendarYears shouldHaveSize 1836 schedule.calendarYears.map { year -> year.id }.sorted() shouldContainInOrder (2004..2020).toList()37 schedule.calendarYears.forEach {38 it.href.toString() shouldEndWith "${it.year}.xml"39 }40 }41 }42 "should load local 2020.xml properly" {43 "schedule_2020.xml".load().fromXml<ScheduleYear>().also { year ->44 year.terms shouldHaveSize 445 year.terms.forEach {46 it.id shouldStartWith "12020"47 }48 }49 }50 "should load remote 2020.xml properly" {51 ScheduleYear.fetch("2020").also { year ->52 year.terms shouldHaveSize 453 year.terms.forEach {54 it.id shouldStartWith "12020"55 }56 }57 }58 "should load local 2020/fall.xml properly" {59 "schedule_2020_fall.xml".load().fromXml<ScheduleYearSemester>().also { semester ->60 semester.subjects.size shouldBeGreaterThan 061 semester.subjects.find { it.id == "CS" }?.department shouldBe "Computer Science"62 semester.parents.calendarYear.year shouldBe 202063 }64 }65 "should load remote 2020/fall.xml properly" {66 ScheduleYearSemester.fetch("2020", "fall").also { semester ->67 semester.subjects.size shouldBeGreaterThan 068 semester.subjects.find { it.id == "CS" }?.department shouldBe "Computer Science"69 semester.parents.calendarYear.year shouldBe 202070 }71 }72 "should load local 2020/fall/CS.xml properly" {73 "schedule_2020_fall_CS.xml".load().fromXml<ScheduleYearSemesterDepartment>().also { department ->74 department.contactName shouldBe "Nancy Amato"75 department.courses.find { it.id == "125" }?.name shouldBe "Intro to Computer Science"76 department.parents.calendarYear.year shouldBe 202077 department.parents.term.semester shouldBe "Fall 2020"78 }79 }80 "should load remote 2020/fall/CS.xml properly" {81 ScheduleYearSemesterDepartment.fetch("2020", "fall", "CS").also { department ->82 department.contactName shouldBe "Nancy Amato"83 department.courses.find { it.id == "125" }?.name shouldBe "Intro to Computer Science"84 department.parents.calendarYear.year shouldBe 202085 department.parents.term.semester shouldBe "Fall 2020"86 }87 }88 "should load local 2020/fall/CS/100.xml properly" {89 "schedule_2020_fall_CS_100.xml".load().fromXml<Course>().also { course ->90 course.label shouldBe "Freshman Orientation"91 course.href shouldNotBe null92 course.description shouldStartWith "Introduction to Computer Science as a field and career"93 course.creditHours shouldBe "1 hours."94 }95 }96 "should load remote 2020/fall/CS/100.xml properly" {97 Course.fetch("2020", "fall", "CS", "100").also { course ->98 course.label shouldBe "Freshman Orientation"99 course.description shouldStartWith "Introduction to Computer Science as a field and career"100 course.creditHours shouldBe "1 hours."101 }102 }103 "should load local 2020/fall/CS/100/30094.xml properly" {104 "schedule_2020_fall_CS_100_30094.xml".load().fromXml<Section>().also { section ->105 section shouldNotBe null106 }107 }108 "should load remote 2020/fall/CS/100/30094.xml properly" {109 Section.fetch("2020", "fall", "CS", "100", "30094").also { section ->110 section shouldNotBe null111 }112 }113 "!should fetch all departments" {114 ScheduleYearSemester.fetch("2020", "fall").departments().also { departments ->115 departments shouldHaveAtLeastSize 0116 }117 }118 "!should fetch all department courses" {119 ScheduleYearSemesterDepartment.fetch("2020", "fall", "CS").courses().also { courses ->120 courses shouldHaveAtLeastSize 0121 }122 }123 "!should fetch all course sections" {124 Course.fetch("2020", "fall", "CS", "125").sections().also { sections ->125 sections shouldHaveAtLeastSize 0126 }127 }128 "!should fetch all department courses and sections" {129 ScheduleYearSemesterDepartment.fetch("2020", "fall", "CS").courses()130 .flatMap { it.sections() }131 .also { sections ->132 sections shouldHaveAtLeastSize 0133 }134 }135 "!should fetch and save all courses" {136 val courses = ScheduleYearSemester.fetch("2019", "fall").departments().flatMap { it.courses() }137 val mapper = ObjectMapper().also {138 it.setSerializationInclusion(JsonInclude.Include.NON_NULL)139 }140 mapper.writerWithDefaultPrettyPrinter()141 .writeValue(File(TestSchedule::class.java.getResource("/").path + "courses.json"), courses)142 }143 "!should fetch and save all course summaries" {144 val year = "2020"145 val semester = "fall"146 val courses = ScheduleYearSemester.fetch("2020", "fall").departments()147 .flatMap { it.courses() }148 .map { CourseSummary(it) }149 val mapper = ObjectMapper().also {150 it.setSerializationInclusion(JsonInclude.Include.NON_NULL)151 }152 mapper.writerWithDefaultPrettyPrinter().writeValue(153 File(154 TestSchedule::class.java.getResource("/").path + "${year}_${semester}_summary.json"155 ), courses156 )157 }158 "f:should fetch and save all CS courses" {159 val year = "2020"160 val semester = "fall"161 val courses = ScheduleYearSemesterDepartment.fetch(year, semester, "CS").courses().shuffled()162 val mapper = ObjectMapper().also {163 it.setSerializationInclusion(JsonInclude.Include.NON_NULL)164 }165 mapper.writerWithDefaultPrettyPrinter().writeValue(166 File(TestSchedule::class.java.getResource("/").path + "${year}_${semester}_CS.json"), courses167 )168 }169 "f:should fetch and save all CS course summaries" {170 val year = "2020"171 val semester = "fall"172 val courses =173 ScheduleYearSemesterDepartment.fetch("2020", "fall", "CS").courses().shuffled().map { CourseSummary(it) }174 val mapper = ObjectMapper().also {175 it.setSerializationInclusion(JsonInclude.Include.NON_NULL)176 }177 mapper.writerWithDefaultPrettyPrinter().writeValue(178 File(179 TestSchedule::class.java.getResource("/").path + "${year}_${semester}_CS_summary.json"180 ), courses181 )182 }183 "!should fetch all courses and sections" {184 ScheduleYearSemester.fetch("2020", "fall").departments()185 .shuffled()186 .flatMap { it.courses() }187 .shuffled()188 .flatMap { it.sections() }189 .also { sections ->190 sections shouldHaveAtLeastSize 0191 }192 }193})...
ComputeInstanceSpec.kt
Source: ComputeInstanceSpec.kt
1package utils2import io.kotest.assertions.fail3import io.kotest.assertions.timing.eventually4import io.kotest.core.spec.style.WordSpec5import io.kotest.matchers.be6import io.kotest.matchers.collections.shouldExist7import io.kotest.matchers.or8import io.kotest.matchers.should9import io.kotest.matchers.shouldBe10import io.kotest.matchers.string.shouldEndWith11import io.kotest.matchers.string.shouldInclude12import io.kotest.matchers.string.shouldNotBeBlank13import kotlinx.coroutines.FlowPreview14import kotlinx.coroutines.async15import kotlinx.coroutines.runBlocking16import kotlinx.serialization.ExperimentalSerializationApi17import utils.Compute.Instance18import kotlin.time.ExperimentalTime19import kotlin.time.minutes20import kotlin.time.seconds21// todo: afterTest Instance.delete22@ExperimentalSerializationApi23@FlowPreview24@ExperimentalTime25class ComputeInstanceSpec : WordSpec({26 val projectId = System.getenv("PROJECT_ID") ?: fail("Must set PROJECT_ID env var")27 val regionId = System.getenv("REGION_ID") ?: fail("Must set REGION_ID env var")28 val dbPass = System.getenv("DB_PASS") ?: fail("Most set DB_PASS env var")29 val dbInstance = System.getenv("DB_INSTANCE") ?: fail("Most set DB_INSTANCE env var")30 val maybeServiceAccount = System.getenv("SERVICE_ACCOUNT")31 val accessToken = Auth.accessTokenFromGcloud(maybeServiceAccount)32 val name = Instance.randomName()33 val zone = "us-central1-a"34 val machineType = "e2-medium"35 val defaultImage = "docker.io/hello-world"36 val testImage = "gcr.io/$projectId/one-off-cloud-run-test"37 val instance1 = Instance(projectId, zone, machineType, defaultImage, name, null, emptyList(), emptyMap(), false)38 val instance2 = instance1.copy(39 name = ""40 )41 val instance3 = instance1.copy(42 name = Instance.randomName(),43 serviceAccountName = maybeServiceAccount44 )45 val instance4 = instance1.copy(46 name = Instance.randomName(),47 containerImage = testImage,48 containerEnvs = mapOf("NAME" to "world"),49 containerEntrypoint = "/bin/sh",50 containerArgs = listOf("-c", "echo \"hello, \$NAME\"")51 )52 val instance5 = instance1.copy(53 name = Instance.randomName(),54 shutdownOnComplete = true55 )56 val instance6 = instance1.copy(57 name = Instance.randomName(),58 containerImage = testImage,59 containerEntrypoint = "psql",60 containerEnvs = mapOf("PGPASSWORD" to dbPass),61 containerArgs = listOf("-h", "/cloudsql/$projectId:$regionId:$dbInstance", "-U", "postgres", "-c", "SELECT 1"),62 instanceConnectionName = "$projectId:$regionId:$dbInstance"63 )64 "instance name" should {65 "not start with a number" {66 instance1.copy(name = "0").validName shouldBe "x-0"67 }68 "not be empty" {69 instance1.copy(name = null).validName.shouldNotBeBlank()70 }71 "fix invalid names" {72 instance1.copy(name = "a/b").validName shouldBe "a-b"73 }74 }75 "an instance" should {76 "be creatable" {77 val operation = Instance.create(instance1, maybeServiceAccount)78 operation.getOrThrow() shouldEndWith "RUNNING"79 }80 "be creatable with an invalid name" {81 val operation = Instance.create(instance2, maybeServiceAccount)82 operation.getOrThrow() shouldEndWith "RUNNING"83 }84 "be describable" {85 val operation = Instance.describe(instance1, maybeServiceAccount)86 operation.getOrThrow().status shouldBe "RUNNING"87 }88 "fail when trying to describe an non-existent instance" {89 val operation = Instance.describe(instance1.copy(name = Instance.randomName()), maybeServiceAccount)90 operation.isFailure shouldBe true91 }92 "be updatable" {93 val operation = Instance.update(instance1, maybeServiceAccount)94 operation.getOrThrow() shouldEndWith "done."95 }96 "be startable" {97 val operation = Instance.start(instance1, maybeServiceAccount)98 operation.getOrThrow() shouldInclude "Updated"99 }100 "be creatable with a custom service account" {101 val operation = Instance.create(instance3, maybeServiceAccount)102 operation.getOrThrow() shouldEndWith "RUNNING"103 Instance.describe(instance3).getOrThrow().serviceAccounts.first().email shouldBe maybeServiceAccount104 }105 "be creatable with a custom entrypoint, args, and env vars" {106 val operation = Instance.create(instance4, maybeServiceAccount)107 operation.getOrThrow() shouldEndWith "RUNNING"108 eventually(2.minutes, 15.seconds) {109 Instance.logs(instance4, 500, accessToken, maybeServiceAccount).getOrThrow() shouldExist { it.jsonPayload?.message?.contains("hello, world") ?: false }110 }111 }112 "shutdown an instance after the docker process stops" {113 val createOperation = Instance.create(instance5, maybeServiceAccount)114 createOperation.getOrThrow() shouldEndWith "RUNNING"115 // wait for the shutdown script to run116 eventually(3.minutes, 15.seconds) {117 val operation = Instance.describe(instance5, maybeServiceAccount)118 val status = operation.getOrThrow().status119 status should (be("TERMINATED") or be("STOPPED"))120 }121 }122 "work with Cloud SQL" {123 val operation = Instance.create(instance6, maybeServiceAccount)124 operation.getOrThrow() shouldEndWith "RUNNING"125 eventually(2.minutes, 15.seconds) {126 Instance.logs(instance6, 500, accessToken, maybeServiceAccount).getOrThrow() shouldExist { it.jsonPayload?.message?.contains("(1 row)") ?: false }127 }128 }129 }130 afterSpec {131 // todo: run in parallel132 runBlocking {133 fun delete(instance: Instance) = async {134 if (Instance.describe(instance, maybeServiceAccount).isSuccess) {135 Instance.delete(instance, maybeServiceAccount)136 }137 }138 val i1 = delete(instance1)139 val i2 = delete(instance2)140 val i3 = delete(instance3)141 val i4 = delete(instance4)142 val i5 = delete(instance5)143 val i6 = delete(instance6)144 i1.await()145 i2.await()146 i3.await()147 i4.await()148 i5.await()149 i6.await()150 }151 }152})...
KotlinTest.kt
Source: KotlinTest.kt
...76class MatcherTest : StringSpec() {77 init {78 // shouldBeë ëì¼í¨ì ì²´í¬íë Matcher ì´ë¤.79 "hello World" shouldBe haveLength(11) // lengthê° ë§¤ê°ë³ìì ì ë¬ë ê°ì´ì´ì¼ í¨ì ì²´í¬íë¤.80 "hello" should include("ll") // 매ê°ë³ì ê°ì´ í¬í¨ëì´ ìëì§ íì¸íë¤.81 "hello" should endWith("lo") // 매ê°ë³ìì ëì´ í¬í¨ëëì§ íì¸íë¤.82 "hello" should match("he...") // 매ê°ë³ìê° ë§¤ì¹ëëì§ ì²´í¬íë¤.83 "hello".shouldBeLowerCase() // ì문ìë¡ ìì±ë ê²ì´ ë§ëì§ ì²´í¬íë¤.84 val list = emptyList<String>()85 val list2 = listOf("aaa", "bbb", "ccc")86 val map = mapOf<String, String>(Pair("aa", "11"))87 list should beEmpty() // ììê° ë¹ìëì§ íì¸íë¤.88 list2 shouldBe sorted<String>() // í´ë¹ ìë£íì´ ì ë ¬ëì´ ìëì§ íì¸íë¤.89 map should contain("aa", "11") // í´ë¹ ììê° í¬í¨ëì´ ìëì§ íì¸íë¤.90 map should haveKey("aa") // í´ë¹ í¤ ê°ì´ í¬í¨ëì´ ìëì§ íì¸íë¤.91 map should haveValue("11") // í´ë¹ value ê°ì´ í¬í¨ëì´ ìëì§ íì¸íë¤.92 }93}...
PasswordGeneratorSpec.kt
Source: PasswordGeneratorSpec.kt
...36 }37 context("Default generator") {38 val defaultGenerator = PasswordGenerator.Default39 test("Uses AZ az characters") {40 val pw = defaultGenerator.generate(includeSpecial = false, includeNumber = false)41 pw shouldMatch Regex("[a-zA-Z]+")42 }43 test("Includes a special characters") {44 val pw = defaultGenerator.generate(includeSpecial = true, includeNumber = false)45 shouldNotThrowAny {46 pw.single { it in oracleAcceptedSpecialCharacters }47 }48 }49 test("Includes a number") {50 val pw = defaultGenerator.generate(includeSpecial = false, includeNumber = true)51 pw.forOne { it shouldBeInRange '0'..'9' }52 }53 }54 test("Generates password with the desired size") {55 target.generate(size = 12) shouldHaveLength 1256 target.generate(size = 25) shouldHaveLength 2557 }58 test("Defaults to size 8") {59 target.generate() shouldHaveLength 860 }61 test("Generates random, different passwords") {62 val passwords = List(100) { target.generate() }63 passwords.shouldBeUnique()64 }...
helloSpec.kt
Source: helloSpec.kt
...44 it("should use custom matcher") {45 fun containFoo() = object : Matcher<String> {46 override fun test(value: String) = MatcherResult(47 value.contains("foo"),48 { "String '$value' should include 'foo'" },49 { "String '$value' should not include 'foo'" }50 )51 }52 "hello foo".shouldNot(containFoo())53 "hello bar".shouldNot(containFoo())54 }55 }56})57/*58use soft assertions to group assertions.59```60assertSoftly(foo) {61 shouldNotEndWith("b")62 length.shouldBe(3)63}...
FollowLinkTest.kt
Source: FollowLinkTest.kt
...13fun containActivities(names: Collection<String>) = object : Matcher<Collection<Activity>> {14 override fun test(value: Collection<Activity>): MatcherResult {15 return MatcherResult(16 value.map(Activity::name).containsAll(names),17 "String $value should include $names",18 "String $value should not include $names"19 )20 }21}22class AnotherFollowLinkTest : DescribeSpec({23 context("when a link is followed") {24 it("will add a followed activity") {25 val adapter = TestAdapter(mutableListOf(Link(href = "http://example.com", name = "name", id = "id")))26 FollowLink(reader = adapter, writer = adapter)27 .follow(name = "name")28 val activities = adapter.find(name = "name")?.activities.orEmpty()29 println(activities)30 activities should containActivities(listOf("followed"))31 }32 it("will return the href") {...
MatcherTest.kt
Source: MatcherTest.kt
...10class MatcherTest : StringSpec() {11 init {12 // 'shouldBe' ëì¼í¨ì ì²´í¬íë Matcher ì
ëë¤.13 "hello world" shouldBe haveLength(11) // lengthê° 11ì´ì´ì¼ í¨ì ì²´í¬ í©ëë¤.14 "hello" should include("ll") // íë¼ë¯¸í°ê° í¬í¨ëì´ ìëì§ ì²´í¬ í©ëë¤.15 "hello" should endWith("lo") // íë¼ë¯¸í°ê° ëì í¬í¨ëëì§ ì²´í¬ í©ëë¤.16 "hello" should match("he...") // íë¼ë¯¸í°ê° 매ì¹ëëì§ ì²´í¬ í©ëë¤.17 "hello".shouldBeLowerCase() // ì문ìë¡ ìì±ëìëì§ ì²´í¬ í©ëë¤.18 val list = emptyList<String>()19 val list2 = listOf("aaa", "bbb", "ccc")20 val map = mapOf<String, String>(Pair("aa", "11"))21 list should beEmpty() // ììê° ë¹ìëì§ ì²´í¬ í©ëë¤.22 list2 shouldBe sorted<String>() // í´ë¹ ìë£íì´ ì ë ¬ ëìëì§ ì²´í¬ í©ëë¤.23 map should contain("aa", "11") // í´ë¹ ììê° í¬í¨ëìëì§ ì²´í¬ í©ëë¤.24 map should haveKey("aa") // í´ë¹ keyê° í¬í¨ëìëì§ ì²´í¬ í©ëë¤.25 map should haveValue("11") // í´ë¹ valueê° í¬í¨ëìëì§ ì²´í¬ í©ëë¤.26 }27}...
RequestLensTest.kt
Source: RequestLensTest.kt
...12import org.http4k.core.Uri13class RequestLensTest: ShouldSpec() {14 @Suppress("SameParameterValue")15 private fun contain(otherSting: String) = object : Matcher<String> {16 override fun test(value: String) = MatcherResult(value.contains(otherSting), "String $value should include $otherSting", "String $value should not include $otherSting")17 }18 init {19 should("Not contain nulls") {20 val habit = HabitRequest(21 "name",22 emptyList(),23 1,24 Period.Day,25 null,26 null,27 null,28 emptyList()29 )30 val request = Request(Method.GET, Uri.of(Config.app.tracker.url).path(""))...
include
Using AI Code Generation
1 fun `should test string`() {2 str should startWith("h")3 str should endWith("o")4 str should contain("ell")5 str should notContain("foo")6 str should match("h.*")7 }8}9 fun `should test collection`() {10 val list = listOf("hello", "world")11 list should haveSize(2)12 list should contain("hello")13 list should containAll("hello", "world")14 list should containInOrder("hello", "world")15 list should containExactly("hello", "world")16 list should containNone("foo")17 list should containAnyOf("foo", "hello")18 list should containAllInOrder("hello", "world")19 list should containAllInOrderOnly("hello", "world")20 }21}22 fun `should test iterable`() {23 val iterable = listOf("hello", "world").asIterable()24 iterable should haveSize(2)25 iterable should contain("hello")26 iterable should containAll("hello", "world")27 iterable should containInOrder("hello", "world")28 iterable should containExactly("hello", "world")29 iterable should containNone("foo")30 iterable should containAnyOf("foo", "hello")31 iterable should containAllInOrder("hello", "world")32 iterable should containAllInOrderOnly("hello", "world")33 }34}35 fun `should test map`() {36 val map = mapOf("hello" to 1, "world" to 2)37 map should haveSize(2)38 map should containKey("hello")39 map should containValue(1)40 map should containAllKeys("hello", "world")41 map should containAllValues(1, 2)42 map should containExactly("hello" to 1, "world" to 2)43 map should containExactlyInAnyOrder("hello" to 1, "world" to 2)
Check out the latest blogs from LambdaTest on this topic:
Agile software development stems from a philosophy that being agile means creating and responding to change swiftly. Agile means having the ability to adapt and respond to change without dissolving into chaos. Being Agile involves teamwork built on diverse capabilities, skills, and talents. Team members include both the business and software development sides working together to produce working software that meets or exceeds customer expectations continuously.
When working on web automation with Selenium, I encountered scenarios where I needed to refresh pages from time to time. When does this happen? One scenario is that I needed to refresh the page to check that the data I expected to see was still available even after refreshing. Another possibility is to clear form data without going through each input individually.
Building a website is all about keeping the user experience in mind. Ultimately, it’s about providing visitors with a mind-blowing experience so they’ll keep coming back. One way to ensure visitors have a great time on your site is to add some eye-catching text or image animations.
Automating testing is a crucial step in the development pipeline of a software product. In an agile development environment, where there is continuous development, deployment, and maintenance of software products, automation testing ensures that the end software products delivered are error-free.
As a developer, checking the cross browser compatibility of your CSS properties is of utmost importance when building your website. I have often found myself excited to use a CSS feature only to discover that it’s still not supported on all browsers. Even if it is supported, the feature might be experimental and not work consistently across all browsers. Ask any front-end developer about using a CSS feature whose support is still in the experimental phase in most prominent web browsers. ????
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!!