Best Kotest code snippet using io.kotest.matchers.date.instant.before
MpInstantSpec.kt
Source:MpInstantSpec.kt
...92 val result = now.plus(1.minutes)93 result.toEpochMillis() shouldBe now.toEpochMillis() + (60 * 1_000)94 }95 "plus(value, unit, timezone)" {96 val beforeDST = MpInstant.parse("2022-03-27T00:00:00.000[Europe/Berlin]")97 val afterDST = beforeDST.plus(1, DateTimeUnit.DAY, TimeZone.of("Europe/Berlin"))98 afterDST shouldBe MpInstant.parse("2022-03-28T00:00:00.000[Europe/Berlin]")99 (afterDST - beforeDST) shouldBe 23.hours100 }101 "minus(duration)" {102 val now = MpInstant.now()103 val result = now.minus(1.minutes)104 result.toEpochMillis() shouldBe now.toEpochMillis() - (60 * 1_000)105 }106 "minus(value, unit, timezone)" {107 val beforeDST = MpInstant.parse("2022-03-28T00:00:00.000[Europe/Berlin]")108 val afterDST = beforeDST.minus(1, DateTimeUnit.DAY, TimeZone.of("Europe/Berlin"))109 afterDST shouldBe MpInstant.parse("2022-03-27T00:00:00.000[Europe/Berlin]")110 (afterDST - beforeDST) shouldBe (-23).hours111 }112 "minus(other: MpInstant)" {113 val result = MpInstant.parse("2022-04-01T01:00:00Z") - MpInstant.parse("2022-04-01T00:00:00Z")114 result shouldBe 1.hours115 }116})...
CaPluginTest.kt
Source:CaPluginTest.kt
1package family.haschka.wolkenschloss.gradle.ca2import family.haschka.wolkenschloss.testing.Template3import family.haschka.wolkenschloss.testing.createRunner4import io.kotest.assertions.assertSoftly5import io.kotest.core.spec.IsolationMode6import io.kotest.core.spec.style.FunSpec7import io.kotest.engine.spec.tempdir8import io.kotest.matchers.file.shouldBeReadable9import io.kotest.matchers.file.shouldContainFile10import io.kotest.matchers.file.shouldExist11import io.kotest.matchers.file.shouldNotBeWriteable12import io.kotest.matchers.ints.shouldBeGreaterThan13import io.kotest.matchers.shouldBe14import org.bouncycastle.asn1.x500.X500Name15import org.bouncycastle.asn1.x509.KeyUsage16import org.gradle.testkit.runner.TaskOutcome17import java.time.LocalDate18import java.time.LocalTime19import java.time.ZoneOffset20import java.time.ZonedDateTime21import java.util.*22class CaPluginTest : FunSpec({23 autoClose(Template("ca")).withClone {24 context("A project using com.github.wolkenschloss.ca gradle plugin") {25 val xdgDataHome = tempdir()26 val environment = mapOf("XDG_DATA_HOME" to xdgDataHome.absolutePath)27 context("executing ca task") {28 val result = createRunner()29 .withArguments(CaPlugin.CREATE_TASK_NAME)30 .withEnvironment(environment)31 .build()32 test("should be successful") {33 result.task(":${CaPlugin.CREATE_TASK_NAME}")!!.outcome shouldBe TaskOutcome.SUCCESS34 }35 test("should create self signed root certificate") {36 assertSoftly(CertificateWrapper.read(xdgDataHome.resolve("wolkenschloss/ca/ca.crt"))) {37 x509Certificate.basicConstraints shouldBeGreaterThan -138 x509Certificate.basicConstraints shouldBe Int.MAX_VALUE39 keyUsage.hasUsages(KeyUsage.keyCertSign) shouldBe true40 issuer shouldBe X500Name(CaPlugin.TRUST_ANCHOR_DEFAULT_SUBJECT)41 subject shouldBe X500Name(CaPlugin.TRUST_ANCHOR_DEFAULT_SUBJECT)42 }43 }44 test("should create read only certificate") {45 assertSoftly(xdgDataHome.resolve("wolkenschloss/ca/ca.crt")) {46 shouldBeReadable()47 shouldNotBeWriteable()48 }49 }50 test("should create readonly private key") {51 assertSoftly(xdgDataHome.resolve("wolkenschloss/ca/ca.key")) {52 shouldNotBeWriteable()53 shouldBeReadable()54 readPrivateKey().algorithm shouldBe "RSA"55 }56 }57 }58 context("executing truststore task") {59 val result = createRunner()60 .withArguments(CaPlugin.TRUSTSTORE_TASK_NAME)61 .withEnvironment(environment)62 .build()63 test("should execute successfully") {64 result.task(":${CaPlugin.TRUSTSTORE_TASK_NAME}")!!.outcome shouldBe TaskOutcome.SUCCESS65 }66 test("should create truststore file") {67 xdgDataHome.resolve("wolkenschloss/ca/ca.jks").shouldExist()68 }69 }70 test("should customize validity") {71 val start = ZonedDateTime.of(72 LocalDate.of(2022, 2, 4),73 LocalTime.MIDNIGHT,74 ZoneOffset.UTC75 )76 val end = ZonedDateTime.of(77 LocalDate.of(2027, 2, 4),78 LocalTime.MIDNIGHT,79 ZoneOffset.UTC80 )81 val result = createRunner()82 .withArguments(CaPlugin.CREATE_TASK_NAME, "-DnotBefore=$start", "-DnotAfter=$end")83 .withEnvironment(environment)84 .build()85 result.task(":${CaPlugin.CREATE_TASK_NAME}")!!.outcome shouldBe TaskOutcome.SUCCESS86 val certificate = xdgDataHome.resolve("wolkenschloss/ca/ca.crt")87 .readX509Certificate()88 assertSoftly(certificate) {89 notBefore.toUtc() shouldBe start90 notAfter.toUtc() shouldBe end91 }92 }93 test("should create output in user defined location") {94 val result = createRunner()95 .withArguments("createInUserDefinedLocation")96 .withEnvironment(environment)97 .build()98 result.task(":createInUserDefinedLocation")!!.outcome shouldBe TaskOutcome.SUCCESS99 assertSoftly(workingDirectory.resolve("build/ca")) {100 shouldContainFile("ca.crt")101 shouldContainFile("ca.key")102 }103 }104 }105 }106}) {107 override fun isolationMode(): IsolationMode = IsolationMode.InstancePerLeaf108}109private fun Date.toUtc(): ZonedDateTime {110 return ZonedDateTime.ofInstant(this.toInstant(), ZoneOffset.UTC)111}...
ItemRepositoryTestOld.kt
Source:ItemRepositoryTestOld.kt
...37class ItemRepositoryTestOld {38 @Autowired39 lateinit var itemRepository: ItemRepository40 @BeforeEach41 fun beforeEach() {42 itemRepository.deleteAll().block()43 }44 @Test45 fun `should save and read item`() = runBlocking<Unit> {46 val item = createItem()47 itemRepository.coSave(item)48 val read = itemRepository.coFindById(item.id)49 read shouldNotBe null50 read!!.id shouldBe item.id51 }52 @Test53 fun `should read all items after lastUpdated date`() = runBlocking<Unit> {54 val db = (1L..5L).map { tokenId ->55 val i = itemRepository.coSave(createItem(tokenId = tokenId))56 delay(10)57 i58 }59 val since = db[0].updatedAt.plus(10, ChronoUnit.MILLIS)60 val items = itemRepository.search(61 ItemFilter.All(lastUpdatedFrom = since),62 null,63 null,64 ItemFilter.Sort.LAST_UPDATE65 ).asFlow().toList()66 items shouldHaveSize 467 items shouldNotContain db[0]68 }69 @Test70 fun `should read all items before lastUpdated date`() = runBlocking<Unit> {71 val db = (1L..5L).map { tokenId ->72 val i = itemRepository.coSave(createItem(tokenId = tokenId))73 delay(10)74 i75 }76 val before = db[2].updatedAt77 val items = itemRepository.search(78 ItemFilter.All(lastUpdatedTo = before),79 null,80 null,81 ItemFilter.Sort.LAST_UPDATE82 ).asFlow().toList()83 items shouldHaveSize 284 items shouldNotContain listOf(db[0], db[1])85 }86 @Test87 fun `should read all items between dates`() = runBlocking<Unit> {88 val db = (1L..5L).map { tokenId ->89 val i = itemRepository.coSave(createItem(tokenId = tokenId))90 delay(10)91 i92 }93 val before = db[2].updatedAt94 val after = db[0].updatedAt95 val items = itemRepository.search(96 ItemFilter.All(lastUpdatedFrom = after, lastUpdatedTo = before),97 null,98 null,99 ItemFilter.Sort.LAST_UPDATE100 ).asFlow().toList()101 items shouldHaveSize 2102 items shouldNotContain listOf(db[0], db[1])103 }104 @Test105 fun `should save and find by account`() = runBlocking<Unit> {106 val item = createItem()107 itemRepository.coSave(item)108 var read = itemRepository.findAllByCreator(FlowAddress("0x01")).asFlow()109 read.count() shouldBe 1110 read.collect {...
timestampTest.kt
Source:timestampTest.kt
...34 "timestamp of current instance should not be after the another timestamp of same instance" {35 val nowInstance = Instant.now()36 Timestamp.from(nowInstance) shouldNotBeAfter Timestamp.from(nowInstance)37 }38 "timestamp of current instance should be before the timestamp of future instance" {39 val nowInstance = Instant.now()40 val instanceAfterFiveSecond = nowInstance.plusMillis(5000L)41 Timestamp.from(nowInstance) shouldBeBefore Timestamp.from(instanceAfterFiveSecond)42 }43 "timestamp of current instance should not be before the timestamp of past instance" {44 val nowInstance = Instant.now()45 val instanceBeforeFiveSecond = nowInstance.minusMillis(5000L)46 Timestamp.from(nowInstance) shouldNotBeBefore Timestamp.from(instanceBeforeFiveSecond)47 }48 "timestamp of current instance should not be before the another timestamp of same instance" {49 val nowInstance = Instant.now()50 Timestamp.from(nowInstance) shouldNotBeBefore Timestamp.from(nowInstance)51 }52 "current timestamp should be between timestamp of past and future" {53 val nowInstant = Instant.now()54 val currentTimestamp = Timestamp.from(nowInstant)55 val pastTimestamp = Timestamp.from(nowInstant.minusMillis(5000))56 val futureTimestamp = Timestamp.from(nowInstant.plusMillis(5000))57 currentTimestamp.shouldBeBetween(pastTimestamp, futureTimestamp)58 }59 "past timestamp should not be between timestamp of current instant and future" {60 val nowInstant = Instant.now()61 val currentTimestamp = Timestamp.from(nowInstant)62 val pastTimestamp = Timestamp.from(nowInstant.minusMillis(5000))...
DataTimeTests.kt
Source:DataTimeTests.kt
1import com.meowool.sweekt.datetime.currentHour2import com.meowool.sweekt.datetime.currentMinute3import com.meowool.sweekt.datetime.currentMonth4import com.meowool.sweekt.datetime.currentSecond5import com.meowool.sweekt.datetime.currentYear6import com.meowool.sweekt.datetime.format7import com.meowool.sweekt.datetime.inRange8import com.meowool.sweekt.datetime.nowDateTime9import com.meowool.sweekt.datetime.nowInstant10import com.meowool.sweekt.datetime.toDateTime11import com.meowool.sweekt.datetime.toInstant12import com.meowool.sweekt.datetime.todayOfMonth13import io.kotest.core.spec.style.StringSpec14import io.kotest.matchers.kotlinx.datetime.shouldBeAfter15import io.kotest.matchers.kotlinx.datetime.shouldBeBefore16import io.kotest.matchers.kotlinx.datetime.shouldHaveSameDayAs17import io.kotest.matchers.kotlinx.datetime.shouldHaveSameMonthAs18import io.kotest.matchers.kotlinx.datetime.shouldHaveSameYearAs19import io.kotest.matchers.kotlinx.datetime.shouldNotBeAfter20import io.kotest.matchers.kotlinx.datetime.shouldNotBeBefore21import io.kotest.matchers.kotlinx.datetime.shouldNotHaveSameYearAs22import io.kotest.matchers.should23import io.kotest.matchers.shouldBe24import java.time.Month25/**26 * Tests for DataTimes.kt27 *28 * @author å (RinOrz)29 */30class DataTimeTests : StringSpec({31 val instant = nowInstant32 val dateTime = nowDateTime33 "effective instant time" {34 val instantTime = instant.toDateTime()35 dateTime shouldHaveSameYearAs instantTime36 dateTime shouldHaveSameMonthAs instantTime37 dateTime shouldHaveSameDayAs instantTime38 dateTime.second shouldBe instantTime.second39 }40 "resolved date time string" {41 val resolvedTime = "2020-2-11 07:00".toDateTime("yyyy-M-d HH:mm")42 val resolvedInstant = "2020-2-11 07:00".toInstant("yyyy-M-d HH:mm")43 val resolvedInstantTime = resolvedInstant.toDateTime()44 resolvedTime.toInstant() shouldBe resolvedInstant45 resolvedTime shouldHaveSameYearAs resolvedInstantTime46 resolvedTime shouldHaveSameMonthAs resolvedInstantTime47 resolvedTime shouldHaveSameDayAs resolvedInstantTime48 resolvedTime should {49 it.year shouldBe 202050 it.month shouldBe Month.FEBRUARY51 it.dayOfMonth shouldBe 1152 it.hour shouldBe 753 it.minute shouldBe 054 it.second shouldBe 055 }56 }57 "correct formatting date time" {58 val dateFormatted = dateTime.format("yyyy-M-d H:m:s")59 dateFormatted shouldBe instant.format("yyyy-M-d H:m:s")60 dateFormatted shouldBe "$currentYear-$currentMonth-$todayOfMonth $currentHour:$currentMinute:$currentSecond"61 }62 "date in range" {63 val start = "2010-1-2".toDateTime("yyyy-M-d")64 val stop = "2011-2-4".toDateTime("yyyy-M-d")65 val early = "2010-11-12".toDateTime("yyyy-M-d")66 val lately = "2111-5-8".toDateTime("yyyy-M-d")67 start shouldNotBeAfter stop68 stop shouldNotBeBefore start69 early shouldBeAfter start70 early shouldBeBefore stop71 lately shouldBeAfter start72 lately shouldNotBeBefore stop73 early.inRange(start, stop) shouldBe true74 lately.inRange(start, stop) shouldBe false75 }76 "time in range" {77 val start = "2022-1-2 02:00".toDateTime("yyyy-M-d HH:mm")78 val stop = "2022-1-2 22:54".toDateTime("yyyy-M-d HH:mm")79 val inRange = "2022-1-2 07:00".toDateTime("yyyy-M-d HH:mm")80 val notRange = "2022-1-2 00:00".toDateTime("yyyy-M-d HH:mm")81 val unknownDate = "07:00".toDateTime("HH:mm")82 start shouldHaveSameYearAs stop83 start shouldHaveSameMonthAs stop84 start shouldHaveSameDayAs stop85 inRange shouldNotBeAfter stop86 notRange shouldBeBefore start87 unknownDate shouldNotHaveSameYearAs start88 unknownDate shouldNotHaveSameYearAs stop89 inRange.inRange(start, stop) shouldBe true90 notRange.inRange(start, stop) shouldBe false91 unknownDate.inRange(start, stop) shouldBe false92 }93})...
instantMatcherTest.kt
Source:instantMatcherTest.kt
...22 val currentInstant = Instant.now()23 val pastInstant = currentInstant.minusMillis(40000)24 currentInstant shouldNotBe pastInstant25 }26 "past instant should be before current instant" {27 val currentInstant = Instant.now()28 val pastInstant = currentInstant.minusMillis(1000)29 pastInstant shouldBeBefore currentInstant30 }31 "current instant should not be before past instant" {32 val currentInstant = Instant.now()33 val pastInstant = currentInstant.minusMillis(1000)34 currentInstant shouldNotBeBefore pastInstant35 }36 "future instant should be after current instant" {37 val currentInstant = Instant.now()38 val futureInstant = currentInstant.plusMillis(1000)39 futureInstant shouldBeAfter currentInstant40 }41 "current instant should not be after past instant" {42 val currentInstant = Instant.now()43 val futureInstant = currentInstant.plusMillis(1000)44 currentInstant shouldNotBeAfter futureInstant45 }46 "instant of same time should not be before another instant of same time" {47 Instant.ofEpochMilli(30000) shouldNotBeBefore Instant.ofEpochMilli(30000)48 }49 "instant of same time should not be after another instant of same time" {50 Instant.ofEpochMilli(30000) shouldNotBeAfter Instant.ofEpochMilli(30000)51 }52 "current instant should be between past instant and future instant" {53 val currentInstant = Instant.now()54 val pastInstant = currentInstant.minusMillis(30000)55 val futureInstant = currentInstant.plusMillis(30000)56 currentInstant.shouldBeBetween(pastInstant, futureInstant)57 }58 "past instant should not be between current instant and future instant" {59 val currentInstant = Instant.now()60 val pastInstant = currentInstant.minusMillis(30000)...
CreateTrialUserImplTest.kt
Source:CreateTrialUserImplTest.kt
1package com.falcon.falcon.core.usecase.trial2import com.falcon.falcon.core.entity.User3import com.falcon.falcon.core.enumeration.UserType4import com.falcon.falcon.core.usecase.user.CreateUserUseCase5import io.kotest.matchers.date.shouldBeBetween6import io.kotest.matchers.shouldBe7import io.kotest.matchers.string.shouldBeUUID8import io.kotest.matchers.types.shouldBeTypeOf9import io.mockk.clearAllMocks10import io.mockk.every11import io.mockk.mockk12import org.junit.jupiter.api.BeforeEach13import org.junit.jupiter.api.Test14import org.junit.jupiter.api.TestInstance15import java.time.Instant16import java.time.temporal.ChronoUnit17@TestInstance(TestInstance.Lifecycle.PER_CLASS)18internal class CreateTrialUserImplTest {19 private val createUserUseCase: CreateUserUseCase = mockk()20 private val trialDuration = 1L21 private val underTest: CreateTrialUserImpl = CreateTrialUserImpl(createUserUseCase, trialDuration)22 @BeforeEach23 fun init() {24 clearAllMocks()25 }26 @Test27 fun `Should generate random user`() {28 // Given29 every { createUserUseCase.execute(any()) } returnsArgument 030 // When31 val result = underTest.execute()32 // Then33 result.shouldBeTypeOf<User>()34 result.username.shouldBeUUID()35 result.password.shouldBeUUID()36 result.type.shouldBe(UserType.TRIAL)37 result.expirationDate?.shouldBeBetween(38 Instant.now().plus(50, ChronoUnit.MINUTES),39 Instant.now().plus(70, ChronoUnit.MINUTES),40 )41 }42}...
PingTest.kt
Source:PingTest.kt
1package no.arcane.platform.tests2import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.date.shouldBeAfter4import io.kotest.matchers.date.shouldBeBefore5import io.kotest.matchers.shouldBe6import io.ktor.client.call.*7import io.ktor.client.request.*8import java.time.Instant9import java.util.*10class PingTest : StringSpec({11 "GET /ping" {12 val response: String = apiClient.get {13 url(path = "ping")14 }.body()15 response shouldBe "pong"16 }17 "POST /ping" {18 val response: String = apiClient.post {19 url(path = "ping")20 }.body()21 response shouldBe "pong"22 }23 "GET /utc" {24 val response: String = apiClient.get {25 url(path = "utc")26 headers {27 appendEndpointsApiUserInfoHeader(UUID.randomUUID().toString())28 }29 }.body()30 Instant.parse(response) shouldBeBefore Instant.now()31 Instant.parse(response) shouldBeAfter Instant.now().minusSeconds(7)32 }33})...
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!!