Best Kotest code snippet using io.kotest.matchers.date.instant.after
TaskScheduleSpec.kt
Source:TaskScheduleSpec.kt
...28 ),29 contextSwitch = Duration.ofMinutes(5),30 isActive = true31 )32 fun after(): Instant = LocalTime.of(0, 50).atDate(LocalDate.now()).toInstant(ZoneOffset.UTC)33 "support updating scheduling" {34 val after = after()35 val within = Duration.ofMinutes(5)36 val schedule = TaskSchedule(task)37 schedule.task shouldBe (task)38 schedule.instances shouldBe (emptyMap())39 val updatedSchedule = schedule.update(after = after, within = within)40 updatedSchedule.task shouldBe (task)41 updatedSchedule.instances.size shouldBe (1)42 val instance = updatedSchedule.instances.values.first()43 instance.instant shouldBe (task.schedule.next(after = after, within = within).first())44 instance.postponed shouldBe (null)45 }46 "not update scheduling if a task is not active" {47 val after = after()48 val within = Duration.ofMinutes(5)49 val inactiveTask = task.copy(isActive = false)50 val schedule = TaskSchedule(inactiveTask)51 schedule.task shouldBe (inactiveTask)52 schedule.instances shouldBe (emptyMap())53 val updatedSchedule = schedule.update(after = after, within = within)54 updatedSchedule.task shouldBe (inactiveTask)55 schedule.instances shouldBe (emptyMap())56 }57 "not update scheduling if a task's next instance already exists" {58 val after = after()59 val within = Duration.ofMinutes(5)60 val schedule = TaskSchedule(task).update(after = after, within = within)61 schedule.task shouldBe (task)62 schedule.instances.size shouldBe (1)63 val updatedSchedule = schedule.update(after = after, within = within)64 updatedSchedule.task shouldBe (task)65 updatedSchedule.instances.size shouldBe (1)66 val instance = updatedSchedule.instances.values.first()67 instance.instant shouldBe (task.schedule.next(after = after, within = within).first())68 instance.postponed shouldBe (null)69 }70 "not update scheduling if a task's next instance was already dismissed (non-repeating schedules)" {71 val after = after()72 val within = Duration.ofMinutes(5)73 val updatedTask = task.copy(74 schedule = Task.Schedule.Once(75 instant = LocalTime.of(0, 5).atDate(LocalDate.now()).toInstant(ZoneOffset.UTC)76 )77 )78 val schedule = TaskSchedule(updatedTask).update(after = after, within = within)79 schedule.task shouldBe (updatedTask)80 schedule.instances.size shouldBe (1)81 val instance = schedule.instances.values.first()82 val updatedSchedule = schedule.dismiss(instance = instance.id)83 updatedSchedule.task shouldBe (updatedTask)84 updatedSchedule.instances shouldBe (emptyMap())85 val finalSchedule = updatedSchedule.update(after = after, within = within)86 finalSchedule.task shouldBe (updatedTask)87 finalSchedule.instances shouldBe (emptyMap())88 }89 "support providing the next task instance" {90 val after = after()91 val within = Duration.ofMinutes(5)92 val schedule = TaskSchedule(task).update(after = after, within = within)93 schedule.instances.size shouldBe (1)94 val instance = schedule.instances.values.first()95 when (val next = schedule.next(after = after).firstOrNull()) {96 null -> fail("Expected next task instance but none found")97 else -> {98 next.first shouldBe (instance)99 next.second.isAfter(after) shouldBe (true)100 }101 }102 val multiInstanceSchedule = schedule103 .update(after = after.plus(Duration.ofMinutes(15)), within = within)104 .update(after = after.plus(Duration.ofMinutes(25)), within = within)105 .update(after = after.plus(Duration.ofMinutes(45)), within = within)106 multiInstanceSchedule.instances.size shouldBe (3)107 when (val next = multiInstanceSchedule.next(after = after).firstOrNull()) {108 null -> fail("Expected next task instance but none found")109 else -> {110 next.first shouldBe (instance)111 next.second.isAfter(after) shouldBe (true)112 }113 }114 val dismissedInstanceSchedule = TaskSchedule(115 task = task,116 instances = emptyMap(),117 dismissed = multiInstanceSchedule.instances.map { it.value.instant }118 ).update(after = after.plus(Duration.ofMinutes(45)), within = within)119 when (val next = dismissedInstanceSchedule.next(after = after).firstOrNull()) {120 null -> fail("Expected next task instance but none found")121 else -> {122 val every = (task.schedule as Task.Schedule.Repeating).every123 val duration = (every as Task.Schedule.Repeating.Interval.DurationInterval).value124 next.first.instant shouldBe (instance.instant.plus(duration.multipliedBy(3)))125 next.second.isAfter(after) shouldBe (true)126 }127 }128 }129 "support dismissing task instances" {130 val after = after()131 val within = Duration.ofMinutes(5)132 val schedule = TaskSchedule(task).update(after = after, within = within)133 schedule.instances.size shouldBe (1)134 val instance = schedule.instances.keys.first()135 val updatedSchedule = schedule.dismiss(instance)136 updatedSchedule.instances shouldBe (emptyMap())137 }138 "fail to dismiss missing task instances" {139 val schedule = TaskSchedule(task)140 val e = shouldThrow<IllegalArgumentException> {141 schedule.dismiss(instance = UUID.randomUUID())142 }143 e.message should startWith("Cannot dismiss instance")144 }145 "support undoing dismissal of task instances" {146 val after = after()147 val within = Duration.ofMinutes(5)148 val schedule = TaskSchedule(task).update(after = after, within = within)149 schedule.instances.size shouldBe (1)150 val instance = schedule.instances.values.first()151 val updatedSchedule = schedule.dismiss(instance.id)152 updatedSchedule.instances shouldBe (emptyMap())153 updatedSchedule.dismissed shouldBe (listOf(instance.instant))154 val latestSchedule = updatedSchedule.undoDismiss(instance.instant)155 latestSchedule.instances.size shouldBe (1)156 latestSchedule.dismissed shouldBe (emptyList())157 val newInstance = latestSchedule.instances.values.first()158 newInstance.id shouldNotBe (instance.id)159 newInstance.instant shouldBe (instance.instant)160 }161 "fail to undo dismissal of missing task instants" {162 val schedule = TaskSchedule(task)163 val e = shouldThrow<IllegalArgumentException> {164 schedule.undoDismiss(instant = Instant.now())165 }166 e.message should startWith("Cannot undo dismissal")167 }168 "support postponing task instances" {169 val after = after()170 val within = Duration.ofMinutes(5)171 val schedule = TaskSchedule(task).update(after = after, within = within)172 schedule.instances.size shouldBe (1)173 val instance = schedule.instances.values.first()174 instance.postponed shouldBe (null)175 val postponedDuration = Duration.ofMinutes(2)176 val updatedSchedule = schedule.postpone(instance = instance.id, by = postponedDuration)177 updatedSchedule.instances.size shouldBe (1)178 val updatedInstance = updatedSchedule.instances.values.first()179 updatedInstance.postponed shouldBe (postponedDuration)180 val finalSchedule = updatedSchedule.postpone(instance = instance.id, by = postponedDuration)181 finalSchedule.instances.size shouldBe (1)182 val finalInstance = finalSchedule.instances.values.first()183 finalInstance.postponed shouldBe (postponedDuration.multipliedBy(2))184 }185 "fail to postpone missing task instances" {186 val schedule = TaskSchedule(task)187 val e = shouldThrow<IllegalArgumentException> {188 schedule.postpone(instance = UUID.randomUUID(), by = Duration.ofSeconds(1))189 }190 e.message should startWith("Cannot postpone instance")191 }192 "support schedule matching" {193 val after = after()194 val within = Duration.ofMinutes(5)195 val tolerance = Duration.ofSeconds(2)196 val schedule = TaskSchedule(task)197 schedule.match(198 instant = after,199 withTolerance = tolerance200 ) shouldBe (emptyList())201 val updatedSchedule = schedule.update(after = after, within = within)202 updatedSchedule.instances.size shouldBe (1)203 val instance = updatedSchedule.instances.values.first()204 val diff = Duration.between(after, instance.execution())205 updatedSchedule.match(206 instant = after.minus(diff).minusSeconds(1),207 withTolerance = tolerance208 ) shouldBe (listOf(TaskSchedule.Matched.None))209 updatedSchedule.match(210 instant = after.plus(diff).minus(task.contextSwitch).plusSeconds(1),211 withTolerance = tolerance212 ) shouldBe (listOf(TaskSchedule.Matched.ContextSwitch(instance)))213 updatedSchedule.match(214 instant = after.plus(diff),215 withTolerance = tolerance216 ) shouldBe (listOf(TaskSchedule.Matched.Instant(instance)))217 }218 "support adjusting scheduling when a task's schedule is updated" {219 val now = Instant.now()220 val within = Duration.ofMinutes(5)221 val schedule = TaskSchedule(task)222 schedule.task shouldBe (task)223 schedule.instances shouldBe (emptyMap())224 val updatedSchedule = schedule225 .update(after = now.minus(Duration.ofMinutes(25)), within = within)226 .update(after = now.minus(Duration.ofMinutes(45)), within = within)227 .update(after = now, within = within)228 updatedSchedule.task shouldBe (task)229 updatedSchedule.instances.size shouldBe (3)230 val updatedTask = task.copy(231 schedule = Task.Schedule.Repeating(232 start = LocalTime.of(0, 5).atDate(LocalDate.now()).toInstant(ZoneOffset.UTC),233 every = Duration.ofMinutes(21).toInterval()234 )235 )236 val scheduleWithUpdatedTask = updatedSchedule.withTask(updatedTask)237 scheduleWithUpdatedTask.task shouldBe (updatedTask)238 scheduleWithUpdatedTask.instances.size shouldBe (2)239 scheduleWithUpdatedTask.instances.values.forEach { instance ->240 instance.execution().isBefore(now) shouldBe (true)241 }242 }243 "support adjusting scheduling when a task's state is updated" {244 val now = Instant.now()245 val within = Duration.ofMinutes(5)246 val schedule = TaskSchedule(task)247 schedule.task shouldBe (task)248 schedule.instances shouldBe (emptyMap())249 val updatedSchedule = schedule250 .update(after = now.minus(Duration.ofMinutes(25)), within = within)251 .update(after = now.minus(Duration.ofMinutes(45)), within = within)252 .update(after = now, within = within)253 updatedSchedule.task shouldBe (task)254 updatedSchedule.instances.size shouldBe (3)255 val updatedTask = task.copy(isActive = false)256 val scheduleWithUpdatedTask = updatedSchedule.withTask(updatedTask)257 scheduleWithUpdatedTask.task shouldBe (updatedTask)258 scheduleWithUpdatedTask.instances.size shouldBe (2)259 scheduleWithUpdatedTask.instances.values.forEach { instance ->260 instance.execution().isBefore(now) shouldBe (true)261 }262 }263 "not adjust scheduling when a task's details are updated" {264 val now = Instant.now()265 val within = Duration.ofMinutes(5)266 val schedule = TaskSchedule(task)267 schedule.task shouldBe (task)268 schedule.instances shouldBe (emptyMap())269 val updatedSchedule = schedule270 .update(after = now.minus(Duration.ofMinutes(25)), within = within)271 .update(after = now.minus(Duration.ofMinutes(45)), within = within)272 .update(after = now, within = within)273 updatedSchedule.task shouldBe (task)274 updatedSchedule.instances.size shouldBe (3)275 val updatedTask = task.copy(276 id = 1,277 name = "other-name",278 description = "other-description",279 goal = "other-goal",280 contextSwitch = Duration.ofMinutes(42)281 )282 val scheduleWithUpdatedTask = updatedSchedule.withTask(updatedTask)283 scheduleWithUpdatedTask.task shouldBe (updatedTask)284 scheduleWithUpdatedTask.instances.size shouldBe (3)285 }286 }...
MpInstantSpec.kt
Source:MpInstantSpec.kt
...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}...
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})...
HotelControllerTest.kt
Source:HotelControllerTest.kt
1package hotel2import arrow.core.Either3import hotel.exception.RoomNotExistException4import hotel.model.Booking5import io.kotest.assertions.arrow.core.shouldBeRight6import io.kotest.assertions.throwables.shouldThrowExactly7import io.kotest.inspectors.forExactly8import io.kotest.matchers.date.shouldBeAfter9import io.kotest.matchers.should10import io.kotest.matchers.string.include11import kotlinx.coroutines.DelicateCoroutinesApi12import kotlinx.coroutines.GlobalScope13import kotlinx.coroutines.async14import kotlinx.coroutines.runBlocking15import org.junit.jupiter.api.Test16import java.time.Clock17import java.time.LocalDate18import java.time.ZoneId19private const val THREADS = 100020private val DATE = LocalDate.of(2021, 11, 7)21private val zoneId = ZoneId.systemDefault()22private val clockYesterday = Clock.fixed(DATE.minusDays(1).atStartOfDay().atZone(zoneId).toInstant(), zoneId)23@DelicateCoroutinesApi24internal class HotelControllerTest {25 @Test26 fun clock() {27 val clock = Clock.systemDefaultZone()28 val instant = clock.instant()29 Thread.sleep(1)30 clock.instant() shouldBeAfter instant31 }32 @Test33 fun wrongRoomSize() {34 shouldThrowExactly<IllegalArgumentException> {35 HotelController(-1)36 }37 shouldThrowExactly<IllegalArgumentException> {38 HotelController(0)39 }40 }41 @Test42 fun bookingRoomNotExist() {43 shouldThrowExactly<RoomNotExistException> {44 val c = getController(1)45 c.bookRoom(DATE, 201, "guest")46 }.message should include("201 not exist")47 }48 @Test49 fun bookingFromPast() {50 shouldThrowExactly<BookingDateNotValidException> {51 val c = getController(1)52 c.bookRoom(LocalDate.MIN, 201, "guest")53 }.message should include(LocalDate.MIN.toString())54 }55 @Test56 fun bookingNullCheck() {57 shouldThrowExactly<NullPointerException> {58 Booking(null, 1, DATE)59 }.message should include("guestName")60 shouldThrowExactly<NullPointerException> {61 Booking("null", 1, null as LocalDate?)62 }.message should include("date")63 shouldThrowExactly<NullPointerException> {64 Booking("null", 1, null as String?)65 }.message should include("date")66 }67 @Test68 fun bookRoomConcurrency() = bookRoomsConcurrency(1)69 @Test70 fun book2RoomsConcurrency() = bookRoomsConcurrency(2)71 @Test72 fun bookXRoomsConcurrency() = repeat(3) { bookRoomsConcurrency((3..50).random(), (1..7).random()) }73 private fun bookRoomsConcurrency(74 size: Int,75 days: Int = 1,76 runConcurrently: (function: (Int) -> Either<Throwable, Any>) -> List<Either<Throwable, Any>> = ::run77 ) {78 val c = getController(size)79 val eitherList = runConcurrently { i: Int ->80// println("Thread $i start at: ${LocalTime.now()}")81 val plusDays = i / size % days82 val room = i % size + 183 val guestName = "guest-$i"84// println("$plusDays, $room, $guestName")85 Either.catch { c.bookRoom(DATE.plusDays(plusDays.toLong()), room, guestName) }86// .also { println("Thread $i end at: ${LocalTime.now()}") }87// .also { println("Result: $it") }88 }89 eitherList.forExactly(size * days) { it.shouldBeRight() }90 }91 private fun getController(size: Int): HotelController = HotelController(size).also { it.clock = clockYesterday }92 private fun run(createEither: (Int) -> Either<Throwable, Any>): List<Either<Throwable, Any>> {93 val deferredList = (1..THREADS).map { i -> GlobalScope.async { createEither(i) } }94 return runBlocking { deferredList.map { it.await() } }95 }96}...
instantMatcherTest.kt
Source:instantMatcherTest.kt
...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)61 val futureInstant = currentInstant.plusMillis(30000)62 pastInstant.shouldNotBeBetween(currentInstant, futureInstant)63 }...
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})...
DateTimeTests.kt
Source:DateTimeTests.kt
1import com.meowool.sweekt.datetime.nowDateTime2import com.meowool.sweekt.datetime.nowInstant3import com.meowool.sweekt.datetime.toDateTime4import io.kotest.core.spec.style.StringSpec5import io.kotest.matchers.kotlinx.datetime.shouldBeAfter6import io.kotest.matchers.kotlinx.datetime.shouldHaveSameDayAs7import io.kotest.matchers.kotlinx.datetime.shouldHaveSameMonthAs8import io.kotest.matchers.kotlinx.datetime.shouldHaveSameYearAs9import io.kotest.matchers.shouldBe10/**11 * Tests for /datetime12 *13 * @author å (RinOrz)14 */15class DateTimeTests : StringSpec({16 val instant = nowInstant17 val dateTime = nowDateTime18 "effective instant time" {19 val instantTime = instant.toDateTime()20 nowInstant shouldBeAfter instant21 dateTime shouldHaveSameYearAs instantTime22 dateTime shouldHaveSameMonthAs instantTime23 dateTime shouldHaveSameDayAs instantTime24 dateTime.second shouldBe instantTime.second25 }26})...
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!!