Skip to content

Commit

Permalink
✅ add additional test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
oharaandrew314 committed Nov 20, 2023
1 parent 0e4c188 commit d70a83e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,20 @@ package io.andrewohara.dynamokt
import software.amazon.awssdk.enhanced.dynamodb.TableSchema
import software.amazon.awssdk.enhanced.dynamodb.mapper.StaticImmutableTableSchema
import kotlin.reflect.KClass
import kotlin.reflect.KVisibility
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.full.primaryConstructor


fun <Item: Any> DataClassTableSchema(dataClass: KClass<Item>): TableSchema<Item> {
val props = dataClass.declaredMemberProperties.sortedBy { it.name }
val params = dataClass.primaryConstructor!!.parameters.sortedBy { it.name }
val constructor = dataClass.primaryConstructor
?.takeIf { it.visibility == KVisibility.PUBLIC }
?: error("${dataClass.simpleName} must have a public primary constructor")

require(dataClass.isData) { "$dataClass must be a data class" }
require(props.size == params.size) { "$dataClass properties MUST all be declared in the constructor" }
val constructor = requireNotNull(dataClass.primaryConstructor) { "$dataClass must have a primary constructor"}
require(props.size == params.size) { "${dataClass.simpleName} properties MUST all be declared in the constructor" }

return StaticImmutableTableSchema.builder(dataClass.java, ImmutableDataClassBuilder::class.java)
.newItemBuilder({ ImmutableDataClassBuilder(constructor) }, { it.build() as Item })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import org.junit.jupiter.api.Test
import software.amazon.awssdk.core.SdkBytes
import software.amazon.awssdk.services.dynamodb.model.AttributeValue
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.nio.ByteBuffer

class DataClassTableSchemaTest {
Expand Down Expand Up @@ -99,4 +100,20 @@ class DataClassTableSchemaTest {
DataClassTableSchema(Person::class)
}
}

@Test
fun `non-data class throws error`() {
shouldThrow<IllegalArgumentException> {
DataClassTableSchema(String::class)
}.message shouldBe "class kotlin.String must be a data class"
}

@Test
fun `data class with private constructor`() {
data class Person private constructor(val name: String)

shouldThrow<IllegalStateException> {
DataClassTableSchema(Person::class)
}.message shouldBe "Person must have a public primary constructor"
}
}

0 comments on commit d70a83e

Please sign in to comment.