Skip to content

Using .at(path).toValue errors if any config files are missing the entry #76

@dtanner

Description

@dtanner

Test case here: https://github.com/dtanner/konf-question/blob/get_at_question/src/test/kotlin/question/ConfigTest.kt#L32

I'd like to avoid using ConfigSpec classes, and instead use the toValue() function to instantiate configuration directly into target classes. For the case where I want to grab a single property, this works fine if the config files I'm loading from all contain all the property I'm looking for, but if any of them don't, it errors. e.g. relevant snippets from the linked test case:

config1.conf:

server {
  host = "0.0.0.0"
}

config2-missing-host.conf:

server {
  # if i uncomment the host here, things work as expected.
  # host = "1.1.1.1"
}

test:

package question

import com.uchuhimo.konf.Config
import com.uchuhimo.konf.source.hocon
import com.uchuhimo.konf.toValue
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test

class ConfigTest {

    data class ServerConfig(val host: String)

    @Test
    fun `foo hocon`() {
        val config = Config()
            .from.hocon.resource("config1.conf")
            .from.hocon.resource("config2-missing-host.conf", optional = true)

        val serverConfig = config.at("server").toValue<ServerConfig>()
        serverConfig.host shouldBe "0.0.0.0"

        /*
        The following line throws:

        item root is unset
        com.uchuhimo.konf.UnsetValueException: item root is unset
        at app//com.uchuhimo.konf.BaseConfig.getOrNull(BaseConfig.kt:187)
        at app//com.uchuhimo.konf.BaseConfig.getOrNull$default(BaseConfig.kt:179)
        at app//com.uchuhimo.konf.BaseConfig.get(BaseConfig.kt:159)
        at app//com.uchuhimo.konf.BaseConfig$property$1.getValue(BaseConfig.kt:527)
         */
        val host = config.at("server.host").toValue<String>()
        host shouldBe "0.0.0.0"
    }

}

Is there a different/better way to get at individual properties and objects without using Spec files? Or is this reasonable to work as expected? Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions