Best Kotest code snippet using io.kotest.matchers.date.timestamp
AppendLoanStatesContractUnitTest.kt
Source:AppendLoanStatesContractUnitTest.kt  
1package io.provenance.scope.loan.contracts2import io.kotest.assertions.throwables.shouldNotThrow3import io.kotest.assertions.throwables.shouldThrow4import io.kotest.core.spec.style.WordSpec5import io.kotest.core.test.TestCaseOrder6import io.kotest.matchers.ints.shouldBeExactly7import io.kotest.matchers.string.shouldContain8import io.kotest.matchers.string.shouldContainIgnoringCase9import io.kotest.property.Arb10import io.kotest.property.arbitrary.arbitrary11import io.kotest.property.arbitrary.flatMap12import io.kotest.property.arbitrary.int13import io.kotest.property.arbitrary.pair14import io.kotest.property.checkAll15import io.provenance.scope.loan.test.Constructors.appendLoanStatesContractWithNoExistingStates16import io.provenance.scope.loan.test.LoanPackageArbs.anyUuid17import io.provenance.scope.loan.test.LoanPackageArbs.anyValidChecksum18import io.provenance.scope.loan.test.LoanPackageArbs.anyValidLoanState19import io.provenance.scope.loan.test.LoanPackageArbs.anyValidTimestamp20import io.provenance.scope.loan.test.LoanPackageArbs.loanStateSet21import io.provenance.scope.loan.utility.ContractViolationException22import io.provenance.scope.util.toOffsetDateTime23import tech.figure.servicing.v1beta1.LoanStateOuterClass.LoanStateMetadata24import tech.figure.servicing.v1beta1.LoanStateOuterClass.ServicingData25import kotlin.math.max26class AppendLoanStatesContractUnitTest : WordSpec({27    "appendLoanStates" When {28        "given an empty input" should {29            "throw an appropriate exception" {30                shouldThrow<ContractViolationException> {31                    appendLoanStatesContractWithNoExistingStates.appendLoanStates(emptyList())32                }.let { exception ->33                    exception.message shouldContainIgnoringCase "Must supply at least one loan state"34                }35            }36        }37        "given at least one loan state with invalid fields" should {38            "throw an appropriate exception" {39                checkAll(anyValidLoanState) { randomLoanState ->40                    shouldThrow<ContractViolationException> {41                        appendLoanStatesContractWithNoExistingStates.appendLoanStates(42                            listOf(43                                LoanStateMetadata.getDefaultInstance(),44                                randomLoanState,45                            )46                        )47                    }.let { exception ->48                        exception.message shouldContainIgnoringCase "must have valid ID"49                        exception.message shouldContainIgnoringCase "missing URI"50                        exception.message shouldContainIgnoringCase "missing checksum"51                    }52                }53            }54        }55        "given loan states which duplicate existing loan state checksums" should {56            "throw an appropriate exception" {57                checkAll(anyValidLoanState, anyValidLoanState, anyValidChecksum) { randomExistingLoanState, randomNewLoanState, randomChecksum ->58                    shouldThrow<ContractViolationException> {59                        AppendLoanStatesContract(60                            existingServicingData = ServicingData.newBuilder().also { servicingDataBuilder ->61                                servicingDataBuilder.clearLoanState()62                                servicingDataBuilder.addLoanState(63                                    randomExistingLoanState.toBuilder().also { loanStateBuilder ->64                                        loanStateBuilder.checksum = randomChecksum65                                    }.build()66                                )67                            }.build()68                        ).appendLoanStates(69                            listOf(70                                randomNewLoanState.toBuilder().also { loanStateBuilder ->71                                    loanStateBuilder.checksum = randomChecksum72                                }.build()73                            )74                        )75                    }.let { exception ->76                        exception.message shouldContain "Loan state with checksum ${randomChecksum.checksum} already exists"77                    }78                }79            }80        }81        "given loan states which duplicate existing loan state IDs" should {82            "throw an appropriate exception" {83                checkAll(anyValidLoanState, anyValidLoanState, anyUuid) { randomExistingLoanState, randomNewLoanState, randomUuid ->84                    shouldThrow<ContractViolationException> {85                        AppendLoanStatesContract(86                            existingServicingData = ServicingData.newBuilder().also { servicingDataBuilder ->87                                servicingDataBuilder.clearLoanState()88                                servicingDataBuilder.addLoanState(89                                    randomExistingLoanState.toBuilder().also { loanStateBuilder ->90                                        loanStateBuilder.id = randomUuid91                                    }.build()92                                )93                            }.build()94                        ).appendLoanStates(95                            listOf(96                                randomNewLoanState.toBuilder().also { loanStateBuilder ->97                                    loanStateBuilder.id = randomUuid98                                }.build()99                            )100                        )101                    }.let { exception ->102                        exception.message shouldContain "Loan state with ID ${randomUuid.value} already exists"103                    }104                }105            }106        }107        "given loan states which duplicate existing loan state times" should {108            "throw an appropriate exception" {109                checkAll(anyValidLoanState, anyValidLoanState, anyValidTimestamp) { randomExistingLoanState, randomNewLoanState, randomTimestamp ->110                    shouldThrow<ContractViolationException> {111                        AppendLoanStatesContract(112                            existingServicingData = ServicingData.newBuilder().also { servicingDataBuilder ->113                                servicingDataBuilder.clearLoanState()114                                servicingDataBuilder.addLoanState(115                                    randomExistingLoanState.toBuilder().also { loanStateBuilder ->116                                        loanStateBuilder.effectiveTime = randomTimestamp117                                    }.build()118                                )119                            }.build()120                        ).appendLoanStates(121                            listOf(122                                randomNewLoanState.toBuilder().also { loanStateBuilder ->123                                    loanStateBuilder.effectiveTime = randomTimestamp124                                }.build()125                            )126                        )127                    }.let { exception ->128                        exception.message shouldContain "Loan state with effective time ${randomTimestamp.toOffsetDateTime()} already exists"129                    }130                }131            }132        }133        "given only new & valid loan states" should {134            "not throw an exception" {135                val stateCountRange = 2..4 // Reduce the upper bound of this range (to no lower than 3) to decrease the execution time136                val arbitraryStateCountAndSplit = Arb.int(stateCountRange).flatMap { randomStateCount ->137                    Arb.pair(arbitrary { randomStateCount }, Arb.int(0..max(randomStateCount - 1, 1)))138                }139                checkAll(arbitraryStateCountAndSplit) { (randomStateCount, randomSplit) ->140                    checkAll(loanStateSet(size = randomStateCount)) { randomStateSet ->141                        val (randomExistingStates, randomNewStates) = randomStateSet.let { orderedRandomStateSet ->142                            orderedRandomStateSet.take(randomSplit) to orderedRandomStateSet.drop(randomSplit)143                        }144                        shouldNotThrow<ContractViolationException> {145                            AppendLoanStatesContract(146                                existingServicingData = ServicingData.newBuilder().also { servicingDataBuilder ->147                                    servicingDataBuilder.clearLoanState()148                                    servicingDataBuilder.addAllLoanState(randomExistingStates)149                                }.build()150                            ).appendLoanStates(151                                randomNewStates152                            ).let { outputRecord ->153                                outputRecord.loanStateCount shouldBeExactly randomStateCount154                            }155                        }156                    }157                }158            }159        }160    }161}) {162    override fun testCaseOrder() = TestCaseOrder.Random163}...ExtractionUtilityTest.kt
Source:ExtractionUtilityTest.kt  
...8import io.kotest.data.forAll9import io.kotest.data.row10import io.kotest.matchers.shouldBe11import io.kotest.matchers.types.shouldBeInstanceOf12import ucfs.claimant.consumer.utility.ExtractionUtility.timestamp13class ExtractionUtilityTest: StringSpec() {14    private val lastModifiedDate = "2020-01-02"15    init {16        "Timestamp returns left when no action" {17            forAll(*sourceFields()) { sourceField ->18                jsonObject("""{ 19                        "message": { "$sourceField": "2020-01-02" },20                        "timestamp": "2020-05-06"21                    }""").timestamp() shouldBeLeft {22                    it.shouldBeInstanceOf<Pair<JsonObject, String>>()23                    val (jsonObject, field) = it24                    gson.toJson(jsonObject) shouldMatchJson """{ "$sourceField": "2020-01-02" }"""25                    field shouldBe "@type"26                }27            }28        }29        "Timestamp returns left when unknown action" {30            forAll(*sourceFields()) { sourceField ->31                jsonObject("""{ 32                    "message": { 33                        "$sourceField": "2020-01-02",34                         "@type": "MONGO_JERRY"35                    },36                    "timestamp": "2020-05-06"}""").timestamp().shouldBeLeft {37                    it.shouldBeInstanceOf<Exception>()38                }39            }40        }41        "Timestamp returns _lastModifiedDateTime when insert or update and field present" {42            forAll(*actions()) { action ->43                jsonObject("""{44                    "message": {45                        "$LAST_MODIFIED_TIMESTAMP_FIELD": "2020-01-02",46                        "@type": "$action"47                    }48                }""").timestamp() shouldBeRight { (date, source) ->49                    date shouldBe lastModifiedDate50                    source shouldBe "_lastModifiedDateTime"51                }52            }53        }54        "Timestamp returns epoch when insert or update and no fields present" {55            forAll(*actions()) { action ->56                validateEpoch(jsonObject("""{57                    "message": {58                        "@type": "$action"59                    }60                }"""))61            }62        }63        "Timestamp returns epoch when insert or update and enqueued date present" {64            forAll(*actions()) { action ->65                validateEpoch(jsonObject("""{66                    "message": {67                        "@type": "$action"68                    },69                    "timestamp": "2020-05-06"70                }"""))71            }72        }73        "Timestamp returns createdDateTime when insert or update and lastModifiedDateTime not present" {74            forAll(*actions()) { action ->75                jsonObject("""{76                    "message": {77                        "$CREATED_TIMESTAMP_FIELD": "2020-01-02",78                        "@type": "$action"79                    }80                }""").timestamp() shouldBeRight { (date, source) ->81                    date shouldBe lastModifiedDate82                    source shouldBe "createdDateTime"83                }84            }85        }86        "Timestamp returns _lastModifiedDateTime when insert or update and all timestamp fields present" {87            forAll(*actions()) { action ->88                jsonObject("""{89                    "message": {90                        "$LAST_MODIFIED_TIMESTAMP_FIELD": "2020-01-02",91                        "$CREATED_TIMESTAMP_FIELD": "2020-01-03",92                        "@type": "$action"93                    },94                    "$ENQUEUED_TIMESTAMP_FIELD": "2020-03-04" 95                }""").timestamp() shouldBeRight { (date, source) ->96                    date shouldBe lastModifiedDate97                    source shouldBe "_lastModifiedDateTime"98                }99            }100        }101        "Timestamp returns enqueued date when delete and enqueued date present" {102            jsonObject("""{103                "message": {104                    "$LAST_MODIFIED_TIMESTAMP_FIELD": "2020-01-02",105                    "$CREATED_TIMESTAMP_FIELD": "2020-01-03",106                    "@type": "$DELETE_ACTION"107                },108                "$ENQUEUED_TIMESTAMP_FIELD": "2020-03-04" 109            }""").timestamp() shouldBeRight { (date, source) ->110                date shouldBe "2020-03-04"111                source shouldBe ENQUEUED_TIMESTAMP_FIELD112            }113        }114        "Timestamp returns epoch when delete and enqueued date not present" {115            validateEpoch(jsonObject("""{116                "message": {117                    "$LAST_MODIFIED_TIMESTAMP_FIELD": "2020-01-02",118                    "$CREATED_TIMESTAMP_FIELD": "2020-01-03",119                    "@type": "$DELETE_ACTION"120                } 121            }"""))122        }123    }124    private fun validateEpoch(x: JsonObject) {125        x.timestamp() shouldBeRight { (date, source) ->126            date shouldBe EPOCH127            source shouldBe EPOCH_INDICATOR128        }129    }130    companion object {131        private const val EPOCH = "1980-01-01T00:00:00.000+0000"132        private const val INSERT_ACTION = "MONGO_INSERT"133        private const val UPDATE_ACTION = "MONGO_UPDATE"134        private const val DELETE_ACTION = "MONGO_DELETE"135        private const val LAST_MODIFIED_TIMESTAMP_FIELD = "_lastModifiedDateTime"136        private const val CREATED_TIMESTAMP_FIELD = "createdDateTime"137        private const val ENQUEUED_TIMESTAMP_FIELD = "timestamp"138        private const val EPOCH_INDICATOR = "epoch"139        private fun actions() = listOf(INSERT_ACTION, UPDATE_ACTION).map(::row).toTypedArray()140        private fun sourceFields() = listOf(LAST_MODIFIED_TIMESTAMP_FIELD, CREATED_TIMESTAMP_FIELD).map(::row).toTypedArray()141        private fun jsonObject(x: String) = gson.fromJson(x, JsonObject::class.java)142        private val gson = Gson()143    }144}...JsonProcessorImplTest.kt
Source:JsonProcessorImplTest.kt  
...27                        "@type": "$databaseAction",28                        "_id": {29                            "$claimantIdSourceField": "123"30                        },31                        "timestamp": "2020-01-01"32                    }33                }""".trimIndent()34                val sourceRecord = sourceRecord()35                val result = JsonProcessorImpl(idSourceFields).process(Pair(sourceRecord, json))36                result shouldBeRight { (record, result) ->37                    val (jsonObject, id, action, timestampAndSource) = result38                    Gson().toJson(jsonObject) shouldMatchJson json39                    record shouldBeSameInstanceAs sourceRecord40                    id shouldBe "123"41                    action shouldBe databaseAction42                    if (action == DatabaseAction.MONGO_DELETE) {43                        timestampAndSource shouldBe Pair("1980-01-01T00:00:00.000+0000", "epoch")44                    }45                    else {46                        timestampAndSource shouldBe Pair("2020-12-12", "_lastModifiedDateTime")47                    }48                }49            }50        }51        "Returns left if unknown database action" {52            val json = """53            {54                "message": {55                    "dbObject": "ENCRYPTED_OBJECT",56                    "@type": "MONGO_HOMOLOGATE"57                }58            }""".trimIndent()59            val sourceRecord = sourceRecord()60            val result = JsonProcessorImpl(idSourceFields).process(Pair(sourceRecord, json))...EventLocalRepositoryTest.kt
Source:EventLocalRepositoryTest.kt  
...17class EventLocalRepositoryTest(18	repository: EventLocalRepository,19) : TestContainersSpec({20	println("zone: ${ZoneId.systemDefault()}")21	val timestamp = LocalDateTime.now()22	println("now: $timestamp")23	beforeSpec {24		val event = EventLocal(description = "Second local event", timestamp = timestamp)25		repository.save(event)26	}27	"should list all events" {28		val events = repository.findAll()29		events shouldHaveSize 230	}31	"should select timestamp with correct local" {32		val correct = LocalDateTime.of(2022, 2, 23, 2, 2, 22)33		val event = repository.findAll(Sort.by(Sort.Direction.ASC, "id")).first()34		printDetails(correct)35		printDetails(event.timestamp)36//		assertSoftly {37			event.timestamp.shouldBeEqualComparingTo(correct)38			event.created.atZone(ZoneId.systemDefault()).toLocalDateTime().isEqual(correct).shouldBe(true)39//		}40	}41	"should find first event but not second" {42		val events = repository.findByTimestampBefore(timestamp.minusMinutes(10))43		events.shouldHaveSize(1)44		events.first().description shouldStartWith "First"45	}46	"should find second event but not first" {47		val events = repository.findByTimestampAfter(timestamp.minusMinutes(10))48		events.shouldHaveSize(1)49		events.first().description shouldStartWith "Second"50		events.first().timestamp shouldBe timestamp51	}52	"should find both" {53		val events = repository.findByTimestampBefore(timestamp.plusSeconds(1))54		events.shouldHaveSize(2)55		println(events)56	}57	"should find today's event" {58		val events = repository.findByTimestampAfter(LocalDate.now())59		events.shouldHaveSize(1)60		events.first().description shouldContain "Second"61		events.first().timestamp shouldBe timestamp62		println(events)63	}64})65private fun printDetails(timestamp: LocalDateTime) {66	println("day: ${timestamp.dayOfMonth}, hour: ${timestamp.hour}")67}...MessageTests.kt
Source:MessageTests.kt  
...31            "mention_roles": [],32            "pinned": false,33            "mention_everyone": false,34            "tts": false,35            "timestamp": "2020-10-03T17:03:22.761000+00:00",36            "edited_timestamp": null,37            "flags": 038        }39        """.trimIndent().deserializes<Message> {40            it.longId shouldBe 761996835337928715L41            it.type shouldBe MessageType.DEFAULT42            it.content shouldBe "This is a message"43            it.channelId.longId shouldBe 761287705354567680L44            it.author.longId shouldBe 310702108997320705L45            it.author.username shouldBe "romangraef89"46            it.author.avatarHash shouldBe "f1fb2bd7862ba7153b98c94bbdb7e750"47            it.author.discriminator shouldBe "0998"48            it.author.publicFlags shouldContainExactly setOf(UserFlag.HOUSE_BRILLIANCE, UserFlag.VERIFIED_BOT_DEVELOPER)49            it.attachments should beEmpty()50            it.embeds should beEmpty()51            it.mentions should beEmpty()52            it.pinned shouldBe false53            it.mentionEveryone shouldBe false54            it.tts shouldBe false55            it.timestamp shouldBe OffsetDateTime.of(56                2020, 10, 3,57                17, 3, 22, 761000000, ZoneOffset.ofHours(0)58            )59            it.editedTimestamp shouldBe null60            it.flags!! should beEmpty()61        }62    }63})...FileTimeSeriesDBTest.kt
Source:FileTimeSeriesDBTest.kt  
...40                )41            }42            val values = collection.read()43                .onEach { record ->44                    record.timestamp shouldBeGreaterThan startTime45                    record.name shouldBe "metric"46                    record.value shouldBeGreaterThanOrEqual 60.047                    record.value shouldBeLessThanOrEqual 100.048                }49                .toList()50            values.count() shouldBe 1_00051            values.map { it.timestamp } shouldBeSortedWith { left, right -> -left.compareTo(right) }52        }53    }54})...DateTimeSpec.kt
Source:DateTimeSpec.kt  
...18                    dateTimeToString(it) should beValidISODateTimeString<String>()19                }20            }21        }22        describe("timestampToString()") {23            it("should return a string as a datetime format") {24                checkAll<LocalDateTime>(100) {25                    timestampToString(Timestamp.valueOf(it)) should beValidISODateTimeString<String>()26                }27            }28        }29    }30)...DateConverterSpec.kt
Source:DateConverterSpec.kt  
1package io.github.zmunm.search.data.cache.converter2import io.kotest.core.spec.style.FunSpec3import io.kotest.matchers.shouldBe4import io.kotest.matchers.shouldNotBe5import java.util.Date6internal class DateConverterSpec : FunSpec({7    val converter = DateConverter()8    test("null") {9        converter.dateToTimestamp(null) shouldBe null10        converter.fromTimestamp(null) shouldBe null11    }12    test("from date") {13        val date = Date()14        val timeStamp = converter.dateToTimestamp(date)15        timeStamp shouldNotBe null16        converter.fromTimestamp(timeStamp)?.time shouldBe date.time17    }18    test("to date") {19        val timeStamp = 1_000L20        val date = converter.fromTimestamp(timeStamp)21        date shouldNotBe null22        converter.dateToTimestamp(date) shouldBe timeStamp23    }24})...timestamp
Using AI Code Generation
1    import io.kotest.matchers.date.shouldBeAfter2    import io.kotest.matchers.date.shouldBeBefore3    import java.time.Instant4    class DateMatchersTest : ShouldSpec({5        should("match date") {6            val now = Instant.now()7            val future = now.plusMillis(1000)8            val past = now.minusMillis(1000)9        }10    })11    import io.kotest.matchers.time.shouldBeAfter12    import io.kotest.matchers.time.shouldBeBefore13    import java.time.LocalDate14    class DateMatchersTest : ShouldSpec({15        should("match date") {16            val now = LocalDate.now()17            val future = now.plusDays(1)18            val past = now.minusDays(1)19        }20    })21    import io.kotest.matchers.duration.shouldBeGreaterThan22    import io.kotest.matchers.duration.shouldBeLessThan23    import java.time.Duration24    class DateMatchersTest : ShouldSpec({25        should("match duration") {26            val now = Duration.ofSeconds(3)27            val future = Duration.ofSeconds(4)28            val past = Duration.ofSeconds(2)29        }30    })31    import io.kotest.matchers.duration.shouldBeGreaterThan32    import io.kotest.matchers.duration.shouldBeLessThan33    import java.time.Duration34    class DateMatchersTest : ShouldSpec({35        should("match duration") {36            val now = Duration.ofSeconds(3)37            val future = Duration.ofSeconds(4)timestamp
Using AI Code Generation
1}2}3import io.kotest.matchers.date.timestamp4import io.kotest.matchers.date.shouldBeAfter5import java.util.Date6import org.junit.Test7class DateMatcherTest {8fun testDateMatcher() {9}10}11import io.kotest.matchers.date.timestamp12import io.kotest.matchers.date.shouldBeEqualTo13import java.util.Date14import org.junit.Test15class DateMatcherTest {16fun testDateMatcher() {17}18}19In this example, we are using the timestamp() function of theLearn 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!!
