How to use keys class of io.kotest.assertions.json package

Best Kotest code snippet using io.kotest.assertions.json.keys

io.github.nstdio.http.ext.test-conventions.gradle.kts

Source:io.github.nstdio.http.ext.test-conventions.gradle.kts Github

copy

Full Screen

...98 testImplementation("com.tngtech.archunit:archunit-junit5:0.23.1")99 spiDeps.forEach { spiTestImplementation(it) }100 spiTestImplementation("com.aayushatharva.brotli4j:native-${getArch()}:$brotli4JVersion")101}102Generator.subset(jsonLibs.keys)103 .simple()104 .stream()105 .forEach { it ->106 val postFix = it.joinToString("And") { it.capitalized() }107 val taskName = if (postFix.isEmpty()) "spiTest" else "spiTestWithout${postFix}"108 tasks.create<Test>(taskName) {109 description = "Run SPI tests"110 group = "verification"111 testClassesDirs = sourceSetsSpiTest.output.classesDirs112 classpath = sourceSetsSpiTest.runtimeClasspath113 doFirst {114 val toExclude = classpath.filter { file ->115 it?.any { file.absolutePath.contains(it) } ?: false116 }...

Full Screen

Full Screen

JsonSerializeVerifiableCredentialTest.kt

Source:JsonSerializeVerifiableCredentialTest.kt Github

copy

Full Screen

1package id.walt.services.data2import com.beust.klaxon.Klaxon3import id.walt.vclib.credentials.Europass4import id.walt.vclib.credentials.PermanentResidentCard5import id.walt.vclib.credentials.VerifiableAttestation6import id.walt.vclib.model.*7import io.kotest.assertions.fail8import io.kotest.assertions.json.shouldEqualJson9import io.kotest.core.spec.style.AnnotationSpec10import io.kotest.matchers.shouldBe11import java.io.File12import java.time.LocalDateTime13class JsonSerializeVerifiableCredentialTest : AnnotationSpec() {14 val VC_PATH = "src/test/resources/verifiable-credentials"15 val format = Klaxon()16 @Test17 fun vcTemplatesTest() {18 File("templates/").walkTopDown()19 .filter { it.toString().endsWith(".json") }20 .forEach {21 println("serializing: $it")22 val input = File(it.toURI()).readText().replace("\\s".toRegex(), "")23 val vc = input.toCredential()24 when (vc) {25 is Europass -> println("\t => Europass serialized")26 is PermanentResidentCard -> {27 println("\t => PermanentResidentCard serialized")28 val enc = Klaxon().toJsonString(vc)29 input shouldEqualJson enc30 }31 is VerifiableAttestation -> {32 println("\t => EbsiVerifiableAttestation serialized")33 val enc = Klaxon().toJsonString(vc)34 input shouldEqualJson enc35 }36 else -> {37 fail("VC type not supported")38 }39 }40 }41 }42 @Test43 fun serializeEbsiVerifiableAuthorization() {44 val va = File("$VC_PATH/vc-ebsi-verifiable-authorisation.json").readText()45 val vc = va.toCredential()46 }47 @Test48 fun serializeSignedVc() {49 val signedEuropassStr = File("$VC_PATH/vc-europass-signed.json").readText()50 println(signedEuropassStr)51 val vc = signedEuropassStr.toCredential()52 }53 // TODO: remove / replace functions below as they are using the old data model54 @Test55 fun vcSerialization() {56 val input = File("templates/vc-template-default.json").readText().replace("\\s".toRegex(), "")57 val vc = Klaxon().parse<VerifiableCredential>(input)58 println(vc)59 val enc = Klaxon().toJsonString(vc)60 println(enc)61 input shouldEqualJson enc62 }63 @Test64 fun vcConstructTest() {65 val proof =66 Proof(67 type = "EidasSeal2019",68 created = LocalDateTime.now().withNano(0).toString(),69 creator = "did:creator",70 proofPurpose = "assertionMethod",71 verificationMethod = "EidasCertificate2019",//VerificationMethodCert("EidasCertificate2019", "1088321447"),72 jws = "BD21J4fdlnBvBA+y6D...fnC8Y="73 )74 val vc = VerifiableAttestation(75 context = listOf(76 "https://www.w3.org/2018/credentials/v1",77 "https://essif.europa.eu/schemas/v-a/2020/v1",78 "https://essif.europa.eu/schemas/eidas/2020/v1"79 ),80 id = "education#higherEducation#3fea53a4-0432-4910-ac9c-69ah8da3c37f",81 issuer = "did:ebsi:2757945549477fc571663bee12042873fe555b674bd294a3",82 issued = "2019-06-22T14:11:44Z",83 validFrom = "2019-06-22T14:11:44Z",84 credentialSubject = VerifiableAttestation.VerifiableAttestationSubject(85 id = "id123"86 ),87 credentialStatus = CredentialStatus(88 id = "https://essif.europa.eu/status/identity#verifiableID#1dee355d-0432-4910-ac9c-70d89e8d674e",89 type = "CredentialStatusList2020"90 ),91 credentialSchema = CredentialSchema(92 id = "https://essif.europa.eu/tsr-vid/verifiableid1.json",93 type = "JsonSchemaValidator2018"94 ),95 evidence = listOf(96 VerifiableAttestation.Evidence(97 id = "https://essif.europa.eu/tsr-va/evidence/f2aeec97-fc0d-42bf-8ca7-0548192d5678",98 type = listOf("DocumentVerification"),99 verifier = "did:ebsi:2962fb784df61baa267c8132497539f8c674b37c1244a7a",100 evidenceDocument = "Passport",101 subjectPresence = "Physical",102 documentPresence = "Physical"103 )104 ),105 proof = Proof(106 type = "EidasSeal2021",107 created = "2019-06-22T14:11:44Z",108 proofPurpose = "assertionMethod",109 verificationMethod = "did:ebsi:2757945549477fc571663bee12042873fe555b674bd294a3#2368332668",110 jws = "HG21J4fdlnBvBA+y6D...amP7O="111 )112 )113 val encoded = format.toJsonString(vc)114 // println(encoded)115 val obj = Klaxon().parse<VerifiableCredential>(encoded)116 // println(obj)117 vc shouldBe obj118 }119 @Test120 fun vcTemplatesOldTest() {121 File("templates/").walkTopDown()122 .filter { it.toString().endsWith(".json") }123 .forEach {124 println("serializing: $it")125 //val obj = Json { ignoreUnknownKeys = true }.decodeFromString<VerifiableCredential>(it.readText())126 val obj = Klaxon().parse<VerifiableCredential>(it.readText())127 println(obj)128 }129 }130}...

Full Screen

Full Screen

KeyProviderTest.kt

Source:KeyProviderTest.kt Github

copy

Full Screen

...16import java.security.interfaces.RSAPrivateKey17import java.security.interfaces.RSAPublicKey18internal class KeyProviderTest {19 private val initialRSAKeysFile = File("src/main/resources$INITIAL_KEYS_FILE")20 private val initialECKeysFile = File("src/main/resources/mock-oauth2-server-keys-ec.json")21 @Test22 fun `signingKey should return a RSA key from initial keys file until deque is empty`() {23 val provider = KeyProvider()24 val initialPublicKeys = initialRsaPublicKeys()25 for (i in initialPublicKeys.indices) {26 provider.signingKey("issuer$i").asClue {27 it.toRSAKey().toRSAPublicKey() shouldBeIn initialPublicKeys28 it.keyID shouldBe "issuer$i"29 }30 }31 provider.signingKey("shouldBeGeneratedOnTheFly").asClue {32 it.toRSAKey().toRSAPublicKey() shouldNotBeIn initialPublicKeys33 it.keyID shouldBe "shouldBeGeneratedOnTheFly"34 }35 }36 @Test37 fun `signingKey should return a EC key from initial keys file until deque is empty`() {38 val provider = KeyProvider(39 initialKeys = KeyProvider.keysFromFile("/mock-oauth2-server-keys-ec.json"),40 algorithm = "ES256"41 )42 val initialPublicKeys = initialEcPublicKeys()43 for (i in initialPublicKeys.indices) {44 provider.signingKey("issuer$i").asClue {45 it.toECKey().toECPublicKey() shouldBeIn initialPublicKeys46 it.keyID shouldBe "issuer$i"47 }48 }49 provider.signingKey("shouldBeGeneratedOnTheFly").asClue {50 it.toECKey().toECPublicKey() shouldNotBeIn initialPublicKeys51 it.keyID shouldBe "shouldBeGeneratedOnTheFly"52 }53 }54 @Test55 fun `unsupported signingKey algorithm should throw an error message`() {56 val provider = KeyProvider(KeyProvider.keysFromFile("/mock-oauth2-server-keys-ec.json"))57 shouldThrow<OAuth2Exception> {58 provider.generate("ET256")59 }.message shouldBe "Unsupported algorithm: ET256"60 }61 @Test62 fun `signingKey should return a RSA key from provided constructor arg until deque is empty`() {63 val initialKeys = generateKeys(2)64 val provider = KeyProvider(initialKeys)65 val initialPublicKeys = initialKeys.map { it.toRSAPublicKey() }66 for (i in initialPublicKeys.indices) {67 provider.signingKey("issuer$i").asClue {68 it.toRSAKey().toRSAPublicKey() shouldBeIn initialPublicKeys69 it.keyID shouldBe "issuer$i"70 }71 }72 provider.signingKey("shouldBeGeneratedOnTheFly").asClue {73 it.toRSAKey().toRSAPublicKey() shouldNotBeIn initialPublicKeys74 it.keyID shouldBe "shouldBeGeneratedOnTheFly"75 }76 }77 private fun initialRsaPublicKeys(): List<RSAPublicKey> =78 initialRSAKeysFile.readText().let {79 JWKSet.parse(it).keys80 }.map {81 it.toRSAKey().toRSAPublicKey()82 }83 private fun initialEcPublicKeys(): List<ECPublicKey> =84 initialECKeysFile.readText().let {85 JWKSet.parse(it).keys86 }.map {87 it.toECKey().toECPublicKey()88 }89 private fun writeInitialKeysFile() {90 val list = generateKeys(5)91 initialRSAKeysFile.writeText(JWKSet(list).toString(false))92 }93 private fun generateKeys(numKeys: Int): List<RSAKey> {94 val list = mutableListOf<RSAKey>()95 for (i in 1..numKeys) {96 val key = KeyPairGenerator.getInstance("RSA").apply { this.initialize(2048) }97 .generateKeyPair()98 .let {99 RSAKey.Builder(it.public as RSAPublicKey)...

Full Screen

Full Screen

ConfigureBaseDependenciesAction.kt

Source:ConfigureBaseDependenciesAction.kt Github

copy

Full Screen

1package ru.itbasis.gradle.backend.actions2import io.spring.gradle.dependencymanagement.DependencyManagementPlugin3import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension4import org.gradle.api.Action5import org.gradle.api.Project6import org.gradle.api.artifacts.DependencyResolveDetails7import org.gradle.kotlin.dsl.apply8import org.gradle.kotlin.dsl.dependencies9import org.gradle.kotlin.dsl.extra10import org.gradle.kotlin.dsl.maven11import org.gradle.kotlin.dsl.repositories12import org.gradle.kotlin.dsl.the13import org.springframework.boot.gradle.plugin.SpringBootPlugin14import ru.itbasis.gradle.backend.utils.getAllPropertiesFromResources15import ru.itbasis.gradle.backend.utils.putExtraKeys16class ConfigureBaseDependenciesAction : Action<Project> {17 override fun execute(target: Project): Unit = target.run {18 apply<DependencyManagementPlugin>()19 putExtraKeys(this@ConfigureBaseDependenciesAction.getAllPropertiesFromResources(propFileName = "versions.properties"))20 the<DependencyManagementExtension>().apply {21 imports {22 mavenBom(SpringBootPlugin.BOM_COORDINATES)23 }24 }25 repositories {26 maven(url = "https://dl.bintray.com/serpro69/maven/")27 maven(url = "https://dl.bintray.com/serpro69/maven-release-candidates/")28 maven(url = "https://kotlin.bintray.com/kotlinx")29 }30 configureResolutionStrategy(target = project)31 configureDependencies(target = project)32 }33 private fun configureResolutionStrategy(target: Project): Unit = target.run {34 @Suppress("ktNoinlineFunc")35 fun DependencyResolveDetails.useExtraVersion(key: String): Unit = useVersion(extra["${key}.version"] as String)36 configurations.all {37 resolutionStrategy {38 failOnVersionConflict()39 preferProjectModules()40 eachDependency {41 when (requested.group) {42 "io.github.microutils" -> useExtraVersion("microutils-logging")43 "org.slf4j" -> useExtraVersion("slf4j")44 "ch.qos.logback" -> useExtraVersion("logback")45 "io.kotest" -> useExtraVersion("kotest")46 "io.mockk" -> useExtraVersion("mockk")47 "io.github.serpro69" -> useExtraVersion("kotlin-faker")48 "commons-codec" -> useExtraVersion("commons-codec")49 "io.ktor" -> useExtraVersion("ktor")50 "org.koin" -> useExtraVersion("koin")51 "org.kodein.di" -> useExtraVersion("kodein-di")52 "org.jetbrains.kotlin" -> useExtraVersion("kotlin")53 "org.jetbrains.exposed" -> useExtraVersion("exposed")54 "org.jetbrains.kotlinx" -> when {55 requested.name.startsWith("kotlinx-coroutines") -> useExtraVersion("kotlinx-coroutines")56 requested.name.startsWith("kotlinx-serialization") -> useExtraVersion("kotlinx-serialization")57 requested.name.startsWith("kotlinx-html") -> useExtraVersion("kotlinx-html")58 requested.name.startsWith("kotlinx-datetime") -> useExtraVersion("kotlinx-datetime")59 }60 "org.webjars" -> when (requested.name) {61 "swagger-ui" -> useExtraVersion("webjars-swagger")62 }63 "com.fasterxml.jackson" -> useExtraVersion("jackson")64 "com.fasterxml.jackson.core" -> useExtraVersion("jackson")65 "com.fasterxml.jackson.datatype" -> useExtraVersion("jackson")66 "com.fasterxml.jackson.module" -> useExtraVersion("jackson")67 "com.fasterxml.jackson.dataformat" -> useExtraVersion("jackson")68 }69 }70 }71 }72 }73 private fun configureDependencies(target: Project): Unit = target.run {74 dependencies {75 "implementation"("org.jetbrains.kotlinx:kotlinx-datetime")76 "testImplementation"("ch.qos.logback:logback-classic")77 "testImplementation"("io.kotest:kotest-runner-junit5")78 "testImplementation"("io.kotest:kotest-extensions-junit5")79 "testImplementation"("io.kotest:kotest-property")80 "testImplementation"("io.kotest:kotest-assertions-core")81 "testImplementation"("io.kotest:kotest-assertions-kotlinx-time")82 "testImplementation"("io.kotest:kotest-assertions-json")83 "testImplementation"("io.github.serpro69:kotlin-faker")84 "testImplementation"("io.mockk:mockk")85 }86 }87}...

Full Screen

Full Screen

BsonMapEncoderTest.kt

Source:BsonMapEncoderTest.kt Github

copy

Full Screen

...31class BsonMapEncoderTest : StringSpec({32 "Encode map as document" {33 checkAll<Map<String, Int>> { m ->34 val document = bson.encodeToBsonDocument(m)35 document.keys shouldContainAll m.keys36 document.values shouldContainAll m.values.map { BsonInt32(it) }37 }38 }39 "Encode map with composite values" {40 val map = mapOf(41 10 to Wrapper2("abc", Wrapper(42.5F)),42 20 to Wrapper2("cde", Wrapper(123.45F))43 )44 bson.encodeToBsonDocument(map)45 .also { println(it.toJson()) }46 }47 "Encode nested map" {48 val map = mapOf(49 10 to Wrapper2("abc", Wrapper(42.5F)),50 20 to Wrapper2("cde", Wrapper(123.45F))51 )52 val wrapper = MapWrapper(map)53 bson.encodeToBsonDocument(wrapper)54 .also { println(it.toJson()) }55 }56 "Encode map with non-primitive keys" {57 val map = mapOf(58 UUID.randomUUID() to StringUUIDContainer(UUID.randomUUID()),59 UUID.randomUUID() to StringUUIDContainer(UUID.randomUUID())60 )61 val doc = bson.encodeToBsonDocument(MapSerializer(UUIDSerializer, StringUUIDContainer.serializer()), map)62 .also { println(it) }63 doc.keys shouldContainAll map.keys.map { it.toString() }64 }65 "Encode map with non-primitive keys using type mapping" {66 val mappingBson = Bson {67 addTypeMapping(UUIDSerializer, BsonKind.UUID)68 }69 val map = mapOf(70 UUID.randomUUID() to StringUUIDContainer(UUID.randomUUID()),71 UUID.randomUUID() to StringUUIDContainer(UUID.randomUUID())72 )73 val doc = mappingBson.encodeToBsonDocument(MapSerializer(UUIDSerializer, StringUUIDContainer.serializer()), map)74 .also { println(it) }75 doc.keys shouldContainAll map.keys.map { it.toString() }76 }77 "Encode map with composite keys" {78 val structuredBson = Bson {79 allowStructuredMapKeys = true80 }81 val map = mapOf(82 Wrapper2("foo", "bar") to 0L,83 Wrapper2("hello", "world") to 10_000_000L84 )85 val wrapper = Wrapper(map)86 val doc = structuredBson.encodeToBsonDocument(wrapper)87 .also { println(it) }88 doc.getArray("value").forEachIndexed { index, bsonValue ->89 bsonValue.bsonType shouldBe if (index % 2 == 0) {90 BsonType.DOCUMENT91 } else {...

Full Screen

Full Screen

LangTest.kt

Source:LangTest.kt Github

copy

Full Screen

...50 }51 "uses correct rule/token name" {52 val usedRules: List<String> = (53 config.processConfig.normalizeConfig.ignoreRules +54 config.processConfig.normalizeConfig.mapping.keys +55 config.processConfig.normalizeConfig.indexedMapping.keys +56 config.processConfig.splitConfig.splitRules57 )58 .flatMap { it.split('/').filter(String::isNotEmpty) }59 .filterNot { it.contains(Regex("[^a-zA-Z]")) }60 val antlrParser = parser!!.antlrParser61 val allowedRules = antlrParser.ruleNames + antlrParser.tokenTypeMap.keys62 runCatching {63 allowedRules shouldContainAll usedRules64 }.onFailure {65 println("see: ${parserConfig.grammarFilePaths.map(Path::normalize)}")66 val errorSymbols = (usedRules - allowedRules)67 config.fileUri.toURL().readText().lineSequence().forEachIndexed { index, line ->68 val file = config.fileUri.toPath()69 val lineNo = index + 170 errorSymbols.filter { line.contains(it) }.forEach {71 println("""$file:$lineNo: "$it" is not defined""")72 }73 }74 }.getOrThrow()75 }...

Full Screen

Full Screen

InvoiceCreatedConsumerIT.kt

Source:InvoiceCreatedConsumerIT.kt Github

copy

Full Screen

1package br.com.ifood.empresas.erp.feature.invoice2import br.com.ifood.empresas.erp.BaseConsumerITTest3import br.com.ifood.empresas.erp.delivery.shared.Defaults4import io.kotest.assertions.json.shouldMatchJsonResource5import io.kotest.matchers.ints.shouldBeExactly6import io.kotest.matchers.shouldBe7import io.kotest.matchers.shouldNotBe8import java.util.UUID9import java.util.concurrent.TimeUnit10import org.awaitility.kotlin.await11import org.awaitility.kotlin.untilAsserted12class InvoiceCreatedConsumerIT : BaseConsumerITTest() {13 companion object {14 const val INVOICE_CREATED_ASSET_EVENT_SAMPLE_1 = "invoice_created_1"15 const val DEFAULT_LOCK_KEY =16 "${Defaults.INVOICE_CREATED_EVENT}_2bb77c6e-53b4-11ec-bf63-0242ac130002_a96f0e6d-177e-4b66-9052-477a30a16054"17 }18 init {19 feature("A message processor for invoice created event") {20 val invoiceCreatedQueue = getQueueProperties().invoiceCreatedErpFacade.queueUrl21 // ignoring test22 xscenario("Should not send request when lock is already set") {23 clearCacheKeysByPrefix("${Defaults.INVOICE_CREATED_EVENT}_*")24 setLockForKey(DEFAULT_LOCK_KEY)25 setInvoiceDescriptionRolloutFlagTo(true)26 addGroupToRollout(UUID.fromString("063d9bc0-2242-4b76-aafa-60b7f3de72c8"))27 sendToQueue(28 invoiceCreatedQueue,29 INVOICE_CREATED_ASSET_EVENT_SAMPLE_130 )31 await.atMost(10, TimeUnit.SECONDS) untilAsserted {32 val createInvoiceRequest = mockWebServer.takeRequest()33 createInvoiceRequest.path shouldNotBe "/IFBTITRECEBER"34 }35 await.atMost(10, TimeUnit.SECONDS) untilAsserted {36 val count = getMessagesCountFromQueue(invoiceCreatedQueue)37 count shouldBeExactly 038 }39 }40 scenario("Should send create invoice request with correct payload") {41 clearCacheKeysByPrefix("${Defaults.INVOICE_CREATED_EVENT}_*")42 setMockWebServerResponse(isSuccess = true)43 setInvoiceDescriptionRolloutFlagTo(true)44 addGroupToRollout(UUID.fromString("063d9bc0-2242-4b76-aafa-60b7f3de72c8"))45 sendToQueue(46 invoiceCreatedQueue,47 INVOICE_CREATED_ASSET_EVENT_SAMPLE_148 )49 await.atMost(10, TimeUnit.SECONDS) untilAsserted {50 val count = getMessagesCountFromQueue(invoiceCreatedQueue)51 count shouldBeExactly 052 }53 await.atMost(10, TimeUnit.SECONDS) untilAsserted {54 val createInvoiceRequest = mockWebServer.takeRequest()55 createInvoiceRequest.path shouldBe "/IFBTITRECEBER"56 createInvoiceRequest.body.readUtf8() shouldMatchJsonResource ("/samples/invoice_created_totvs_request.json")57 }58 }59 }60 }61}...

Full Screen

Full Screen

OverlayTextElementTest.kt

Source:OverlayTextElementTest.kt Github

copy

Full Screen

1package fr.delphes.bot.overlay2import io.kotest.assertions.json.shouldEqualJson3import io.kotest.matchers.shouldBe4import kotlinx.serialization.decodeFromString5import kotlinx.serialization.encodeToString6import kotlinx.serialization.json.Json7import org.junit.jupiter.api.Test8internal class OverlayTextElementSerializationTest {9 private val serializer = Json {10 ignoreUnknownKeys = true11 isLenient = false12 encodeDefaults = true13 coerceInputValues = true14 }15 @Test16 internal fun deserialize() {17 serializer.decodeFromString<OverlayElement>(18 """19 {20 "type": "Text",21 "id": "0ea18104-c775-4741-acba-5c0944b554bb",22 "left": 273,23 "top": 308,24 "text": "my text"25 }26 """27 ).shouldBe(28 OverlayTextElement(29 "0ea18104-c775-4741-acba-5c0944b554bb",30 273,31 308,32 "my text"33 )34 )35 }36 @Test37 internal fun serialize() {38 serializer.encodeToString(39 OverlayTextElement(40 "0ea18104-c775-4741-acba-5c0944b554bb",41 273,42 308,43 "my text"44 )45 ).shouldEqualJson(46 """47 {48 "id": "0ea18104-c775-4741-acba-5c0944b554bb",49 "top": 308,50 "left": 273,51 "text": "my text"52 }53 """54 )55 }56}...

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 methods in keys

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful