Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fill in placeholder values for TemplateString #183

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/*
* Copyright 2025, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package io.spine.test

import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.maps.shouldContainExactly
import io.kotest.matchers.shouldBe
import io.spine.test.tools.validate.RequiredPlaceholders
import io.spine.validate.ValidationException
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows

@DisplayName("Error message placeholders should have values")
internal class PlaceholdersSomeTest {

@Nested
inner class `for '(required)' option` {

@Test
fun `with the default error message`() {
val exception = assertThrows<ValidationException> {
RequiredPlaceholders.newBuilder()
.setValueCustom("something")
.build()
}
exception.constraintViolations shouldHaveSize 1
val template = exception.constraintViolations[0].message
template.withPlaceholders shouldBe "The field `\${parent.type}.\${field.path}` of the type `\${field.type}` must have a value."
template.placeholderValueMap shouldContainExactly mapOf(
"field.path" to "value_default",
"field.type" to "string",
"parent.type" to "spine.test.tools.validate.RequiredPlaceholders"
)
}

@Test
fun `with the custom error message`() {
val exception = assertThrows<ValidationException> {
RequiredPlaceholders.newBuilder()
.setValueDefault("something")
.build()
}
exception.constraintViolations shouldHaveSize 1
val template = exception.constraintViolations[0].message
template.withPlaceholders shouldBe "Custom for (required)."
template.placeholderValueMap shouldContainExactly mapOf(
"field.path" to "value_default",
"field.type" to "string",
"parent.type" to "spine.test.tools.validate.RequiredPlaceholders"
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright 2024, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
syntax = "proto3";

package spine.test.tools.validate;

import "spine/options.proto";

option (type_url_prefix) = "type.spine.io";
option java_package = "io.spine.test.tools.validate";
option java_outer_classname = "PlaceholdersProto";
option java_multiple_files = true;

message RequiredPlaceholders {

string value_default = 1 [(required) = true];
string value_custom = 2 [(required) = true, (if_missing).error_msg = "Custom for (required)."];
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import com.squareup.javapoet.CodeBlock
import io.spine.logging.WithLogging
import io.spine.protodata.java.Expression
import io.spine.tools.java.codeBlock
import io.spine.validation.ErrorMessage
import io.spine.validation.Rule.KindCase.COMPOSITE
import io.spine.validation.Rule.KindCase.MESSAGE_WIDE
import io.spine.validation.Rule.KindCase.SIMPLE
Expand Down Expand Up @@ -98,7 +97,7 @@ internal abstract class CodeGenerator(
/**
* Forms an error message for the found violation.
*/
abstract fun error(): ErrorMessage
abstract fun error(): Pair<String, Map<Expression<*>, Expression<*>>>

/**
* Constructs code which creates a `ConstrainViolation` and puts it into a list of violations.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ import io.spine.string.titleCase
import io.spine.tools.java.codeBlock
import io.spine.tools.java.methodSpec
import io.spine.validate.ConstraintViolation
import io.spine.validation.ErrorMessage
import javax.lang.model.element.Modifier

/**
Expand Down Expand Up @@ -146,7 +145,7 @@ internal class DistributingGenerator(
return MethodCall(violationsName, "isEmpty")
}

override fun error(): ErrorMessage =
override fun error(): Pair<String, Map<Expression<*>, Expression<*>>> =
delegate.error()

override fun createViolation(): CodeBlock = codeBlock {
Expand Down
15 changes: 13 additions & 2 deletions java/src/main/kotlin/io/spine/validation/java/ErrorMessages.kt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import io.spine.protodata.java.call
import io.spine.protodata.java.newBuilder
import io.spine.protodata.ast.isList
import io.spine.protodata.ast.isMap
import io.spine.protodata.java.mapExpression
import io.spine.protodata.java.packToAny
import io.spine.validate.ConstraintViolation
import io.spine.validate.TemplateString
Expand Down Expand Up @@ -88,7 +89,7 @@ public fun ErrorMessage.createCompositeViolation(
return addViolation(violation, violationsList)
}

private fun addViolation(
public fun addViolation(
violation: Expression<ConstraintViolation>,
violationsList: Expression<MutableList<ConstraintViolation>>
): CodeBlock = CodeBlock.builder()
Expand All @@ -100,9 +101,19 @@ private fun ErrorMessage.buildViolation(
field: Field?,
fieldValue: Expression<*>?,
ignoreCardinality: Boolean = false
) = buildViolation(this.toString(), type, field, fieldValue, ignoreCardinality)

public fun buildViolation(
errorMessage: String,
type: TypeName,
field: Field?,
fieldValue: Expression<*>?,
ignoreCardinality: Boolean = false,
placeholders: Map<Expression<*>, Expression<*>> = emptyMap() // TODO: Fix in ProtoData.
): Expression<ConstraintViolation> {
val message = ClassName(TemplateString::class).newBuilder()
.chainSet("withPlaceholders", Literal(this))
.chainSet("withPlaceholders", Literal(errorMessage))
.chainPutAll("placeholderValue", mapExpression(ClassName(String::class), ClassName(String::class), placeholders))
.chainBuild<TemplateString>()
var violationBuilder = ClassName(ConstraintViolation::class).newBuilder()
.chainSet("message", message)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@

package io.spine.validation.java

import com.squareup.javapoet.CodeBlock
import io.spine.protodata.ast.Cardinality.CARDINALITY_SINGLE
import io.spine.protodata.ast.OneofName
import io.spine.protodata.java.Expression
import io.spine.protodata.java.field
import io.spine.validation.ErrorMessage

/**
* A code generator for the `(is_required)` constraint.
Expand All @@ -54,9 +54,18 @@ internal class RequiredOneofGenerator(
return Expression("$numberGetter != 0")
}

override fun error() =
ErrorMessage.forRule(rule.errorMessage)
override fun error() = rule.errorMessage to emptyMap<Expression<*>, Expression<*>>()

override fun createViolation() =
error().createViolation(ctx)
override fun createViolation(): CodeBlock {
val error = error()
val violation = buildViolation(
error.first,
ctx.validatedType,
ctx.fieldFromSimpleRule,
ctx.fieldOrElement,
ignoreCardinality = ctx.isElement,
error.second
)
return addViolation(violation, ctx.violationList)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,11 @@ import io.spine.protodata.ast.PrimitiveType.TYPE_STRING
import io.spine.protodata.ast.Type
import io.spine.protodata.ast.isList
import io.spine.protodata.ast.isMap
import io.spine.protodata.ast.qualifiedName
import io.spine.protodata.ast.typeName
import io.spine.protodata.java.ClassName
import io.spine.protodata.java.Expression
import io.spine.protodata.java.StringLiteral
import io.spine.protodata.java.call
import io.spine.protodata.value.Value
import io.spine.string.shortly
Expand All @@ -45,7 +48,6 @@ import io.spine.validation.ComparisonOperator.GREATER_THAN
import io.spine.validation.ComparisonOperator.LESS_OR_EQUAL
import io.spine.validation.ComparisonOperator.LESS_THAN
import io.spine.validation.ComparisonOperator.NOT_EQUAL
import io.spine.validation.ErrorMessage
import io.spine.validation.SimpleRule
import io.spine.validation.SimpleRule.OperatorKindCase.CUSTOM_OPERATOR
import io.spine.validation.SimpleRule.OperatorKindCase.OPERATOR
Expand Down Expand Up @@ -142,18 +144,32 @@ internal open class SimpleRuleGenerator(ctx: GenerationContext) : CodeGenerator(
PRIMITIVE_COMPARISON_OPS
}

override fun error(): ErrorMessage {
val actualValue = ClassName(String::class)
override fun error(): Pair<String, Map<Expression<*>, Expression<*>>> {
val fieldValue = ClassName(String::class)
.call<String>("valueOf", ctx.fieldOrElement!!)
return ErrorMessage.forRule(
rule.errorMessage,
actualValue.toCode(),
otherValue?.toCode()
val fieldPath = rule.field.value
val fieldType = ctx.simpleRuleField.type.typeName.qualifiedName
val parentType = ctx.validatedType.qualifiedName
return rule.errorMessage to mapOf(
StringLiteral("field.path") to StringLiteral(fieldPath),
StringLiteral("parent.type") to StringLiteral(parentType),
StringLiteral("field.type") to StringLiteral(fieldType),
StringLiteral("field.value") to fieldValue
)
}

override fun createViolation(): CodeBlock =
error().createViolation(ctx)
override fun createViolation(): CodeBlock {
val error = error()
val violation = buildViolation(
error.first,
ctx.validatedType,
ctx.fieldFromSimpleRule,
ctx.fieldOrElement,
ignoreCardinality = ctx.isElement,
error.second
)
return addViolation(violation, ctx.violationList)
}
}

internal fun generatorForSimple(ctx: GenerationContext): CodeGenerator {
Expand Down
Loading