1 /* <lambda>null2 * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 package kotlinx.serialization 6 7 import kotlinx.serialization.internal.* 8 import kotlinx.serialization.modules.* 9 import kotlin.reflect.* 10 import kotlin.test.* 11 import kotlin.test.Test 12 13 class CachingTest { 14 @Test 15 fun testCache() { 16 var factoryCalled = 0 17 18 val cache = createCache { 19 factoryCalled += 1 20 it.serializerOrNull() 21 } 22 23 repeat(10) { 24 cache.get(typeOf<String>().kclass()) 25 } 26 27 assertEquals(1, factoryCalled) 28 } 29 30 @Test 31 fun testParameterizedCache() { 32 var factoryCalled = 0 33 34 val cache = createParametrizedCache { clazz, types -> 35 factoryCalled += 1 36 val serializers = EmptySerializersModule().serializersForParameters(types, true)!! 37 clazz.parametrizedSerializerOrNull(serializers) { types[0].classifier } 38 } 39 40 repeat(10) { 41 cache.get(typeOf<Map<*, *>>().kclass(), listOf(typeOf<String>(), typeOf<String>())) 42 } 43 44 assertEquals(1, factoryCalled) 45 } 46 47 @Serializable 48 class Target 49 50 @Test 51 fun testJvmIntrinsics() { 52 val ser1 = Target.serializer() 53 assertFalse(SERIALIZERS_CACHE.isStored(Target::class), "Cache shouldn't have values before call to serializer<T>()") 54 val ser2 = serializer<Target>() 55 assertFalse( 56 SERIALIZERS_CACHE.isStored(Target::class), 57 "Serializer for Target::class is stored in the cache, which means that runtime lookup was performed and call to serializer<Target> was not intrinsified." + 58 "Check that compiler plugin intrinsics are enabled and working correctly." 59 ) 60 val ser3 = serializer(typeOf<Target>()) 61 assertTrue(SERIALIZERS_CACHE.isStored(Target::class), "Serializer should be stored in cache after typeOf-based lookup") 62 } 63 64 @Serializable 65 class Target2 66 67 inline fun <reified T : Any> indirect(): KSerializer<T> = serializer<T>() 68 69 @Test 70 fun testJvmIntrinsicsIndirect() { 71 val ser1 = Target2.serializer() 72 assertFalse(SERIALIZERS_CACHE.isStored(Target2::class), "Cache shouldn't have values before call to serializer<T>()") 73 val ser2 = indirect<Target2>() 74 assertFalse( 75 SERIALIZERS_CACHE.isStored(Target2::class), 76 "Serializer for Target2::class is stored in the cache, which means that runtime lookup was performed and call to serializer<Target2> was not intrinsified." + 77 "Check that compiler plugin intrinsics are enabled and working correctly." 78 ) 79 } 80 } 81