Sunday, January 21, 2018

Kotlin - Reified type parameters sample

This post walks through a sample that demonstrates Kotlin's ability to cleverly reify generic type parameters.

So consider first a world where Kotlin does not support this feature, if we were using the Jackson library to convert a JSON to a Map with String based keys and Integer based values, I would use a code along these lines:

@Test
fun `sample parameterized retrieval raw object mapper`() {
    val objectMapper = ObjectMapper()
    val map: Map<String, Int> = objectMapper.readValue("""
        | {
        |   "key1": 1,
        |   "key2": 2,
        |   "key3": 3
        | }
        """.trimMargin(), object : TypeReference<Map<String, Int>>() {})

    assertThat(map).isEqualTo(mapOf("key1" to 1, "key2" to 2, "key3" to 3))
}

TypeReference used above implements a pattern called Super type token which allows the type of a parameterized type to be captured by sub-classing. Note the ugly way to creating an anonymous sub-class in Kotlin.

object : TypeReference<Map<String, Int>>() {}


What I would like to do is to invoke the ObjectMapper the following way instead:

@Test
fun `sample parameterized retrieval`() {
    val om = ObjectMapper()
    val map: Map<String, Int> = om.readValue("""
        | {
        |   "key1": 1,
        |   "key2": 2,
        |   "key3": 3
        | }
        """.trimMargin())

    assertThat(map).isEqualTo(mapOf("key1" to 1, "key2" to 2, "key3" to 3))
}

The generic type parameter is being inferred based on the type of what is to be returned (the left-hand side).


This can be achieved using an extension function on ObjectMapper which looks like this:

inline fun <reified T> ObjectMapper.readValue(s: String): T = 
        this.readValue(s, object : TypeReference<T>() {})

The inline function is the heart of the support for being able to reify generic type parameter here - after compilation, the function would be expanded out into any place this function is called and thus the second version is exactly same as the first version of the test but reads far better than before.


Note that Jackson already implements these Kotlin extension functions in the excellent jackson-module-kotlin library.

Thursday, January 4, 2018

Spring Based Application - Migrating to Junit 5

This is a quick write-up on migrating a Gradle based Spring Boot app from Junit 4 to the shiny new Junit 5. Junit 4 tests continue to work with Junit 5 Test Engine abstraction which provides support for tests written in different programming models, in this instance, Junit 5 supports a Vintage Test Engine with the ability to run JUnit 4 tests.


Here is a sample project with JUnit 5 integrations already in place along with sample tests in Junit 4 and Junit 5 - https://github.com/bijukunjummen/boot2-with-junit5-sample

Sample Junit 4 candidate test

As a candidate project, I have a Spring Boot 2 app with tests written in Kotlin using Junit 4 as the testing framework. This is how a sample test looks with all dependencies explicitly called out. It uses the Junit4's @RunWith annotation to load up the Spring Context:

import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.reactive.server.WebTestClient
import java.nio.charset.StandardCharsets

@RunWith(SpringRunner::class)
@WebFluxTest(controllers = arrayOf(RouteConfig::class))
class SampleJunit4Test {

    @Autowired
    lateinit var webTestClient: WebTestClient

    @Test
    fun `get of hello URI should return Hello World!`() {
        webTestClient.get()
                .uri("/hello")
                .exchange()
                .expectStatus().isOk
                .expectBody()
                .consumeWith({ m ->
                    assertThat(String(m.responseBodyContent, StandardCharsets.UTF_8)).isEqualTo("Hello World!")
                })

    }

}

the Junit 4 dependencies are pulled in transitively via "spring-boot-starter-test" module:

testCompile('org.springframework.boot:spring-boot-starter-test')


Junit 5 migration


The first step to do is to pull in the Junit 5 dependencies along with Gradle plugin which enables running the tests:

Plugin:

buildscript {
 dependencies {
  ....
  classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.2'
 }
}
apply plugin: 'org.junit.platform.gradle.plugin'

Dependencies:

testCompile("org.junit.jupiter:junit-jupiter-api")
testRuntime("org.junit.jupiter:junit-jupiter-engine")
testRuntime("org.junit.vintage:junit-vintage-engine:4.12.2")

With these changes in place, all the Junit 4 tests will continue to run both in IDE and when the Gradle build is executed and at this point, the tests itself can be slowly migrated over.

The test which I had shown before looks like this with Junit 5 Jupiter which provides the programming model for the tests:

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.springframework.test.web.reactive.server.WebTestClient
import java.nio.charset.StandardCharsets

@ExtendWith(SpringExtension::class)
@WebFluxTest(controllers = arrayOf(RouteConfig::class))
class SampleJunit5Test {

    @Autowired
    lateinit var webTestClient: WebTestClient

    @Test
    fun `get of hello URI should return Hello World!`() {
        webTestClient.get()
                .uri("/hello")
                .exchange()
                .expectStatus().isOk
                .expectBody()
                .consumeWith({ m ->
                    assertEquals("Hello World!", String(m.responseBodyContent, StandardCharsets.UTF_8))
                })
    }

}

Note that now instead of using JUnit 4 @RunWith annotation, I am using the @ExtendWith annotation and providing SpringExtension as a parameter which is responsible for loading up the Spring Context like before. Rest of the Spring annotations will continue to work with JUnit 5. This way tests can be slowly moved over from JUnit 4 to JUnit 5.


Caveats

Not everything is smooth though, there are a few issues in migrating from JUnit 4 to JUnit 5, the biggest of them is likely the support for JUnit @Rule and @ClassRule annotation and the JUnit 5 documentation does go into details on how it can be mitigated.

Monday, January 1, 2018

Kotlin - Tuple type

It is very simple to write a Tuple type with the expressiveness of Kotlin. My objective expressed in tests is the following:

1. Be able to define a Tuple of up to 5 elements and be able to retrieve the elements using an index like placeholder, in a test expressed with 2 elements like this:

val tup = Tuple("elem1", "elem2")
assertThat(tup._1).isEqualTo("elem1")
assertThat(tup._2).isEqualTo("elem2")

2. Be able to de-construct the constituent types along the following lines:
val tup = Tuple("elem1", "elem2")
val (e1, e2) = tup

assertThat(e1).isEqualTo("elem1")
assertThat(e2).isEqualTo("elem2")


Implementation

The implementation for a tuple of 2 elements is the following in its entirity:

data class Tuple2<out A, out B>(val _1: A, val _2: B)

A Kotlin data class provides all the underlying support of being able to retrieve the individual fields and the ability to destructure using an expression like this:

val (e1, e2) = Tuple2("elem1", "elem2")

All that I need to do at this point is provide a helper that creates a tuple of appropriate size based on the number of arguments provided which I have defined as follows:

object Tuple {
    operator fun <A> invoke(_1: A): Tuple1<A> = Tuple1(_1)
    operator fun <A, B> invoke(_1: A, _2: B): Tuple2<A, B> = Tuple2(_1, _2)
    operator fun <A, B, C> invoke(_1: A, _2: B, _3: C): Tuple3<A, B, C> = Tuple3(_1, _2, _3)
    operator fun <A, B, C, D> invoke(_1: A, _2: B, _3: C, _4: D): Tuple4<A, B, C, D> = Tuple4(_1, _2, _3, _4)
    operator fun <A, B, C, D, E> invoke(_1: A, _2: B, _3: C, _4: D, _5: E): Tuple5<A, B, C, D, E> = Tuple5(_1, _2, _3, _4, _5)
}

which allows me to define tuples of different sizes using a construct which looks like this:

val tup2 = Tuple("elem1", "elem2")
val tup3 = Tuple("elem1", "elem2", "elem3")
val tup4 = Tuple("elem1", "elem2", "elem3", "elem4")

A little more twist, typically a Pair type is an alias for Tuple with 2 elements and Triple is an alias for a Tuple of 3 elements, this can be trivially defined in Kotlin the following way:

typealias Pair<A, B> = Tuple2<A, B>
typealias Triple<A, B, C> = Tuple3<A, B, C>

Simple indeed! a more filled-in sample is available in my github repo here - https://github.com/bijukunjummen/kfun