gradlegradle-plugingradle-kotlin-dslgradle-task

In gradle kotlin dsl, how to call a dynamic test extension?


I'm trying to add a new configuration option when using the gradle ScalaTest plugin:

https://github.com/maiflai/gradle-scalatest

In its source code, the config was injected into the Test class as a dynamic extension:

    static void configure(Test test) {
        ...
        Map<String, ?> config = [:]
        test.extensions.add(ScalaTestAction.CONFIG, config)
        test.extensions.add("config", { String name, value -> config.put(name, value) })
        test.extensions.add("configMap", { Map<String, ?> c -> config.putAll(c) })
        ...
    }

If using groovy as the dsl, calling this property is easy:

test {
    configMap([
        'db.name': 'testdb'
        'server': '192.168.1.188'
        ])
}

unfortunately the kotlin dsl can't use this method due to static typing, when being invoked as a test plugin, it is clearly visible within the test scope, e.g. when using extensions.getByName:

tasks {

    test {

        val map = extensions.getByName("configMap")
        println(map)
    }
}

It yields the following output:

...


> Configure project :
com.github.maiflai.ScalaTestPlugin$_configure_closure6@45c21cac

But there is no way to retrieve or assert its type in compile time, and it ends up being useless (unless reflection is used, which is against the design philosophy of kotlin dsl). Is there a easy way for kotlin dsl to achieve the same?


Solution

  • I saw in the Scala test gradle plugin that the dynamic extension is defined like this:

    test.extensions.add("configMap", { Map<String, ?> c -> config.putAll(c) })
    

    The com.github.maiflai.ScalaTestPlugin$_configure_closure6@45c21cac you saw should be a closure of type (Map<String, Any>) -> Unit, which means you can do that. We'll have to change the map values so let's assume that it's also mutable.

    extensions.getByName("configMap").closureOf<MutableMap<String, Any?>> {
        this["db.name"] = "testdb"
        this["server"] = "192.168.1.188"
    }
    

    This builds fine but I don't have Scala installed and never used Scala test. I have no idea if it actually works, so please tell me.