How to use concurrentHashMap method of io.kotest.common.concurrentHashMap class

Best Kotest code snippet using io.kotest.common.concurrentHashMap.concurrentHashMap

InstancePerTestSpecRunner.kt

Source:InstancePerTestSpecRunner.kt Github

copy

Full Screen

1package io.kotest.engine.spec.runners2import io.kotest.common.ExperimentalKotest3import io.kotest.common.flatMap4import io.kotest.core.concurrency.CoroutineDispatcherFactory5import io.kotest.core.config.ProjectConfiguration6import io.kotest.core.spec.Spec7import io.kotest.core.test.NestedTest8import io.kotest.core.test.TestCase9import io.kotest.core.test.TestResult10import io.kotest.core.test.TestScope11import io.kotest.core.test.TestType12import io.kotest.engine.listener.TestEngineListener13import io.kotest.engine.spec.Materializer14import io.kotest.engine.spec.SpecExtensions15import io.kotest.engine.spec.SpecRunner16import io.kotest.engine.test.TestCaseExecutionListener17import io.kotest.engine.test.TestCaseExecutor18import io.kotest.engine.test.scheduler.TestScheduler19import io.kotest.engine.test.scopes.DuplicateNameHandlingTestScope20import io.kotest.mpp.log21import kotlinx.coroutines.coroutineScope22import java.util.concurrent.ConcurrentHashMap23import kotlin.coroutines.CoroutineContext24/**25 * Implementation of [SpecRunner] that executes each [TestCase] in a fresh instance26 * of the [Spec] class.27 *28 * This differs from the [InstancePerLeafSpecRunner] in that29 * every single test, whether of type [TestType.Test] or [TestType.Container], will be30 * executed separately. Branch tests will ultimately be executed once as a standalone31 * test, and also as part of the "path" to any nested tests.32 *33 * So, given the following structure:34 *35 * outerTest {36 * innerTestA {37 * // test38 * }39 * innerTestB {40 * // test41 * }42 * }43 *44 * Three spec instances will be created. The execution process will be:45 *46 * spec1 = instantiate spec47 * spec1.outerTest48 * spec2 = instantiate spec49 * spec2.outerTest50 * spec2.innerTestA51 * spec3 = instantiate spec52 * spec3.outerTest53 * spec3.innerTestB54 */55@ExperimentalKotest56internal class InstancePerTestSpecRunner(57 listener: TestEngineListener,58 schedule: TestScheduler,59 private val defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory,60 private val configuration: ProjectConfiguration,61) : SpecRunner(listener, schedule, configuration) {62 private val extensions = SpecExtensions(configuration.registry)63 private val results = ConcurrentHashMap<TestCase, TestResult>()64 /**65 * The intention of this runner is that each [TestCase] executes in its own instance66 * of the containing [Spec] class. Therefore, when we begin executing a test case from67 * the queue, we must first instantiate a new spec, and begin execution on _that_ instance.68 *69 * As test lambdas are executed, nested test cases will be registered, these should be ignored70 * if they are not an ancestor of the target. If they are then we can step into them, and71 * continue recursively until we find the target.72 *73 * Once the target is found it can be executed as normal, and any test lambdas it contains74 * can be registered back with the stack for execution later.75 */76 override suspend fun execute(spec: Spec): Result<Map<TestCase, TestResult>> =77 runCatching {78 launch(spec) {79 executeInCleanSpec(it)80 .getOrThrow()81 }82 results83 }84 /**85 * The intention of this runner is that each [TestCase] executes in its own instance86 * of the containing [Spec] class. Therefore, when we begin executing a test case from87 * the queue, we must first instantiate a new spec, and begin execution on _that_ instance.88 *89 * As test lambdas are executed, nested test cases will be registered, these should be ignored90 * if they are not an ancestor of the target. If they are then we can step into them, and91 * continue recursively until we find the target.92 *93 * Once the target is found it can be executed as normal, and any test lambdas it contains94 * can be registered back with the stack for execution later.95 */96 private suspend fun executeInCleanSpec(test: TestCase): Result<Spec> {97 return createInstance(test.spec::class)98 .flatMap { spec ->99 runCatching {100 extensions.intercept(spec) {101 extensions.beforeSpec(spec)102 .flatMap { run(it, test) }103 .flatMap { extensions.afterSpec(it) }104 }105 }.map { spec }106 }107 }108 private suspend fun run(spec: Spec, test: TestCase): Result<Spec> = kotlin.runCatching {109 log { "Created new spec instance $spec" }110 // we need to find the same root test but in the newly created spec111 val root = materializer.materialize(spec).first { it.descriptor.isOnPath(test.descriptor) }112 log { "Starting root test ${root.descriptor} in search of ${test.descriptor}" }113 run(root, test)114 spec115 }116 private suspend fun run(test: TestCase, target: TestCase) {117 val isTarget = test.descriptor == target.descriptor118 coroutineScope {119 val context = object : TestScope {120 override val testCase: TestCase = test121 override val coroutineContext: CoroutineContext = this@coroutineScope.coroutineContext122 override suspend fun registerTestCase(nested: NestedTest) {123 val t = Materializer(configuration).materialize(nested, testCase)124 // if we are currently executing the target, then any registered tests are new, and we125 // should begin execution of them in fresh specs126 // otherwise if the test is on the path we can continue in the same spec127 if (isTarget) {128 executeInCleanSpec(t).getOrThrow()129 } else if (t.descriptor.isOnPath(target.descriptor)) {130 run(t, target)131 }132 }133 }134 val context2 = DuplicateNameHandlingTestScope(configuration.duplicateTestNameMode, context)135 val testExecutor = TestCaseExecutor(136 object : TestCaseExecutionListener {137 override suspend fun testStarted(testCase: TestCase) {138 if (isTarget) listener.testStarted(testCase)139 }140 override suspend fun testIgnored(testCase: TestCase, reason: String?) {141 if (isTarget) listener.testIgnored(testCase, reason)142 }143 override suspend fun testFinished(testCase: TestCase, result: TestResult) {144 if (isTarget) listener.testFinished(testCase, result)145 }146 },147 defaultCoroutineDispatcherFactory,148 configuration149 )150 val result = testExecutor.execute(test, context2)151 results[test] = result152 }153 }154}...

Full Screen

Full Screen

AuthRoutesTest.kt

Source:AuthRoutesTest.kt Github

copy

Full Screen

1package com.ketabs.route2import arrow.core.computations.ResultEffect.bind3import com.auth0.jwt.JWT4import com.ketabs.ObjectMother5import com.ketabs.model.User6import com.ketabs.model.valueobject.ID7import com.ketabs.repository.InMemoryUserRepository8import com.ketabs.testApp9import io.kotest.common.runBlocking10import io.ktor.http.ContentType11import io.ktor.http.HttpHeaders12import io.ktor.http.HttpMethod13import io.ktor.http.HttpStatusCode14import io.ktor.server.testing.handleRequest15import io.ktor.server.testing.setBody16import io.ktor.server.testing.withTestApplication17import kotlinx.serialization.decodeFromString18import kotlinx.serialization.encodeToString19import kotlinx.serialization.json.Json20import org.junit.jupiter.api.DynamicTest21import org.junit.jupiter.api.TestFactory22import java.util.concurrent.ConcurrentHashMap23import kotlin.test.Test24import kotlin.test.assertContains25import kotlin.test.assertEquals26import kotlin.test.assertNull27import kotlin.test.assertTrue28internal class AuthRoutesTest {29 @Test30 fun `user must register`() {31 val (user, plainPassword) = ObjectMother.randomUserAndPlainPassword()32 val userRepo = InMemoryUserRepository()33 withTestApplication(testApp(userRepo = userRepo)) {34 with(35 handleRequest(HttpMethod.Post, "/auth/register") {36 setBody(37 Json.encodeToString(38 mapOf(39 "email" to user.email.value,40 "password" to plainPassword.value,41 "full_name" to user.fullName.value42 )43 )44 )45 addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())46 }47 ) {48 val resData = Json.decodeFromString<Map<String, String>>(response.content ?: "{}")49 assertEquals(HttpStatusCode.Created, response.status())50 assertEquals(user.email.value, resData["email"])51 assertEquals(user.fullName.value, resData["full_name"])52 runBlocking {53 val found = userRepo.getByID(ID.of(resData["id"] ?: "").bind()).bind()54 assertEquals(user.email.value, found.email.value)55 assertEquals(user.fullName.value, found.fullName.value)56 assertTrue(found.password.matches(plainPassword))57 }58 }59 }60 }61 @Test62 fun `user must log in`() {63 val (user, plainPassword) = ObjectMother.randomUserAndPlainPassword()64 val store = ConcurrentHashMap<ID, User>()65 store[user.id] = user66 val userRepo = InMemoryUserRepository.withStore(store)67 withTestApplication(testApp(userRepo = userRepo)) {68 with(69 handleRequest(HttpMethod.Post, "/auth/login") {70 setBody(71 Json.encodeToString(72 mapOf(73 "email" to user.email.value,74 "password" to plainPassword.value,75 )76 )77 )78 addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())79 }80 ) {81 val resData = Json.decodeFromString<Map<String, String>>(response.content ?: "{}")82 assertEquals(HttpStatusCode.OK, response.status())83 assertContains(resData, "token")84 val decodedToken = JWT.decode(resData["token"])85 assertEquals(user.id.value, decodedToken.getClaim("id").asString())86 assertEquals(user.email.value, decodedToken.getClaim("email").asString())87 assertEquals(user.fullName.value, decodedToken.getClaim("full_name").asString())88 }89 }90 }91 @TestFactory92 fun `user must not log in`(): List<DynamicTest> {93 val (registeredUser, registeredUserPlainPassword) = ObjectMother.randomUserAndPlainPassword()94 val (unregisteredUser, unregisteredUserPlainPassword) = ObjectMother.randomUserAndPlainPassword()95 val store = ConcurrentHashMap<ID, User>()96 store[registeredUser.id] = registeredUser97 val userRepo = InMemoryUserRepository.withStore(store)98 return listOf(99 Pair(registeredUser.email.value, registeredUserPlainPassword.value + "hello"),100 Pair(unregisteredUser.email.value, unregisteredUserPlainPassword.value),101 ).map { (email, password) ->102 DynamicTest.dynamicTest("when I try logging in is as `$email` with password `$password` then I must be unauthorized") {103 withTestApplication(testApp(userRepo = userRepo)) {104 with(105 handleRequest(HttpMethod.Post, "/auth/login") {106 setBody(107 Json.encodeToString(108 mapOf(109 "email" to email, "password" to password110 )111 )112 )113 addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())114 }115 ) {116 assertNull(response.content)117 assertEquals(HttpStatusCode.Unauthorized, response.status())118 }119 }120 }121 }122 }123}...

Full Screen

Full Screen

SingleInstanceSpecRunner.kt

Source:SingleInstanceSpecRunner.kt Github

copy

Full Screen

1package io.kotest.engine.spec.runners2import io.kotest.common.ExperimentalKotest3import io.kotest.common.flatMap4import io.kotest.core.concurrency.CoroutineDispatcherFactory5import io.kotest.core.config.ProjectConfiguration6import io.kotest.core.spec.Spec7import io.kotest.core.test.NestedTest8import io.kotest.core.test.TestCase9import io.kotest.core.test.TestResult10import io.kotest.core.test.TestScope11import io.kotest.engine.listener.TestEngineListener12import io.kotest.engine.spec.Materializer13import io.kotest.engine.spec.SpecExtensions14import io.kotest.engine.spec.SpecRunner15import io.kotest.engine.test.TestCaseExecutor16import io.kotest.engine.test.listener.TestCaseExecutionListenerToTestEngineListenerAdapter17import io.kotest.engine.test.scheduler.TestScheduler18import io.kotest.engine.test.scopes.DuplicateNameHandlingTestScope19import io.kotest.mpp.Logger20import io.kotest.mpp.bestName21import kotlinx.coroutines.coroutineScope22import java.util.concurrent.ConcurrentHashMap23import kotlin.coroutines.CoroutineContext24/**25 * Implementation of [SpecRunner] that executes all tests against the26 * same [Spec] instance. In other words, only a single instance of the spec class27 * is instantiated for all the test cases.28 */29@ExperimentalKotest30internal class SingleInstanceSpecRunner(31 listener: TestEngineListener,32 scheduler: TestScheduler,33 private val defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory,34 private val configuration: ProjectConfiguration,35) : SpecRunner(listener, scheduler, configuration) {36 private val results = ConcurrentHashMap<TestCase, TestResult>()37 private val extensions = SpecExtensions(configuration.registry)38 private val logger = Logger(SingleInstanceSpecRunner::class)39 override suspend fun execute(spec: Spec): Result<Map<TestCase, TestResult>> {40 logger.log { Pair(spec::class.bestName(), "executing spec $spec") }41 suspend fun interceptAndRun(context: CoroutineContext) = runCatching {42 val rootTests = materializer.materialize(spec)43 logger.log { Pair(spec::class.bestName(), "Materialized root tests: ${rootTests.size}") }44 launch(spec) {45 logger.log { Pair(it.name.testName, "Executing test $it") }46 runTest(it, context, null)47 }48 }49 try {50 return coroutineScope {51 extensions.beforeSpec(spec)52 .flatMap { interceptAndRun(coroutineContext) }53 .flatMap { SpecExtensions(configuration.registry).afterSpec(spec) }54 .map { results }55 }56 } catch (e: Exception) {57 e.printStackTrace()58 throw e59 }60 }61 /**62 * A [TestScope] that runs discovered tests as soon as they are registered in the same spec instance.63 *64 * This implementation tracks fail fast if configured via TestCase config or globally.65 */66 inner class SingleInstanceTestScope(67 override val testCase: TestCase,68 override val coroutineContext: CoroutineContext,69 private val parentScope: SingleInstanceTestScope?,70 ) : TestScope {71 // set to true if we failed fast and should ignore further tests72 private var skipRemaining = false73 // in the single instance runner we execute each nested test as soon as they are registered74 override suspend fun registerTestCase(nested: NestedTest) {75 logger.log { Pair(testCase.name.testName, "Nested test case discovered '${nested}") }76 val nestedTestCase = Materializer(configuration).materialize(nested, testCase)77 if (skipRemaining) {78 logger.log { Pair(testCase.name.testName, "Skipping test due to fail fast") }79 listener.testIgnored(nestedTestCase, "Skipping test due to fail fast")80 } else {81 // if running this nested test results in an error, we won't launch anymore nested tests82 val result = runTest(nestedTestCase, coroutineContext, this@SingleInstanceTestScope)83 if (result.isErrorOrFailure) {84 if (testCase.config.failfast || configuration.projectWideFailFast) {85 logger.log { Pair(testCase.name.testName, "Test failed - setting skipRemaining = true") }86 skipRemaining = true87 parentScope?.skipRemaining = true88 }89 }90 }91 }92 }93 private suspend fun runTest(94 testCase: TestCase,95 coroutineContext: CoroutineContext,96 parentScope: SingleInstanceTestScope?,97 ): TestResult {98 val testExecutor = TestCaseExecutor(99 TestCaseExecutionListenerToTestEngineListenerAdapter(listener),100 defaultCoroutineDispatcherFactory,101 configuration,102 )103 val scope = DuplicateNameHandlingTestScope(104 configuration.duplicateTestNameMode,105 SingleInstanceTestScope(testCase, coroutineContext, parentScope)106 )107 val result = testExecutor.execute(testCase, scope)108 results[testCase] = result109 return result110 }111}...

Full Screen

Full Screen

CollectingTestEngineListener.kt

Source:CollectingTestEngineListener.kt Github

copy

Full Screen

1package io.kotest.engine.listener2import io.kotest.common.concurrentHashMap3import io.kotest.core.descriptors.Descriptor4import io.kotest.core.test.TestCase5import io.kotest.core.test.TestResult6import kotlin.reflect.KClass7class CollectingTestEngineListener : AbstractTestEngineListener() {8 val specs = concurrentHashMap<KClass<*>, TestResult>()9 val tests = concurrentHashMap<TestCase, TestResult>()10 val names = mutableListOf<String>()11 var errors = false12 fun result(descriptor: Descriptor.TestDescriptor): TestResult? = tests.mapKeys { it.key.descriptor }[descriptor]13 fun result(testname: String): TestResult? = tests.mapKeys { it.key.name.testName }[testname]14 override suspend fun specFinished(kclass: KClass<*>, result: TestResult) {15 specs[kclass] = result16 if (result.isErrorOrFailure) errors = true17 }18 override suspend fun testIgnored(testCase: TestCase, reason: String?) {19 tests[testCase] = TestResult.Ignored(reason)20 names.add(testCase.name.testName)21 }22 override suspend fun testFinished(testCase: TestCase, result: TestResult) {23 tests[testCase] = result...

Full Screen

Full Screen

concurrentHashMap.kt

Source:concurrentHashMap.kt Github

copy

Full Screen

1package io.kotest.common2actual fun <K, V> concurrentHashMap(): MutableMap<K, V> = mutableMapOf()...

Full Screen

Full Screen

collections.kt

Source:collections.kt Github

copy

Full Screen

1package io.kotest.common2expect fun <K, V> concurrentHashMap(): MutableMap<K, V>...

Full Screen

Full Screen

concurrentHashMap

Using AI Code Generation

copy

Full Screen

1val map = concurrentHashMapOf("a" to 1, "b" to 2)2val queue = concurrentLinkedQueueOf(1, 2, 3)3val map = concurrentSkipListMapOf("a" to 1, "b" to 2)4val set = concurrentSkipListSetOf(1, 2, 3)5val list = copyOnWriteArrayListOf(1, 2, 3)6val set = copyOnWriteArraySetOf(1, 2, 3)7val map = enumMapOf(1 to "a", 2 to "b")8val set = enumSetOf(1, 2, 3)9val set = hashSetOf(1, 2, 3)10val set = linkedHashSetOf(1, 2, 3)11val map = linkedMapOf("a" to 1, "b" to 2)12val set = linkedSetOf(1, 2, 3)13val map = mapOf("a" to 1, "b" to 2)14val map = sortedMapOf("a" to 1, "b" to

Full Screen

Full Screen

concurrentHashMap

Using AI Code Generation

copy

Full Screen

1val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )2val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )3val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )4val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )5val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )6val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )7val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )8val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )9val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )10val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )11val map = concurrentHashMapOf ( "one" to 1 , "two" to 2 , "three" to 3 )

Full Screen

Full Screen

concurrentHashMap

Using AI Code Generation

copy

Full Screen

1val map = concurrentHashMapOf("a" to 1, "b" to 2, "c" to 3)2map shouldContainAll mapOf("a" to 4, "b" to 2, "c" to 3, "d" to 5)3map shouldNotContainAll mapOf("a" to 4, "b" to 2, "c" to 3, "d" to 5)4map shouldContainExactly mapOf("a" to 4, "b" to 2, "c" to 3, "d" to 5)5map shouldContainExactlyInAnyOrder mapOf("a" to 4, "b" to 2, "c" to 3, "d" to 5)6map shouldContainExactlyInAnyOrderEntries mapOf("a" to 4, "b" to 2, "c" to 3, "d" to 5).entries7map shouldContainExactlyEntries mapOf("a" to 4, "b" to 2, "c" to 3, "d" to 5).entries8map shouldContainAllEntries mapOf("a" to 4, "b" to 2, "c" to 3, "

Full Screen

Full Screen

concurrentHashMap

Using AI Code Generation

copy

Full Screen

1val map = concurrentHashMapOf(1 to "one", 2 to "two")2val map = concurrentHashMapOf(1 to "one", 2 to "two")3val map = concurrentHashMapOf(1 to "one", 2 to "two")4val map = concurrentHashMapOf(1 to "one", 2 to "two")5val map = concurrentHashMapOf(1 to "one", 2 to "two")6val map = concurrentHashMapOf(1 to "one", 2 to "two")7val map = concurrentHashMapOf(1 to "one", 2 to "two")8val map = concurrentHashMapOf(1 to "one", 2 to "two")9val map = concurrentHashMapOf(1 to "one", 2 to "two")10val map = concurrentHashMapOf(1 to "one", 2 to "two")11val map = concurrentHashMapOf(1 to "one", 2 to "two")12val map = concurrentHashMapOf(1 to "one", 2 to "two")13val map = concurrentHashMapOf(1 to "one",

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in concurrentHashMap

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful