Best Kotest code snippet using io.kotest.matchers.ints.int.Int.shouldBeZero
BCounterTest.kt
Source:BCounterTest.kt
1/*2* Copyright © 2020, Concordant and contributors.3*4* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and5* associated documentation files (the "Software"), to deal in the Software without restriction,6* including without limitation the rights to use, copy, modify, merge, publish, distribute,7* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is8* furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice shall be included in all copies or11* substantial portions of the Software.12*13* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT14* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND15* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,16* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,17* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.18*/19package crdtlib.crdt20import crdtlib.utils.ClientUId21import crdtlib.utils.SimpleEnvironment22import io.kotest.assertions.throwables.shouldThrow23import io.kotest.core.spec.style.StringSpec24import io.kotest.matchers.ints.shouldBeZero25import io.kotest.matchers.shouldBe26/**27* Represents a suite test for BCounter.28**/29class BCounterTest : StringSpec({30 val uid1 = ClientUId("clientid1")31 val uid2 = ClientUId("clientid2")32 var client1 = SimpleEnvironment(uid1)33 var client2 = SimpleEnvironment(uid2)34 beforeTest {35 client1 = SimpleEnvironment(uid1)36 client2 = SimpleEnvironment(uid2)37 }38 "create and get value" {39 val cnt = BCounter()40 cnt.get().shouldBeZero()41 }42 "create and localRights value" {43 val cnt = BCounter()44 cnt.localRights(uid1).shouldBeZero()45 }46 "increment and get/localRights" {47 val inc = 1048 val cnt = BCounter(client1)49 cnt.increment(inc)50 cnt.get().shouldBe(10)51 cnt.localRights(uid1).shouldBe(10)52 }53 "failing decrement and get/localRights" {54 val cnt = BCounter(client1)55 shouldThrow<IllegalArgumentException> {56 cnt.decrement(10)57 }58 cnt.get().shouldBeZero()59 cnt.localRights(uid1).shouldBeZero()60 }61 "increment decrement and get/localRights" {62 val cnt = BCounter(client1)63 cnt.increment(15)64 cnt.decrement(6)65 cnt.get().shouldBe(9)66 cnt.localRights(uid1).shouldBe(9)67 }68 "failing negative increment and get" {69 val cnt = BCounter(client1)70 shouldThrow<IllegalArgumentException> {71 cnt.increment(-15)72 }73 cnt.get().shouldBeZero()74 cnt.localRights(uid1).shouldBeZero()75 }76 "positive increment, negative increment and get" {77 val cnt = BCounter(client1)78 cnt.increment(15)79 cnt.increment(-8)80 cnt.get().shouldBe(7)81 cnt.localRights(uid1).shouldBe(7)82 }83 "negative decrement and get" {84 val cnt = BCounter(client1)85 cnt.decrement(-15)86 cnt.get().shouldBe(15)87 cnt.localRights(uid1).shouldBe(15)88 }89 "multiple increments and get" {90 val cnt = BCounter(client1)91 cnt.increment(10)92 cnt.increment(1)93 cnt.increment(100)94 cnt.get().shouldBe(111)95 cnt.localRights(uid1).shouldBe(111)96 }97 "multiple failing decrements and get" {98 val cnt = BCounter(client1)99 shouldThrow<IllegalArgumentException> {100 cnt.decrement(10)101 }102 shouldThrow<IllegalArgumentException> {103 cnt.decrement(1)104 }105 shouldThrow<IllegalArgumentException> {106 cnt.decrement(100)107 }108 cnt.get().shouldBeZero()109 cnt.localRights(uid1).shouldBeZero()110 }111 "one increment, multiple decrements and get" {112 val cnt = BCounter(client1)113 cnt.increment(150)114 cnt.decrement(10)115 cnt.decrement(1)116 cnt.decrement(100)117 cnt.get().shouldBe(39)118 cnt.localRights(uid1).shouldBe(39)119 }120 "multiple (increment, decrement)" {121 val cnt = BCounter(client1)122 cnt.increment(15)123 cnt.get().shouldBe(15)124 cnt.localRights(uid1).shouldBe(15)125 cnt.decrement(5)126 cnt.get().shouldBe(10)127 cnt.localRights(uid1).shouldBe(10)128 cnt.increment(40)129 cnt.get().shouldBe(50)130 cnt.localRights(uid1).shouldBe(50)131 cnt.decrement(2)132 cnt.get().shouldBe(48)133 cnt.localRights(uid1).shouldBe(48)134 shouldThrow<IllegalArgumentException> {135 cnt.decrement(50)136 }137 }138 /* Merging */139 "R1: increment; R2: merge and get" {140 val cnt1 = BCounter(client1)141 val cnt2 = BCounter(client1)142 cnt1.increment(11)143 cnt2.merge(cnt1)144 cnt1.merge(cnt2)145 cnt1.get().shouldBe(11)146 cnt2.get().shouldBe(11)147 cnt1.localRights(uid1).shouldBe(11)148 cnt2.localRights(uid1).shouldBe(11)149 }150 "R1: increment; R2: increment, merge, get" {151 val cnt1 = BCounter(client1)152 val cnt2 = BCounter(client2)153 cnt1.increment(10)154 cnt2.increment(1)155 cnt2.merge(cnt1)156 cnt2.get().shouldBe(11)157 cnt1.localRights(uid1).shouldBe(10)158 cnt2.localRights(uid2).shouldBe(1)159 }160 "R1: increment; R2: merge, increment, get" {161 val cnt1 = BCounter(client1)162 val cnt2 = BCounter(client2)163 cnt1.increment(10)164 cnt2.merge(cnt1)165 cnt2.increment(1)166 cnt2.get().shouldBe(11)167 cnt1.localRights(uid1).shouldBe(10)168 cnt2.localRights(uid2).shouldBe(1)169 }170 "R1: multiple operations; R2: multiple operations, merge, get" {171 val cnt1 = BCounter(client1)172 val cnt2 = BCounter(client2)173 cnt1.increment(10)174 cnt1.decrement(10)175 cnt1.increment(30)176 cnt1.decrement(20)177 cnt2.increment(50)178 cnt2.decrement(30)179 cnt2.increment(70)180 cnt2.decrement(40)181 cnt2.merge(cnt1)182 cnt2.get().shouldBe(60)183 cnt1.localRights(uid1).shouldBe(10)184 cnt2.localRights(uid2).shouldBe(50)185 shouldThrow<IllegalArgumentException> {186 cnt1.decrement(20)187 }188 shouldThrow<IllegalArgumentException> {189 cnt2.decrement(60)190 }191 }192 "R1: multiple operations; R2: merge, multiple operations, get" {193 val cnt1 = BCounter(client1)194 val cnt2 = BCounter(client2)195 cnt1.increment(10)196 cnt1.decrement(10)197 cnt1.increment(30)198 cnt1.decrement(20)199 cnt2.merge(cnt1)200 cnt2.increment(50)201 cnt2.decrement(30)202 cnt2.increment(70)203 cnt2.decrement(40)204 cnt2.get().shouldBe(60)205 cnt1.localRights(uid1).shouldBe(10)206 cnt2.localRights(uid2).shouldBe(50)207 }208 /* Deltas */209 "use delta returned by increment" {210 val cnt1 = BCounter(client1)211 val cnt2 = BCounter(client1)212 val returnedIncOp = cnt1.increment(11)213 val incOp = client1.popWrite().second214 returnedIncOp.shouldBe(incOp)215 cnt2.merge(incOp)216 cnt1.merge(incOp)217 cnt2.get().shouldBe(11)218 cnt1.localRights(uid1).shouldBe(11)219 cnt2.localRights(uid1).shouldBe(11)220 }221 "use delta returned by increment and decrement" {222 val cnt1 = BCounter(client1)223 val cnt2 = BCounter(client1)224 val returnedIncOp = cnt1.increment(15)225 val incOp = client1.popWrite().second226 returnedIncOp.shouldBe(incOp)227 val returnedDecOp = cnt1.decrement(11)228 val decOp = client1.popWrite().second229 returnedDecOp.shouldBe(decOp)230 cnt2.merge(incOp)231 cnt1.merge(incOp)232 cnt2.merge(decOp)233 cnt1.merge(decOp)234 cnt1.get().shouldBe(4)235 cnt2.get().shouldBe(4)236 cnt1.localRights(uid1).shouldBe(4)237 cnt2.localRights(uid1).shouldBe(4)238 }239 "generate delta" {240 val cnt1 = BCounter(client1)241 val cnt2 = BCounter(client1)242 cnt1.increment(11)243 cnt1.increment(33)244 val vv = client1.getState()245 cnt2.merge(cnt1)246 cnt1.decrement(10)247 cnt1.decrement(20)248 val delta = cnt1.generateDelta(vv)249 cnt2.merge(delta)250 cnt2.get().shouldBe(14)251 cnt2.localRights(uid1).shouldBe(14)252 }253 /* Rights transfer */254 "rights transfer, one way" {255 val cnt1 = BCounter(client1)256 val cnt2 = BCounter(client1)257 cnt1.increment(20)258 cnt1.transfer(5, uid2)259 cnt2.merge(cnt1)260 cnt1.get().shouldBe(20)261 cnt2.get().shouldBe(20)262 cnt1.localRights(uid1).shouldBe(15)263 cnt2.localRights(uid2).shouldBe(5)264 }265 "two rights transfers, one way" {266 val cnt1 = BCounter(client1)267 val cnt2 = BCounter(client1)268 cnt1.increment(10)269 cnt1.transfer(6, uid2)270 cnt2.merge(cnt1)271 cnt1.get().shouldBe(10)272 cnt2.get().shouldBe(10)273 cnt1.localRights(uid1).shouldBe(4)274 cnt2.localRights(uid2).shouldBe(6)275 cnt1.transfer(4, uid2)276 cnt2.merge(cnt1)277 cnt1.get().shouldBe(10)278 cnt2.get().shouldBe(10)279 cnt1.localRights(uid1).shouldBe(0)280 cnt2.localRights(uid2).shouldBe(10)281 }282 "two rights transfers (one failing), one way" {283 val cnt1 = BCounter(client1)284 val cnt2 = BCounter(client2)285 cnt1.increment(10)286 cnt2.increment(30)287 cnt2.merge(cnt1)288 cnt1.merge(cnt2)289 cnt1.get().shouldBe(40)290 cnt2.get().shouldBe(40)291 cnt1.localRights(uid1).shouldBe(10)292 cnt2.localRights(uid2).shouldBe(30)293 cnt1.transfer(5, uid2)294 cnt2.merge(cnt1)295 cnt1.get().shouldBe(40)296 cnt2.get().shouldBe(40)297 cnt1.localRights(uid1).shouldBe(5)298 cnt2.localRights(uid2).shouldBe(35)299 shouldThrow<IllegalArgumentException> {300 cnt1.transfer(10, uid2)301 }302 cnt1.get().shouldBe(40)303 cnt2.get().shouldBe(40)304 cnt1.localRights(uid1).shouldBe(5)305 }306 "two way transfer" {307 val cnt1 = BCounter(client1)308 val cnt2 = BCounter(client2)309 cnt1.increment(10)310 cnt2.increment(30)311 cnt2.merge(cnt1)312 cnt1.merge(cnt2)313 cnt1.get().shouldBe(40)314 cnt2.get().shouldBe(40)315 cnt1.localRights(uid1).shouldBe(10)316 cnt2.localRights(uid2).shouldBe(30)317 cnt1.transfer(5, uid2)318 cnt2.merge(cnt1)319 cnt1.get().shouldBe(40)320 cnt2.get().shouldBe(40)321 cnt1.localRights(uid1).shouldBe(5)322 cnt2.localRights(uid2).shouldBe(35)323 cnt2.transfer(20, uid1)324 cnt1.merge(cnt2)325 cnt1.get().shouldBe(40)326 cnt2.get().shouldBe(40)327 cnt1.localRights(uid1).shouldBe(25)328 cnt2.localRights(uid2).shouldBe(15)329 }330 /* Overflow errors */331 "overflowing increment" {332 val cnt = BCounter(client1)333 cnt.increment(Int.MAX_VALUE)334 shouldThrow<ArithmeticException> {335 cnt.increment(1)336 }337 cnt.get().shouldBe(Int.MAX_VALUE)338 }339 "R1: increment; R2: increment, merge, overflowing get" {340 val cnt1 = BCounter(client1)341 val cnt2 = BCounter(client2)342 cnt1.increment(Int.MAX_VALUE)343 cnt2.increment(1)344 cnt2.merge(cnt1)345 shouldThrow<ArithmeticException> {346 cnt2.get()347 }348 }349 "overflowing rights transfer" {350 val cnt1 = BCounter(client1)351 val cnt2 = BCounter(client2)352 cnt1.increment(Int.MAX_VALUE)353 cnt2.increment(1)354 cnt2.transfer(1, uid1)355 cnt1.merge(cnt2)356 shouldThrow<ArithmeticException> {357 cnt1.localRights(uid1)358 }359 cnt1.transfer(1, uid2)360 cnt1.merge(cnt2)361 cnt1.localRights(uid1).shouldBe(Int.MAX_VALUE)362 cnt1.localRights(uid2).shouldBe(1)363 }364 "rights transfer, overflowing decrement" {365 val cnt1 = BCounter(client1)366 val cnt2 = BCounter(client2)367 cnt1.increment(Int.MAX_VALUE)368 cnt2.increment(1)369 cnt2.transfer(1, uid1)370 cnt1.merge(cnt2)371 cnt1.decrement(1)372 shouldThrow<ArithmeticException> {373 cnt1.decrement(Int.MAX_VALUE)374 }375 cnt1.get().shouldBe(Int.MAX_VALUE)376 }377 /* Serialization */378 "empty JSON serialization" {379 val cnt = BCounter(client1)380 val cntJson = cnt.toJson()381 cntJson.shouldBe("""{"type":"BCounter","metadata":{"increment":[],"decrement":[]},"value":0}""")382 }383 "empty JSON deserialization" {384 val cntJson = BCounter.fromJson("""{"type":"BCounter","metadata":{"increment":[],"decrement":[]},"value":0}""")385 cntJson.get().shouldBe(0)386 }387 "JSON serialization" {388 val cnt1 = BCounter(client1)389 val cnt2 = BCounter(client2)390 cnt1.increment(10)391 cnt1.decrement(5)392 cnt2.increment(30)393 cnt2.decrement(20)394 cnt2.transfer(2, uid1)395 cnt1.merge(cnt2)396 val cntJson = cnt1.toJson()397 cntJson.shouldBe("""{"type":"BCounter","metadata":{"increment":[{"name":"clientid1"},[{"name":"clientid1"},{"first":10,"second":{"uid":{"name":"clientid1"},"cnt":-2147483647}}],{"name":"clientid2"},[{"name":"clientid2"},{"first":30,"second":{"uid":{"name":"clientid2"},"cnt":-2147483647}},{"name":"clientid1"},{"first":2,"second":{"uid":{"name":"clientid2"},"cnt":-2147483645}}]],"decrement":[{"name":"clientid1"},{"first":5,"second":{"uid":{"name":"clientid1"},"cnt":-2147483646}},{"name":"clientid2"},{"first":20,"second":{"uid":{"name":"clientid2"},"cnt":-2147483646}}]},"value":15}""")398 }399 "JSON deserialization" {400 val cntJson = BCounter.fromJson(401 """{"type":"BCounter","metadata":{"increment":[{"name":"clientid1"},[{"name":"clientid1"},{"first":10,"second":{"uid":{"name":"clientid1"},"cnt":-2147483647}}],{"name":"clientid2"},[{"name":"clientid2"},{"first":30,"second":{"uid":{"name":"clientid2"},"cnt":-2147483647}},{"name":"clientid1"},{"first":2,"second":{"uid":{"name":"clientid2"},"cnt":-2147483645}}]],"decrement":[{"name":"clientid1"},{"first":5,"second":{"uid":{"name":"clientid1"},"cnt":-2147483646}},{"name":"clientid2"},{"first":20,"second":{"uid":{"name":"clientid2"},"cnt":-2147483646}}]},"value":15}""",402 client1403 )404 cntJson.get().shouldBe(15)405 cntJson.localRights(uid1).shouldBe(7)406 cntJson.localRights(uid2).shouldBe(8)407 }408})...
ConsumerControlVerticleTest.kt
Source:ConsumerControlVerticleTest.kt
1package ch.sourcemotion.vertx.kinesis.consumer.orchestra.impl2import ch.sourcemotion.vertx.kinesis.consumer.orchestra.ShardIteratorStrategy3import ch.sourcemotion.vertx.kinesis.consumer.orchestra.VertxKinesisOrchestraOptions4import ch.sourcemotion.vertx.kinesis.consumer.orchestra.consumer.KinesisConsumerVerticleOptions5import ch.sourcemotion.vertx.kinesis.consumer.orchestra.internal.service.ConsumerControlService6import ch.sourcemotion.vertx.kinesis.consumer.orchestra.internal.service.NodeScoreDto7import ch.sourcemotion.vertx.kinesis.consumer.orchestra.internal.service.NodeScoreService8import ch.sourcemotion.vertx.kinesis.consumer.orchestra.testing.AbstractRedisTest9import ch.sourcemotion.vertx.kinesis.consumer.orchestra.testing.TEST_APPLICATION_NAME10import ch.sourcemotion.vertx.kinesis.consumer.orchestra.testing.TEST_STREAM_NAME11import io.kotest.matchers.collections.shouldContainExactly12import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder13import io.kotest.matchers.ints.shouldBeZero14import io.kotest.matchers.nulls.shouldBeNull15import io.kotest.matchers.shouldBe16import io.vertx.core.AbstractVerticle17import io.vertx.core.Future18import io.vertx.core.Verticle19import io.vertx.core.json.JsonObject20import io.vertx.junit5.VertxTestContext21import io.vertx.kotlin.coroutines.CoroutineVerticle22import io.vertx.kotlin.coroutines.await23import kotlinx.coroutines.delay24import org.junit.jupiter.api.Test25import java.time.Duration26internal class ConsumerControlVerticleTest : AbstractRedisTest() {27 companion object {28 const val START_ACK_ADDR = "/consumer-control/test/start"29 const val STOP_ACK_ADDR = "/consumer-control/test/stop"30 }31 @Test32 internal fun start_one_consumer(testContext: VertxTestContext) = testContext.async {33 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))34 val startEventChannel = eventBusChannelOf<Unit>(START_ACK_ADDR)35 consumerControl.startConsumers(shardIds(1)).await().shouldBe(1)36 startEventChannel.receive()37 }38 @Test39 internal fun start_consumer_same_shard_two_times(testContext: VertxTestContext) = testContext.async {40 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))41 val shardIds = shardIds(1)42 val startEventChannel = eventBusChannelOf<Unit>(START_ACK_ADDR)43 consumerControl.startConsumers(shardIds).await().shouldBe(1)44 startEventChannel.receive()45 // Second start should be ignored46 consumerControl.startConsumers(shardIds).await().shouldBe(1)47 delay(1000)48 startEventChannel.tryReceive().getOrNull().shouldBeNull()49 }50 @Test51 internal fun start_ten_consumers(testContext: VertxTestContext) = testContext.async {52 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))53 val shardIds = shardIds(10)54 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)55 consumerControl.startConsumers(shardIds).await().shouldBe(shardIds.size)56 shardIds.forEach { shardId ->57 startEventChannel.receive().body().mapTo(KinesisConsumerVerticleOptions::class.java).shardId.shouldBe(58 shardId59 )60 }61 }62 @Test63 internal fun start_ten_consumers_than_stop_each(testContext: VertxTestContext) = testContext.async {64 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))65 val shardIds = shardIds(10)66 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)67 val stopEventChannel = eventBusChannelOf<JsonObject>(STOP_ACK_ADDR)68 consumerControl.startConsumers(shardIds).await().shouldBe(shardIds.size)69 shardIds.forEach { shardId ->70 startEventChannel.receive().body().mapTo(KinesisConsumerVerticleOptions::class.java)71 .shardId.shouldBe(shardId)72 }73 shardIds.forEachIndexed { idx, shardId ->74 val stopConsumersCmdResult = consumerControl.stopConsumers(1).await()75 stopConsumersCmdResult.activeConsumers.shouldBe(shardIds.size - (idx + 1))76 stopConsumersCmdResult.stoppedShardIds.shouldContainExactly(shardId)77 stopEventChannel.receive().body()78 .mapTo(KinesisConsumerVerticleOptions::class.java).shardId.shouldBe(shardId)79 }80 }81 @Test82 internal fun stop_not_started_consumers(testContext: VertxTestContext) = testContext.async {83 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))84 val startedShardId = ShardId("1")85 val notStartedShardId = ShardId("2")86 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)87 val stopEventChannel = eventBusChannelOf<JsonObject>(STOP_ACK_ADDR)88 consumerControl.startConsumers(listOf(startedShardId)).await().shouldBe(1)89 startEventChannel.receive()90 // Try to stop consumer of a shard for that never a consumer was started91 consumerControl.stopConsumer(notStartedShardId)92 delay(1000)93 stopEventChannel.tryReceive().getOrNull().shouldBeNull()94 }95 @Test96 internal fun start_stop_start_consumer(testContext: VertxTestContext) = testContext.async {97 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))98 val shardId = ShardId("1")99 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)100 val stopEventChannel = eventBusChannelOf<JsonObject>(STOP_ACK_ADDR)101 consumerControl.startConsumers(listOf(shardId)).await().shouldBe(1)102 startEventChannel.receive()103 consumerControl.stopConsumer(shardId)104 stopEventChannel.receive()105 consumerControl.startConsumers(listOf(shardId)).await().shouldBe(1)106 startEventChannel.receive()107 }108 @Test109 internal fun stop_more_than_started_consumers(testContext: VertxTestContext) = testContext.async {110 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))111 val shardIds = shardIds(10)112 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)113 consumerControl.startConsumers(shardIds).await().shouldBe(shardIds.size)114 shardIds.forEach { shardId ->115 startEventChannel.receive().body().mapTo(KinesisConsumerVerticleOptions::class.java).shardId.shouldBe(116 shardId117 )118 }119 val stopEventChannel = eventBusChannelOf<JsonObject>(STOP_ACK_ADDR)120 val stopConsumersCmdResult = consumerControl.stopConsumers(20).await()121 stopConsumersCmdResult.stoppedShardIds.shouldContainExactlyInAnyOrder(shardIds)122 stopConsumersCmdResult.activeConsumers.shouldBeZero()123 shardIds.forEach { shardId ->124 stopEventChannel.receive().body()125 .mapTo(KinesisConsumerVerticleOptions::class.java).shardId.shouldBe(shardId)126 }127 // Verify only 10 consumers are stopped128 delay(1000)129 stopEventChannel.tryReceive().getOrNull().shouldBeNull()130 }131 @Test132 internal fun force_latest_when_no_existing_sequence_number(testContext: VertxTestContext) = testContext.async {133 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))134 val shardId = ShardId("1")135 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)136 consumerControl.startConsumers(listOf(shardId)).await().shouldBe(1)137 val options = startEventChannel.receive().body().mapTo(KinesisConsumerVerticleOptions::class.java)138 options.shardId.shouldBe(shardId)139 options.shardIteratorStrategy.shouldBe(ShardIteratorStrategy.FORCE_LATEST)140 }141 @Test142 internal fun existing_or_latest_on_existing_sequence_number(testContext: VertxTestContext) = testContext.async {143 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartStopAckConsumerVerticle::class.java))144 val shardId = ShardId("1")145 shardStatePersistenceService.saveConsumerShardSequenceNumber(shardId, SequenceNumber("1", SequenceNumberIteratorPosition.AT))146 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)147 consumerControl.startConsumers(listOf(shardId)).await().shouldBe(1)148 val options = startEventChannel.receive().body().mapTo(KinesisConsumerVerticleOptions::class.java)149 options.shardId.shouldBe(shardId)150 options.shardIteratorStrategy.shouldBe(ShardIteratorStrategy.EXISTING_OR_LATEST)151 }152 @Test153 internal fun stop_failing_consumers(testContext: VertxTestContext) = testContext.async {154 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StopFailingConsumerVerticle::class.java))155 val shardIds = shardIds(10)156 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)157 consumerControl.startConsumers(shardIds).await().shouldBe(shardIds.size)158 shardIds.forEach { shardId ->159 startEventChannel.receive().body().mapTo(KinesisConsumerVerticleOptions::class.java).shardId.shouldBe(160 shardId161 )162 }163 val stopEventChannel = eventBusChannelOf<JsonObject>(STOP_ACK_ADDR)164 val stopConsumersCmdResult = consumerControl.stopConsumers(shardIds.size).await()165 stopConsumersCmdResult.stoppedShardIds.shouldContainExactlyInAnyOrder(shardIds)166 stopConsumersCmdResult.activeConsumers.shouldBeZero()167 shardIds.forEach { shardId ->168 stopEventChannel.receive().body()169 .mapTo(KinesisConsumerVerticleOptions::class.java).shardId.shouldBe(shardId)170 }171 }172 @Test173 internal fun start_failing_consumers(testContext: VertxTestContext) = testContext.async {174 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartFailingConsumerVerticle::class.java))175 val shardIds = shardIds(10)176 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)177 consumerControl.startConsumers(shardIds).await().shouldBeZero()178 shardIds.forEach { shardId ->179 startEventChannel.receive().body().mapTo(KinesisConsumerVerticleOptions::class.java).shardId.shouldBe(180 shardId181 )182 }183 }184 @Test185 internal fun start_timed_out_consumers(testContext: VertxTestContext) = testContext.async {186 val consumerControl = deployConsumerControl(consumerControlOptionsOf(StartTimeoutConsumerVerticle::class.java))187 val shardIds = shardIds(10)188 val startEventChannel = eventBusChannelOf<JsonObject>(START_ACK_ADDR)189 consumerControl.startConsumers(shardIds).await().shouldBeZero()190 shardIds.forEach { shardId ->191 startEventChannel.receive().body().mapTo(KinesisConsumerVerticleOptions::class.java).shardId.shouldBe(192 shardId193 )194 }195 }196 private fun shardIds(amount: Int) = IntRange(1, amount).map { ShardId("$it") }197 private suspend fun deployConsumerControl(198 options: ConsumerControlVerticle.Options199 ): ConsumerControlService {200 deployTestVerticle<ConsumerControlVerticle>(options)201 deployNodeScoreService()202 return ConsumerControlService.createService(vertx)203 }204 private suspend fun deployNodeScoreService() {205 NodeScoreService.exposeService(vertx, object : NodeScoreService {206 override fun setThisNodeScore(score: Int): Future<Void> = Future.succeededFuture()207 override fun getNodeScores(): Future<List<NodeScoreDto>> = Future.succeededFuture(emptyList())208 }).await()209 }210 private fun consumerControlOptionsOf(211 verticleClass: Class<out Verticle>,212 verticleOptions: JsonObject = JsonObject(),213 consumerDeploymentTimeoutMillis: Long = 1000,214 ) =215 VertxKinesisOrchestraOptions(216 applicationName = TEST_APPLICATION_NAME,217 streamName = TEST_STREAM_NAME,218 redisOptions = redisHeimdallOptions,219 consumerVerticleClass = verticleClass.name,220 consumerVerticleOptions = verticleOptions,221 shardIteratorStrategy = ShardIteratorStrategy.EXISTING_OR_LATEST,222 consumerDeploymentTimeout = Duration.ofMillis(consumerDeploymentTimeoutMillis)223 ).asConsumerControlOptions()224}225class StartStopAckConsumerVerticle : AbstractVerticle() {226 override fun start() {227 vertx.eventBus().send(ConsumerControlVerticleTest.START_ACK_ADDR, config())228 }229 override fun stop() {230 vertx.eventBus().send(ConsumerControlVerticleTest.STOP_ACK_ADDR, config())231 }232}233class StopFailingConsumerVerticle : AbstractVerticle() {234 override fun start() {235 vertx.eventBus().send(ConsumerControlVerticleTest.START_ACK_ADDR, config())236 }237 override fun stop() {238 vertx.eventBus().send(ConsumerControlVerticleTest.STOP_ACK_ADDR, config())239 throw Exception("Some failure")240 }241}242class StartFailingConsumerVerticle : AbstractVerticle() {243 override fun start() {244 vertx.eventBus().send(ConsumerControlVerticleTest.START_ACK_ADDR, config())245 throw Exception("Some failure")246 }247 override fun stop() {248 vertx.eventBus().send(ConsumerControlVerticleTest.STOP_ACK_ADDR, config())249 }250}251class StartTimeoutConsumerVerticle : CoroutineVerticle() {252 override suspend fun start() {253 vertx.eventBus().send(ConsumerControlVerticleTest.START_ACK_ADDR, config)254 delay(10000)255 }256}...
matchers.kt
Source:matchers.kt
1package tutorial.kotest2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.assertions.throwables.shouldThrowAny4import io.kotest.assertions.throwables.shouldThrowExactly5import io.kotest.core.spec.style.DescribeSpec6import io.kotest.core.test.AssertionMode7import io.kotest.matchers.booleans.shouldBeTrue8import io.kotest.matchers.collections.shouldBeIn9import io.kotest.matchers.collections.shouldBeOneOf10import io.kotest.matchers.collections.shouldBeSameSizeAs11import io.kotest.matchers.collections.shouldBeSingleton12import io.kotest.matchers.collections.shouldBeSmallerThan13import io.kotest.matchers.collections.shouldBeSorted14import io.kotest.matchers.collections.shouldBeUnique15import io.kotest.matchers.collections.shouldContain16import io.kotest.matchers.collections.shouldContainAll17import io.kotest.matchers.collections.shouldContainAnyOf18import io.kotest.matchers.collections.shouldContainDuplicates19import io.kotest.matchers.collections.shouldContainExactly20import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder21import io.kotest.matchers.collections.shouldContainInOrder22import io.kotest.matchers.collections.shouldContainNull23import io.kotest.matchers.collections.shouldEndWith24import io.kotest.matchers.collections.shouldHaveAtLeastSize25import io.kotest.matchers.collections.shouldHaveLowerBound26import io.kotest.matchers.collections.shouldHaveSingleElement27import io.kotest.matchers.collections.shouldHaveSize28import io.kotest.matchers.collections.shouldHaveUpperBound29import io.kotest.matchers.collections.shouldNotContainAnyOf30import io.kotest.matchers.collections.shouldNotHaveElementAt31import io.kotest.matchers.collections.shouldStartWith32import io.kotest.matchers.comparables.shouldBeEqualComparingTo33import io.kotest.matchers.comparables.shouldBeLessThanOrEqualTo34import io.kotest.matchers.date.shouldBeToday35import io.kotest.matchers.date.shouldHaveSameHoursAs36import io.kotest.matchers.doubles.Percentage37import io.kotest.matchers.doubles.beNaN38import io.kotest.matchers.doubles.plusOrMinus39import io.kotest.matchers.doubles.shouldBeNaN40import io.kotest.matchers.doubles.shouldNotBeNaN41import io.kotest.matchers.equality.shouldBeEqualToComparingFields42import io.kotest.matchers.equality.shouldBeEqualToComparingFieldsExcept43import io.kotest.matchers.equality.shouldBeEqualToIgnoringFields44import io.kotest.matchers.equality.shouldBeEqualToUsingFields45import io.kotest.matchers.file.shouldBeADirectory46import io.kotest.matchers.file.shouldBeAbsolute47import io.kotest.matchers.file.shouldExist48import io.kotest.matchers.file.shouldNotBeEmpty49import io.kotest.matchers.ints.beOdd50import io.kotest.matchers.ints.shouldBeBetween51import io.kotest.matchers.ints.shouldBeInRange52import io.kotest.matchers.ints.shouldBeLessThan53import io.kotest.matchers.ints.shouldBeLessThanOrEqual54import io.kotest.matchers.ints.shouldBeOdd55import io.kotest.matchers.ints.shouldBePositive56import io.kotest.matchers.ints.shouldBeZero57import io.kotest.matchers.iterator.shouldBeEmpty58import io.kotest.matchers.iterator.shouldHaveNext59import io.kotest.matchers.maps.shouldBeEmpty60import io.kotest.matchers.maps.shouldContain61import io.kotest.matchers.maps.shouldContainAll62import io.kotest.matchers.maps.shouldContainExactly63import io.kotest.matchers.maps.shouldContainKey64import io.kotest.matchers.nulls.shouldBeNull65import io.kotest.matchers.nulls.shouldNotBeNull66import io.kotest.matchers.shouldBe67import io.kotest.matchers.shouldNot68import io.kotest.matchers.shouldNotBe69import io.kotest.matchers.string.beEmpty70import io.kotest.matchers.string.shouldBeBlank71import io.kotest.matchers.string.shouldBeEmpty72import io.kotest.matchers.string.shouldBeEqualIgnoringCase73import io.kotest.matchers.string.shouldBeInteger74import io.kotest.matchers.string.shouldBeLowerCase75import io.kotest.matchers.string.shouldBeUpperCase76import io.kotest.matchers.string.shouldContain77import io.kotest.matchers.string.shouldContainADigit78import io.kotest.matchers.string.shouldContainIgnoringCase79import io.kotest.matchers.string.shouldContainOnlyDigits80import io.kotest.matchers.string.shouldContainOnlyOnce81import io.kotest.matchers.string.shouldEndWith82import io.kotest.matchers.string.shouldHaveLength83import io.kotest.matchers.string.shouldHaveLineCount84import io.kotest.matchers.string.shouldHaveMaxLength85import io.kotest.matchers.string.shouldHaveMinLength86import io.kotest.matchers.string.shouldHaveSameLengthAs87import io.kotest.matchers.string.shouldMatch88import io.kotest.matchers.string.shouldNotBeEmpty89import io.kotest.matchers.string.shouldStartWith90import io.kotest.matchers.throwable.shouldHaveCause91import io.kotest.matchers.throwable.shouldHaveCauseInstanceOf92import io.kotest.matchers.throwable.shouldHaveCauseOfType93import io.kotest.matchers.throwable.shouldHaveMessage94import io.kotest.matchers.types.shouldBeInstanceOf95import io.kotest.matchers.types.shouldBeSameInstanceAs96import io.kotest.matchers.types.shouldBeTypeOf97import io.kotest.matchers.uri.shouldHaveHost98import io.kotest.matchers.uri.shouldHavePort99import io.kotest.matchers.uri.shouldHaveScheme100import java.io.File101import java.net.URI102import java.time.LocalDate103import java.time.LocalTime104// https://kotest.io/docs/assertions/core-matchers.html105class MatchersTest : DescribeSpec({106 describe("general") {107 it("basics") {108 (1 == 1).shouldBeTrue()109 (2 + 2) shouldBe 4110 val foo: Any = "foobar"111 foo.shouldBeTypeOf<String>() shouldContain "fo"112 "".shouldBeEmpty()113 "x".shouldNot(beEmpty()) // manually negate114 "x".shouldNotBeEmpty() // reusable115 URI("https://tba") shouldHaveHost "tba"116 URI("https://tba:81") shouldHavePort 81117 URI("https://tba") shouldHaveScheme "https"118 File("/").apply {119 shouldExist()120 shouldBeADirectory()121 shouldBeAbsolute()122 shouldNotBeEmpty()123 }124 // executable, hidden, readable, smaller, writeable, containFile, extension, path, ...125 LocalDate.now().shouldBeToday()126 // before/after, within, same, between, have year/month/day/hour/...127 LocalTime.now().shouldHaveSameHoursAs(LocalTime.now())128 // before/after/between, sameMinute/Seconds/Nanos129 }130 it("numbers") {131 1 shouldBeLessThan 2132 1 shouldBeLessThanOrEqual 1 // Int-based; returns this133 1 shouldBeLessThanOrEqualTo 1 // Comparble-based; void134 1 shouldBeEqualComparingTo 1 // Comparable-based135 1.shouldBeBetween(0, 2)136 1 shouldBeInRange 0..2137 0.shouldBeZero()138 1.shouldBePositive()139 1.shouldBeOdd()140 (1.2).shouldBe(1.20001.plusOrMinus(Percentage(20.0)))141 (1.2).shouldNotBeNaN()142 }143 it("strings") {144 // generic: "abc" shouldBe "abc"145 "aBc" shouldBeEqualIgnoringCase "abc"146 "".shouldBeEmpty()147 " ".shouldBeBlank() // empty or whitespace148 "abc" shouldContain ("b")149 "aBc" shouldContainIgnoringCase "bc"150 "x-a-x" shouldContain """\-[a-z]\-""".toRegex()151 "-a-" shouldMatch """\-[a-z]\-""".toRegex()152 "abc" shouldStartWith ("a")153 "abc" shouldEndWith ("c")154 "ab aa" shouldContainOnlyOnce "aa"155 "abc".shouldBeLowerCase()156 "ABC".shouldBeUpperCase()157 "abc" shouldHaveLength 3158 "a\nb" shouldHaveLineCount 2159 "ab" shouldHaveMinLength 1 shouldHaveMaxLength 3160 "abc" shouldHaveSameLengthAs "foo"161 "1".shouldBeInteger()162 "12".shouldContainOnlyDigits()163 "abc1".shouldContainADigit() // at least one164 }165 it("types") {166 @Connotation167 open class SuperType()168 class SubType : SuperType()169 val sameRef = SuperType()170 sameRef.shouldBeSameInstanceAs(sameRef)171 val superType: SuperType = SubType()172 superType.shouldBeTypeOf<SubType>() // exact runtime match (SuperType won't work!)173 superType.shouldBeInstanceOf<SuperType>() // T or below174// SubType().shouldHaveAnnotation(Connotation::class)175 val nullable: String? = null176 nullable.shouldBeNull()177 }178 it("collections") {179 emptyList<Int>().iterator().shouldBeEmpty()180 listOf(1).iterator().shouldHaveNext()181 listOf(1, 2) shouldContain 1 // at least182 listOf(1, 2) shouldContainExactly listOf(1, 2) // in-order; not more183 listOf(1, 2) shouldContainExactlyInAnyOrder listOf(2, 1) // out-order; not more184 listOf(0, 3, 0, 4, 0).shouldContainInOrder(3, 4) // possible items in between185 listOf(1) shouldNotContainAnyOf listOf(2, 3) // black list186 listOf(1, 2, 3) shouldContainAll listOf(3, 2) // out-order; more187 listOf(1, 2, 3).shouldBeUnique() // no duplicates188 listOf(1, 2, 2).shouldContainDuplicates() // at least one duplicate189 listOf(1, 2).shouldNotHaveElementAt(1, 3)190 listOf(1, 2) shouldStartWith 1191 listOf(1, 2) shouldEndWith 2192 listOf(1, 2) shouldContainAnyOf listOf(2, 3)193 val x = SomeType(1)194 x shouldBeOneOf listOf(x) // by reference/instance195 x shouldBeIn listOf(SomeType(1)) // by equality/structural196 listOf(1, 2, null).shouldContainNull()197 listOf(1) shouldHaveSize 1198 listOf(1).shouldBeSingleton() // size == 1199 listOf(1).shouldBeSingleton {200 it.shouldBeOdd()201 }202 listOf(1).shouldHaveSingleElement {203 beOdd().test(it).passed() // have to return a boolean here :-/204 }205 listOf(2, 3) shouldHaveLowerBound 1 shouldHaveUpperBound 4206 listOf(1) shouldBeSmallerThan listOf(1, 2)207 listOf(1) shouldBeSameSizeAs listOf(2)208 listOf(1, 2) shouldHaveAtLeastSize 1209 listOf(1, 2).shouldBeSorted()210 mapOf(1 to "a").shouldContain(1, "a") // at least this211 mapOf(1 to "a") shouldContainAll mapOf(1 to "a") // at least those212 mapOf(1 to "a") shouldContainExactly mapOf(1 to "a") // not more213 mapOf(1 to "a") shouldContainKey 1214 emptyMap<Any, Any>().shouldBeEmpty()215 }216 it("exceptions") {217 class SubException() : Exception()218 Exception("a") shouldHaveMessage "a" // same (not contains!)219 Exception("abc").message shouldContain "b"220 Exception("", Exception()).shouldHaveCause()221 Exception("symptom", Exception("cause")).shouldHaveCause {222 it.message shouldBe "cause"223 }224 Exception("", SubException()).shouldHaveCauseInstanceOf<Exception>() // T or subclass225 Exception("", SubException()).shouldHaveCauseOfType<SubException>() // exactly T226 shouldThrow<Exception> { // type or subtype227 throw SubException()228 }229 shouldThrowExactly<Exception> { // exactly that type (no subtype!)230 throw Exception()231 }232 shouldThrowAny { // don't care which233 throw Exception()234 }235 }236 }237 describe("advanced") {238 it("selective matcheres") {239 data class Foo(val p1: Int, val p2: Int)240 val foo1 = Foo(1, 1)241 val foo2 = Foo(1, 2)242 foo1.shouldBeEqualToUsingFields(foo2, Foo::p1)243 foo1.shouldBeEqualToIgnoringFields(foo2, Foo::p2)244 class Bar(val p1: Int, val p2: Int) // not a data class! no equals.245 val bar1a = Bar(1, 1)246 val bar1b = Bar(1, 1)247 bar1a shouldNotBe bar1b248 bar1a shouldBeEqualToComparingFields bar1b // "fake equals" (ignoring private properties)249 bar1a.shouldBeEqualToComparingFields(bar1b, false) // explicitly also check private props250 val bar2 = Bar(1, 2)251 bar1a.shouldBeEqualToComparingFieldsExcept(bar2, Bar::p2)252 }253 }254 // channels255 // concurrent, futures256 // result, optional257 // threads258 // reflection259 // statistic, regex260})261private data class SomeType(val value: Int = 1)262private annotation class Connotation...
ByteBufferInputStreamTest.kt
Source:ByteBufferInputStreamTest.kt
1/*2 * Copyright (C) 2022 Edgar Asatryan3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package io.github.nstdio.http.ext17import io.kotest.assertions.throwables.shouldThrowExactly18import io.kotest.matchers.booleans.shouldBeTrue19import io.kotest.matchers.collections.shouldBeEmpty20import io.kotest.matchers.ints.shouldBeZero21import io.kotest.matchers.shouldBe22import io.kotest.matchers.throwable.shouldHaveMessage23import io.kotest.property.Arb24import io.kotest.property.arbitrary.int25import io.kotest.property.arbitrary.next26import org.assertj.core.api.Assertions.assertThat27import org.assertj.core.api.Assertions.assertThatIOException28import org.junit.jupiter.api.Assertions29import org.junit.jupiter.api.Assertions.assertEquals30import org.junit.jupiter.api.Assertions.assertThrows31import org.junit.jupiter.api.Named32import org.junit.jupiter.api.RepeatedTest33import org.junit.jupiter.api.Test34import org.junit.jupiter.params.ParameterizedTest35import org.junit.jupiter.params.provider.MethodSource36import java.io.ByteArrayOutputStream37import java.io.IOException38import java.util.stream.IntStream39import java.util.stream.Stream40internal class ByteBufferInputStreamTest {41 private val arbByteBuffer = Arb.byteBuffer(Arb.int(8..32))42 private val arbByteArray = Arb.byteArray(Arb.int(16, 48))43 @ParameterizedTest44 @MethodSource("fullReadingData")45 fun fullReading(bytes: ByteArray) {46 //given47 val s = ByteBufferInputStream()48 Helpers.toBuffers(bytes).forEach(s::add)49 //when50 val available = s.available()51 val actual = s.readAllBytes()52 //then53 available shouldBe bytes.size54 actual.shouldBe(bytes)55 }56 @Test57 fun shouldReturnNegativeWhenInputIsEmpty() {58 //given59 val stream = ByteBufferInputStream()60 stream.add(arbByteBuffer.next())61 //when62 val actual = stream.read(ByteArray(0))63 //then64 actual.shouldBeZero()65 }66 @RepeatedTest(4)67 fun shouldReadSingleProperly() {68 //given69 val s = ByteBufferInputStream()70 val bytes = arbByteArray.next()71 Helpers.toBuffers(bytes).forEach(s::add)72 val out = ByteArrayOutputStream()73 //when74 var read: Int75 while (s.read().also { read = it } != -1) {76 out.write(read)77 }78 //then79 s.read().shouldBe(-1)80 out.toByteArray().shouldBe(bytes)81 }82 @Test83 fun shouldFlipBuffer() {84 //given85 val bytes = arbByteArray.next()86 val stream = ByteBufferInputStream()87 Helpers.toBuffers(bytes)88 .map { it.position(it.limit()) }89 .forEach(stream::add)90 stream.add(ByteArray(0).toBuffer())91 //when92 val actual = stream.readAllBytes()93 //then94 Assertions.assertArrayEquals(bytes, actual)95 }96 @Test97 fun shouldThrowWhenClosed() {98 //given99 val s = ByteBufferInputStream()100 //when101 s.close()102 //then103 assertThatIOException().isThrownBy { s.read() }104 assertThatIOException().isThrownBy { s.read(ByteArray(0)) }105 assertThatIOException().isThrownBy { s.read(ByteArray(5), 0, 5) }106 assertThatIOException().isThrownBy { s.readAllBytes() }107 assertThatIOException().isThrownBy { s.available() }108 }109 @Test110 fun shouldReportAvailable() {111 //given112 val bytes = arbByteArray.next()113 val s = ByteBufferInputStream()114 Helpers.toBuffers(bytes).forEach(s::add)115 //when116 val actual = s.available()117 //then118 assertEquals(bytes.size, actual)119 }120 @Test121 fun shouldReadAllBytes() {122 //given123 val bytes = arbByteArray.next()124 val s = ByteBufferInputStream()125 Helpers.toBuffers(bytes).forEach(s::add)126 //when127 val actual = s.readAllBytes()128 //then129 actual.shouldBe(bytes)130 }131 @Test132 fun shouldThrowWhenRequestedBytesNegative() {133 //given134 val `is` = ByteBufferInputStream()135 //when + then136 assertThrows(IllegalArgumentException::class.java) { `is`.readNBytes(-1) }137 }138 @Test139 fun shouldReadUpToNBytes() {140 //given141 val bytes = arbByteArray.next()142 val count = bytes.size143 val s = ByteBufferInputStream()144 Helpers.toBuffers(bytes).forEach(s::add)145 //when146 val actual = s.readNBytes(count + 1)147 //then148 Assertions.assertArrayEquals(bytes, actual)149 }150 @Test151 fun shouldSupportMark() {152 //given + when + then153 ByteBufferInputStream().markSupported().shouldBeTrue()154 }155 @Test156 fun shouldDumpBuffersToList() {157 //given158 val s = ByteBufferInputStream()159 val buffers = Helpers.toBuffers(arbByteArray.next())160 buffers.forEach(s::add)161 //when162 val actual = s.drainToList()163 //then164 assertEquals(-1, s.read())165 assertThat(actual)166 .hasSameSizeAs(buffers)167 .containsExactlyElementsOf(buffers)168 }169 @Test170 fun `Should not add when closed`() {171 //given172 val s = ByteBufferInputStream().also { it.close() }173 //when174 s.add(arbByteBuffer.next())175 //then176 s.drainToList().shouldBeEmpty()177 }178 @Test179 fun `Should throw when reset called but not marked`() {180 //given181 val s = ByteBufferInputStream()182 //when + then183 shouldThrowExactly<IOException>(s::reset)184 .shouldHaveMessage("nothing to reset")185 }186 @Test187 fun `Should restore marked on reset`() {188 //given189 val bytes = "abcd".toByteArray()190 val s = ByteBufferInputStream().also { it.add(bytes.toBuffer()) }191 //when192 s.mark(2)193 s.read(); s.read()194 s.reset()195 //then196 s.read().shouldBe(bytes[0])197 s.read().shouldBe(bytes[1])198 }199 @Test200 fun `Should drop mark when read limit exceeds`() {201 //given202 val bytes = "abcd".toByteArray()203 val s = ByteBufferInputStream().also { it.add(bytes.toBuffer()) }204 //when205 s.mark(1)206 s.read(); s.read()207 //then208 s.read().shouldBe(bytes[2])209 s.read().shouldBe(bytes[3])210 }211 @Test212 fun `Should drop mark when limit is negative`() {213 //given214 val bytes = "abcd".toByteArray()215 val s = ByteBufferInputStream().also { it.add(bytes.toBuffer()) }216 //when217 s.mark(1)218 s.mark(-1)219 //then220 s.read().shouldBe(bytes[0])221 shouldThrowExactly<IOException> { s.reset() }222 .shouldHaveMessage("nothing to reset")223 }224 companion object {225 @JvmStatic226 fun fullReadingData(): Stream<Named<ByteArray>> {227 return IntStream.of(8192, 16384, 65536)228 .mapToObj { n: Int ->229 Named.named(230 "Size: $n", Arb.byteArray(n).next()231 )232 }233 }234 }235}...
KotestAsserts.kt
Source:KotestAsserts.kt
1package testing.asserts2import arrow.core.*3import io.kotest.assertions.arrow.either.shouldBeLeft4import io.kotest.assertions.arrow.either.shouldBeRight5import io.kotest.assertions.arrow.nel.shouldContain6import io.kotest.assertions.arrow.nel.shouldContainNull7import io.kotest.assertions.arrow.option.shouldBeNone8import io.kotest.assertions.arrow.option.shouldBeSome9import io.kotest.assertions.arrow.validation.shouldBeInvalid10import io.kotest.assertions.arrow.validation.shouldBeValid11import io.kotest.assertions.asClue12import io.kotest.assertions.json.*13import io.kotest.assertions.throwables.shouldThrowAny14import io.kotest.assertions.throwables.shouldThrowExactly15import io.kotest.assertions.withClue16import io.kotest.matchers.Matcher17import io.kotest.matchers.MatcherResult18import io.kotest.matchers.booleans.shouldBeFalse19import io.kotest.matchers.booleans.shouldBeTrue20import io.kotest.matchers.collections.shouldBeEmpty21import io.kotest.matchers.collections.shouldBeOneOf22import io.kotest.matchers.collections.shouldBeSameSizeAs23import io.kotest.matchers.collections.shouldBeSorted24import io.kotest.matchers.collections.shouldContain25import io.kotest.matchers.date.shouldBeAfter26import io.kotest.matchers.ints.shouldBeEven27import io.kotest.matchers.ints.shouldBeGreaterThan28import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual29import io.kotest.matchers.ints.shouldBeLessThan30import io.kotest.matchers.ints.shouldBeLessThanOrEqual31import io.kotest.matchers.ints.shouldBeZero32import io.kotest.matchers.maps.shouldBeEmpty33import io.kotest.matchers.maps.shouldContain34import io.kotest.matchers.maps.shouldContainKey35import io.kotest.matchers.maps.shouldContainValue36import io.kotest.matchers.nulls.shouldBeNull37import io.kotest.matchers.should38import io.kotest.matchers.shouldBe39import io.kotest.matchers.shouldNot40import io.kotest.matchers.string.shouldBeBlank41import io.kotest.matchers.string.shouldBeEmpty42import io.kotest.matchers.string.shouldBeUpperCase43import io.kotest.matchers.string.shouldContain44import io.kotest.matchers.string.shouldNotBeBlank45import java.time.LocalDate46import org.junit.jupiter.api.Test47/**48 * Kotest assertions49 *50 * - [Kotest Assertions Documentation](https://kotest.io/assertions/)51 * - [Github](https://github.com/kotest/kotest/)52 */53class KotestAsserts {54 @Test55 fun `General assertions`() {56 "text" shouldBe "text"57 " ".shouldBeBlank()58 "hi".shouldNotBeBlank()59 "".shouldBeEmpty()60 "HI".shouldBeUpperCase()61 "hello".shouldContain("ll")62 true.shouldBeTrue()63 false.shouldBeFalse()64 null.shouldBeNull()65 10 shouldBeLessThan 1166 10 shouldBeLessThanOrEqual 1067 11 shouldBeGreaterThan 1068 11 shouldBeGreaterThanOrEqual 1169 10.shouldBeEven()70 0.shouldBeZero()71 }72 @Test73 fun `Exception assertions`() {74 shouldThrowExactly<IllegalStateException> {75 angryFunction()76 }77 shouldThrowAny {78 angryFunction()79 }80 }81 @Test82 fun `Collection assertions`() {83 emptyList<Int>().shouldBeEmpty()84 listOf(1, 2, 3) shouldContain 385 listOf(1, 2, 3).shouldBeSorted()86 listOf(1, 2, 3) shouldBeSameSizeAs listOf(4, 5, 6)87 1 shouldBeOneOf listOf(1, 2, 3)88 emptyMap<Int, String>().shouldBeEmpty()89 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainKey 190 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainValue "two"91 mapOf(1 to "one", 2 to "two", 3 to "three") shouldContain (3 to "three")92 }93 @Test94 fun `Arrow assertions`() {95 val optionNone = none<String>()96 val optionSome = Some("I am something").toOption()97 optionNone.shouldBeNone()98 optionSome.shouldBeSome()99 val rightEither = Either.Right(1)100 val leftEither = Either.Left("ERROR!!")101 rightEither.shouldBeRight()102 rightEither shouldBeRight 1103 leftEither.shouldBeLeft()104 leftEither shouldBeLeft "ERROR!!"105 val nonEmptyList = NonEmptyList.of(1, 2, 3, 4, 5, null)106 nonEmptyList shouldContain 1107 nonEmptyList.shouldContainNull()108 val valid = Validated.valid()109 val invalid = Validated.invalid()110 valid.shouldBeValid()111 invalid.shouldBeInvalid()112 }113 @Test114 fun `Json assertions`() {115 val jsonString = "{\"test\": \"property\", \"isTest\": true }"116 jsonString shouldMatchJson jsonString117 jsonString shouldContainJsonKey "$.test"118 jsonString shouldNotContainJsonKey "$.notTest"119 jsonString.shouldContainJsonKeyValue("$.isTest", true)120 }121 @Test122 fun `Custom assertions`() {123 val sentMail = Mail(124 dateCreated = LocalDate.of(2020, 10, 27),125 sent = true, message = "May you have an amazing day"126 )127 val unsentMail = Mail(128 dateCreated = LocalDate.of(2020, 10, 27),129 sent = false, message = "May you have an amazing day"130 )131 // This is possible132 sentMail.sent should beSent()133 unsentMail.sent shouldNot beSent()134 // This is recommended135 sentMail.shouldBeSent()136 unsentMail.shouldNotBeSent()137 }138 @Test139 fun `withClue usage`() {140 val mail = Mail(141 dateCreated = LocalDate.of(2020, 10, 27),142 sent = false, message = "May you have an amazing day"143 )144 withClue("sent field should be false") {145 mail.sent shouldBe false146 }147 mail.asClue {148 it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)149 it.sent shouldBe false150 }151 }152 @Test153 fun `asClue usage`() {154 val mail = Mail(155 dateCreated = LocalDate.of(2020, 10, 27),156 sent = false, message = "May you have an amazing day"157 )158 mail.asClue {159 it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)160 it.sent shouldBe false161 }162 }163 fun beSent() = object : Matcher<Boolean> {164 override fun test(value: Boolean) = MatcherResult(value, "Mail.sent should be true", "Mail.sent should be false")165 }166 fun Mail.shouldBeSent() = this.sent should beSent()167 fun Mail.shouldNotBeSent() = this.sent shouldNot beSent()168}169data class Mail(val dateCreated: LocalDate, val sent: Boolean, val message: String)170fun angryFunction() {171 throw IllegalStateException("How dare you!")172}...
IntMatchersTest.kt
Source:IntMatchersTest.kt
1package com.sksamuel.kotest.matchers.numerics2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.matchers.ints.beEven4import io.kotest.matchers.ints.beOdd5import io.kotest.matchers.ints.shouldBeBetween6import io.kotest.matchers.ints.shouldBeGreaterThan7import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual8import io.kotest.matchers.ints.shouldBeLessThan9import io.kotest.matchers.ints.shouldBeLessThanOrEqual10import io.kotest.matchers.ints.shouldBeNegative11import io.kotest.matchers.ints.shouldBePositive12import io.kotest.matchers.ints.shouldBeZero13import io.kotest.matchers.ints.shouldNotBeZero14import io.kotest.core.spec.style.StringSpec15import io.kotest.matchers.should16import io.kotest.matchers.shouldBe17import io.kotest.matchers.shouldNot18import io.kotest.matchers.shouldNotBe19import io.kotest.data.forAll20import io.kotest.data.forNone21import io.kotest.data.headers22import io.kotest.data.row23import io.kotest.data.table24class IntMatchersTest : StringSpec() {25 init {26 "be positive" {27 1.shouldBePositive()28 shouldThrow<AssertionError> {29 (-1).shouldBePositive()30 }.message shouldBe "-1 should be > 0"31 shouldThrow<AssertionError> {32 (0).shouldBePositive()33 }.message shouldBe "0 should be > 0"34 }35 "be negative" {36 (-1).shouldBeNegative()37 shouldThrow<AssertionError> {38 1.shouldBeNegative()39 }.message shouldBe "1 should be < 0"40 shouldThrow<AssertionError> {41 0.shouldBeNegative()42 }.message shouldBe "0 should be < 0"43 }44 "should return expected/actual in intellij format" {45 shouldThrow<AssertionError> {46 1 shouldBe 44447 }.message shouldBe "expected:<444> but was:<1>"48 }49 "shouldBe should support ints" {50 1 shouldBe 151 }52 "isEven" {53 4 shouldBe beEven()54 3 shouldNotBe beEven()55 }56 "isOdd" {57 3 shouldBe beOdd()58 4 shouldNotBe beOdd()59 }60 "inRange" {61 3 should io.kotest.matchers.ints.beInRange(1..10)62 3 should io.kotest.matchers.ints.beInRange(3..10)63 3 should io.kotest.matchers.ints.beInRange(3..3)64 4 shouldNot io.kotest.matchers.ints.beInRange(3..3)65 4 shouldNot io.kotest.matchers.ints.beInRange(1..3)66 }67 "beGreaterThan" {68 1 should io.kotest.matchers.ints.beGreaterThan(0)69 3.shouldBeGreaterThan(2)70 shouldThrow<AssertionError> {71 2 should io.kotest.matchers.ints.beGreaterThan(3)72 }73 }74 "beLessThan" {75 1 should io.kotest.matchers.ints.beLessThan(2)76 1.shouldBeLessThan(2)77 shouldThrow<AssertionError> {78 2 shouldBe io.kotest.matchers.ints.lt(1)79 }80 }81 "beLessThanOrEqualTo" {82 1 should io.kotest.matchers.ints.beLessThanOrEqualTo(2)83 2.shouldBeLessThanOrEqual(3)84 shouldThrow<AssertionError> {85 2 shouldBe io.kotest.matchers.ints.lte(1)86 }87 }88 "beGreaterThanOrEqualTo" {89 1 should io.kotest.matchers.ints.beGreaterThanOrEqualTo(0)90 3.shouldBeGreaterThanOrEqual(1)91 shouldThrow<AssertionError> {92 2 should io.kotest.matchers.ints.beGreaterThanOrEqualTo(3)93 }94 }95 "between should test for valid interval" {96 val table = table(97 headers("a", "b"),98 row(0, 2),99 row(1, 2),100 row(0, 1),101 row(1, 1)102 )103 forAll(table) { a, b ->104 1 shouldBe io.kotest.matchers.ints.between(a, b)105 1.shouldBeBetween(a, b)106 }107 }108 "between should test for invalid interval" {109 val table = table(110 headers("a", "b"),111 row(0, 2),112 row(2, 2),113 row(4, 5),114 row(4, 6)115 )116 forNone(table) { a, b ->117 3 shouldBe io.kotest.matchers.ints.between(a, b)118 }119 }120 "shouldBeZero" {121 0.shouldBeZero()122 1.shouldNotBeZero()123 Int.MIN_VALUE.shouldNotBeZero()124 Int.MAX_VALUE.shouldNotBeZero()125 }126 }127}...
int.kt
Source:int.kt
1package io.kotest.matchers.ints2import io.kotest.matchers.Matcher3import io.kotest.matchers.MatcherResult4import io.kotest.matchers.comparables.gt5import io.kotest.matchers.comparables.gte6import io.kotest.matchers.comparables.lt7import io.kotest.matchers.comparables.lte8import io.kotest.matchers.should9import io.kotest.matchers.shouldBe10import io.kotest.matchers.shouldNot11import io.kotest.matchers.shouldNotBe12fun Int.shouldBePositive() = this shouldBe positive()13fun positive() = object : Matcher<Int> {14 override fun test(value: Int) = MatcherResult(value > 0, "$value should be > 0", "$value should not be > 0")15}16fun Int.shouldBeNegative() = this shouldBe negative()17fun negative() = object : Matcher<Int> {18 override fun test(value: Int) = MatcherResult(value < 0, "$value should be < 0", "$value should not be < 0")19}20fun Int.shouldBeEven() = this should beEven()21fun Int.shouldNotBeEven() = this shouldNot beEven()22fun beEven() = object : Matcher<Int> {23 override fun test(value: Int): MatcherResult =24 MatcherResult(value % 2 == 0, "$value should be even", "$value should be odd")25}26fun Int.shouldBeOdd() = this should beOdd()27fun Int.shouldNotBeOdd() = this shouldNot beOdd()28fun beOdd() = object : Matcher<Int> {29 override fun test(value: Int): MatcherResult =30 MatcherResult(value % 2 == 1, "$value should be odd", "$value should be even")31}32infix fun Int.shouldBeLessThan(x: Int) = this shouldBe lt(x)33infix fun Int.shouldNotBeLessThan(x: Int) = this shouldNotBe lt(x)34infix fun Int.shouldBeLessThanOrEqual(x: Int) = this shouldBe lte(x)35infix fun Int.shouldNotBeLessThanOrEqual(x: Int) = this shouldNotBe lte(x)36infix fun Int.shouldBeGreaterThan(x: Int) = this shouldBe gt(x)37infix fun Int.shouldNotBeGreaterThan(x: Int) = this shouldNotBe gt(x)38infix fun Int.shouldBeGreaterThanOrEqual(x: Int) = this shouldBe gte(x)39infix fun Int.shouldNotBeGreaterThanOrEqual(x: Int) = this shouldNotBe gte(x)40infix fun Int.shouldBeExactly(x: Int) = this shouldBe exactly(x)41infix fun Int.shouldNotBeExactly(x: Int) = this shouldNotBe exactly(x)42fun Int.shouldBeZero() = this shouldBeExactly 043fun Int.shouldNotBeZero() = this shouldNotBeExactly 0...
Int.shouldBeZero
Using AI Code Generation
1@file:Suppress("RedundantSemicolon")2import io.kotest.matchers.Matcher3import io.kotest.matchers.MatcherResult4import io.kotest.matchers.shouldBe5import kotlin.Int6infix fun Int?.shouldBeZero(): Unit = this.shouldBe(0)7infix fun Int?.shouldNotBeZero(): Unit = this.shouldNotBe(0)8fun zero(): Matcher<Int> = object : Matcher<Int> {9override fun test(value: Int): MatcherResult = MatcherResult(value == 0, "$value should be 0", "$value should not be 0")10}11fun notZero(): Matcher<Int> = object : Matcher<Int> {12override fun test(value: Int): MatcherResult = MatcherResult(value != 0, "$value should not be 0", "$value should be 0")13}14fun Int.shouldBeEven(): Unit = this % 2 shouldBe 015fun Int.shouldBeOdd(): Unit = this % 2 shouldBe 116fun Int.shouldBePositive(): Unit = this shouldBe greaterThan(0)17fun Int.shouldBeNegative(): Unit = this shouldBe lessThan(0)18fun Int.shouldBeNonPositive(): Unit = this shouldBe lessOrEqual(0)19fun Int.shouldBeNonNegative(): Unit = this shouldBe greaterOrEqual(0)20fun Int.shouldBeInRange(start: Int, endInclusive: Int): Unit = this shouldBe between(start, endInclusive)21fun Int.shouldBeLessThan(n: Int): Unit = this shouldBe lessThan(n)22fun Int.shouldBeGreaterThan(n: Int): Unit = this shouldBe greaterThan(n)23fun Int.shouldBeLessOrEqual(n: Int): Unit = this shouldBe lessOrEqual(n)24fun Int.shouldBeGreaterOrEqual(n: Int): Unit = this shouldBe greaterOrEqual(n)25fun Int.shouldBeBetween(start: Int, endInclusive: Int): Unit = this shouldBe between(start, endInclusive)26fun Int.shouldBeBetween(start: Int, endInclusive: Int, rangeStep: Int): Unit = this shouldBe between(start, endInclusive, rangeStep)27fun Int.shouldNotBeInRange(start: Int, endInclusive: Int): Unit = this shouldNotBe between(start, endInclusive)28fun Int.shouldNotBeLessThan(n: Int): Unit = this shouldNotBe lessThan(n)29fun Int.shouldNotBeGreaterThan(n:
Int.shouldBeZero
Using AI Code Generation
1@kotlin.test.Test fun testIntShouldBeZero() { 0 .shouldBeZero() }2@kotlin.test.Test fun testIntShouldBeOdd() { 1 .shouldBeOdd() }3@kotlin.test.Test fun testIntShouldBeEven() { 2 .shouldBeEven() }4@kotlin.test.Test fun testIntShouldBeGreaterThan() { 2 .shouldBeGreaterThan( 1 ) }5@kotlin.test.Test fun testIntShouldBeGreaterThanOrEqual() { 2 .shouldBeGreaterThanOrEqual( 2 ) }6@kotlin.test.Test fun testIntShouldBeLessThan() { 1 .shouldBeLessThan( 2 ) }7@kotlin.test.Test fun testIntShouldBeLessThanOrEqual() { 1 .shouldBeLessThanOrEqual( 1 ) }8@kotlin.test.Test fun testIntShouldBeBetween() { 2 .shouldBeBetween( 1 , 3 ) }9@kotlin.test.Test fun testIntShouldBePositive() { 2 .shouldBePositive() }10@kotlin.test.Test fun testIntShouldBeNegative() { - 1 .shouldBeNegative() }11@kotlin.test.Test fun testIntShouldBeInRange() { 2 .shouldBeInRange( 1 .. 3 ) }
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!!